<commit_before>#include "Text.h"

namespace hm
{
	Text::Text()
	{
		// Initialize.
		font = NULL;
		sdltext = NULL;
		text = "Hume Library";
	}

	Text::Text(Font *font)
	{
		// Initialize and set default text.
		this->font = font;
		sdltext = NULL;
		text = "Hume Library";
		std::cout << "constructor invoked and calling updateSurface()" << std::endl;
		updateSurface();
	}

	Text::Text(std::string text, Font *font)
	{
		// Initialize and set custom text.
		this->font = font;
		sdltext = NULL;
		this->text = text;
		updateSurface();
	}

	SDL_Surface* Text::getSurface()
	{
		return sdltext;
	}

	void Text::setText(std::string text)
	{
		this->text = text;
		updateSurface();
	}

	std::string Text::getText()
	{
		return text;
	}

	void Text::setPosition(int x, int y)
	{
		position.x = x;
		position.y = y;

		return;
	}

	SDL_Rect* Text::getPosition()
	{
		return &position;
	}

	void Text::updateSurface()
	{
		// See if TTF_WasInit().
		if(TTF_WasInit() == 0)
		{
			std::cout << "SDL_ttf was not initialized. Cannot update surface." << std::endl;
			return;
		}
		else
			std::cout << "SDL_ttf was initialized. Continuing..." << std::endl;

		// Check if the font is null.
		if(font == NULL)
		{
			std::cout << "Cannot update surface. Font is nulled." << std::endl;
			return;
		}

		// Output.
		std::cout << "Font: " << font << std::endl;
		std::cout << "Text: " << text.c_str() << std::endl;
		std::cout << "FGColor: " << font->getFgColor().r << ", " << font->getFgColor().g << ", " << font->getFgColor().b << std::endl;
		std::cout << "BGColor: " << font->getBgColor().r << ", " << font->getBgColor().g << ", " << font->getBgColor().b << std::endl;

		if(font->getRenderMode() == SOLID)
		{
			std::cout << "Rendering text solid..." << std::endl;
			sdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor());
		}
		if(font->getRenderMode() == SHADED)
		{
			std::cout << "Rendering text shaded..." << std::endl;
			sdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor());
		}
		if(font->getRenderMode() == BLENDED)
		{
			std::cout << "Rendering text blended..." << std::endl;
			sdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor());
		}

		std::cout << "Surface is located at " << sdltext << "." << std::endl;

		return;
	}
}
<commit_msg>Got rid of output of TTF_RenderText_*() parameters.<commit_after>#include "Text.h"

namespace hm
{
	Text::Text()
	{
		// Initialize.
		font = NULL;
		sdltext = NULL;
		text = "Hume Library";
	}

	Text::Text(Font *font)
	{
		// Initialize and set default text.
		this->font = font;
		sdltext = NULL;
		text = "Hume Library";
		std::cout << "constructor invoked and calling updateSurface()" << std::endl;
		updateSurface();
	}

	Text::Text(std::string text, Font *font)
	{
		// Initialize and set custom text.
		this->font = font;
		sdltext = NULL;
		this->text = text;
		updateSurface();
	}

	SDL_Surface* Text::getSurface()
	{
		return sdltext;
	}

	void Text::setText(std::string text)
	{
		this->text = text;
		updateSurface();
	}

	std::string Text::getText()
	{
		return text;
	}

	void Text::setPosition(int x, int y)
	{
		position.x = x;
		position.y = y;

		return;
	}

	SDL_Rect* Text::getPosition()
	{
		return &position;
	}

	void Text::updateSurface()
	{
		// See if TTF_WasInit().
		if(TTF_WasInit() == 0)
		{
			std::cout << "SDL_ttf was not initialized. Cannot update surface." << std::endl;
			return;
		}
		else
			std::cout << "SDL_ttf was initialized. Continuing..." << std::endl;

		// Check if the font is null.
		if(font == NULL)
		{
			std::cout << "Cannot update surface. Font is nulled." << std::endl;
			return;
		}

		// Output.
		std::cout << "Font: " << font << std::endl;
        std::cout << "Text: " << text.c_str() << std::endl;

		if(font->getRenderMode() == SOLID)
		{
			std::cout << "Rendering text solid..." << std::endl;
			sdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor());
		}
		if(font->getRenderMode() == SHADED)
		{
			std::cout << "Rendering text shaded..." << std::endl;
			sdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor());
		}
		if(font->getRenderMode() == BLENDED)
		{
			std::cout << "Rendering text blended..." << std::endl;
			sdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor());
		}

		std::cout << "Surface is located at " << sdltext << "." << std::endl;

		return;
	}
}
<|endoftext|>


<commit_before>/*
 * File:   Zone.cpp
 * Author: Aztyu
 *
 * Created on 22 décembre 2014, 15:50
 */

#include "Zone.h"

using namespace std;

Zone::Zone(char* name){
    zone_name = name;
    tableau.reserve(10);

    for(int i=0; i < 8; i++){
        type_number[i] = 0;
    }

    cout << "Creation de la zone " << zone_name << endl;
}

Zone::Zone(const Zone& orig) {
}

Zone::~Zone() {
}

void Zone::addObjet(Objet* objet){
    tableau.push_back(objet);
}

void Zone::removeObjet(int index){
    tableau[index]->getSceneNode()->remove();
    delete tableau[index]->getPointer();
    tableau.erase(tableau.begin()+index);
}

void Zone::createObjet(object form){
    char name[50];
    string type = "ressources/";
    switch((int)form){
        case 0:
            if(type_number[0] > 0){
                sprintf (name, "Rectangle%d", type_number[0]);
            }else{
                sprintf (name, "Rectangle");
            }
            type += "rectangle";
            type_number[0]++;
            break;
        case 1:
            if(type_number[1] > 0){
                sprintf (name, "Line%d", type_number[1]);
            }else{
                sprintf (name, "Line");
            }
            type += "line";
            type_number[1]++;
            break;
        case 2:
            if(type_number[2] > 0){
                sprintf (name, "Circle%d", type_number[2]);
            }else{
                sprintf (name, "Circle");
            }
            type += "circle";
            type_number[2]++;
            break;
        case 3:
            if(type_number[3] > 0){
                sprintf (name, "Trapeze%d", type_number[3]);
            }else{
                sprintf (name, "Trapeze");
            }
            type += "trapeze";
            type_number[3]++;
            break;
        case 4:
            if(type_number[4] > 0){
                sprintf (name, "Cube%d", type_number[4]);
            }else{
                sprintf (name, "Cube");
            }
            type += "cube";
            type_number[4]++;
            break;
        case 5:
            if(type_number[5] > 0){
                sprintf (name, "Pyramid%d", type_number[5]);
            }else{
                sprintf (name, "Pyramid");
            }
            type += "pyramide";
            type_number[5]++;
            break;
        case 6:
            if(type_number[6] > 0){
                sprintf (name, "Sphere%d", type_number[6]);
            }else{
                sprintf (name, "Sphere");
            }
            type += "sphere";
            type_number[6]++;
            break;
        case 7:
            if(type_number[7] > 0){
                sprintf (name, "Cylinder%d", type_number[7]);
            }else{
                sprintf (name, "Cylinder");
            }
            type += "cylinder";
            type_number[7]++;
            break;
    }
    type += ".obj";
    tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name));
    wchar_t buffer [100];
    swprintf( buffer, 100, L"%s", name);
    //box_global->addItem(buffer);
}

int Zone::getObjectCount(){
    return tableau.size();
}

void Zone::printZone(){
    cout << "La zone s'appelle " << zone_name << endl;
    for(int i=0; i < tableau.size(); i++){
        tableau[i]->printObjet();
    }
}

Objet* Zone::getObjetPointer(int index){
    if(index >= 0 && index < tableau.size()){
        return tableau[index];
    }else{
        return 0;
    }
}

Zone* Zone::getPointer(){
    return this;
}

<commit_msg>forgot one file<commit_after>/*
 * File:   Zone.cpp
 * Author: Aztyu
 *
 * Created on 22 décembre 2014, 15:50
 */

#include "Zone.h"

using namespace std;

Zone::Zone(char* name, irr::scene::ISceneManager* scene){
    zone_name = name;
    tableau.reserve(10);

    for(int i=0; i < 8; i++){
        type_number[i] = 0;
    }
    current_scene = scene;

    cout << "Creation de la zone " << zone_name << endl;
}

Zone::Zone(const Zone& orig) {
}

Zone::~Zone() {
}

void Zone::addObjet(Objet* objet){
    tableau.push_back(objet);
}

void Zone::removeObjet(int index){
    tableau[index]->getSceneNode()->remove();
    delete tableau[index]->getPointer();
    tableau.erase(tableau.begin()+index);
}

void Zone::createObjet(object form){
    char name[50];
    string type = "ressources/";
    switch((int)form){
        case 0:
            if(type_number[0] > 0){
                sprintf (name, "Rectangle%d", type_number[0]);
            }else{
                sprintf (name, "Rectangle");
            }
            type += "rectangle";
            type_number[0]++;
            break;
        case 1:
            if(type_number[1] > 0){
                sprintf (name, "Line%d", type_number[1]);
            }else{
                sprintf (name, "Line");
            }
            type += "line";
            type_number[1]++;
            break;
        case 2:
            if(type_number[2] > 0){
                sprintf (name, "Circle%d", type_number[2]);
            }else{
                sprintf (name, "Circle");
            }
            type += "circle";
            type_number[2]++;
            break;
        case 3:
            if(type_number[3] > 0){
                sprintf (name, "Trapeze%d", type_number[3]);
            }else{
                sprintf (name, "Trapeze");
            }
            type += "trapeze";
            type_number[3]++;
            break;
        case 4:
            if(type_number[4] > 0){
                sprintf (name, "Cube%d", type_number[4]);
            }else{
                sprintf (name, "Cube");
            }
            type += "cube";
            type_number[4]++;
            break;
        case 5:
            if(type_number[5] > 0){
                sprintf (name, "Pyramid%d", type_number[5]);
            }else{
                sprintf (name, "Pyramid");
            }
            type += "pyramide";
            type_number[5]++;
            break;
        case 6:
            if(type_number[6] > 0){
                sprintf (name, "Sphere%d", type_number[6]);
            }else{
                sprintf (name, "Sphere");
            }
            type += "sphere";
            type_number[6]++;
            break;
        case 7:
            if(type_number[7] > 0){
                sprintf (name, "Cylinder%d", type_number[7]);
            }else{
                sprintf (name, "Cylinder");
            }
            type += "cylinder";
            type_number[7]++;
            break;
    }
    type += ".obj";
    tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name));
    //wchar_t buffer [100];
    //swprintf( buffer, 100, L"%s", name);
    //box_global->addItem(buffer);
}

int Zone::getObjectCount(){
    return tableau.size();
}

void Zone::printZone(){
    cout << "La zone s'appelle " << zone_name << endl;
    for(int i=0; i < tableau.size(); i++){
        tableau[i]->printObjet();
    }
}

Objet* Zone::getObjetPointer(int index){
    if(index >= 0 && index < tableau.size()){
        return tableau[index];
    }else{
        return 0;
    }
}

Zone* Zone::getPointer(){
    return this;
}

<|endoftext|>


<commit_before>/*
Copyright 2014-2015 Adam Grandquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#include "ReQL.hpp"

#include <cstring>

namespace ReQL {

Result::Result() : type(REQL_R_JSON) {}

Result::Result(const Result &other) {
  value.copy(other.value, type);
}

Result::Result(Result &&other) {
  value.move(std::move(other.value), type);
}

Result::~Result() {
  value.release(type);
}

Result &
Result::operator=(const Result &other) {
  if (this != &other) {
    type = other.type;
    value.copy(other.value, type);
  }
  return *this;
}

Result &
Result::operator=(Result &&other) {
  if (this != &other) {
    type = std::move(other.type);
    value.move(std::move(other.value), type);
  }
  return *this;
}

Result::JSON_Value::JSON_Value() {
  std::memset(this, 0, sizeof(Result::JSON_Value));
}

void
Result::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) {
  release(a_type);
  switch (a_type) {
    case REQL_R_ARRAY: {
      array = new std::vector<Result>(*other.array);
      break;
    }
    case REQL_R_BOOL: {
      boolean = new bool(*other.boolean);
      break;
    }
    case REQL_R_NUM: {
      num = new double(*other.num);
      break;
    }
    case REQL_R_OBJECT: {
      object = new std::map<std::string, Result>(*other.object);
      break;
    }
    case REQL_R_STR: {
      string = new std::string(*other.string);
      break;
    }
    case REQL_R_NULL:
    case REQL_R_JSON:
    case REQL_R_REQL: break;
  }
}

void
Result::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) {
  release(a_type);
  switch (a_type) {
    case REQL_R_ARRAY: {
      array = std::move(other.array);
      break;
    }
    case REQL_R_BOOL: {
      boolean = std::move(other.boolean);
      break;
    }
    case REQL_R_NUM: {
      num = std::move(other.num);
      break;
    }
    case REQL_R_OBJECT: {
      object = std::move(other.object);
      break;
    }
    case REQL_R_STR: {
      string = std::move(other.string);
      break;
    }
    case REQL_R_NULL:
    case REQL_R_JSON:
    case REQL_R_REQL: break;
  }
}

void
Result::JSON_Value::release(ReQL_Datum_t a_type) {
  switch (a_type) {
    case REQL_R_ARRAY: {
      if (array != nullptr) {
        delete array;
      }
      break;
    }
    case REQL_R_OBJECT: {
      if (object != nullptr) {
        delete object;
      }
      break;
    }
    case REQL_R_STR: {
      if (string != nullptr) {
        delete string;
      }
      break;
    }
    case REQL_R_BOOL: {
      if (boolean != nullptr) {
        delete boolean;
      }
      break;
    }
    case REQL_R_NUM: {
      if (num != nullptr) {
        delete num;
      }
      break;
    }
    case REQL_R_JSON:
    case REQL_R_NULL:
    case REQL_R_REQL: break;
  }
}

Result::JSON_Value::~JSON_Value() {
  std::memset(this, 0, sizeof(Result::JSON_Value));
}

void
Parser::parse(ReQL_Obj_t *val) {
  switch (reql_datum_type(val)) {
    case REQL_R_ARRAY: {
      startArray();

      ReQL_Iter_t it = reql_new_iter(val);
      ReQL_Obj_t *elem = NULL;

      while ((elem = reql_iter_next(&it)) != NULL) {
        parse(elem);
      }

      endArray();
      break;
    }
    case REQL_R_BOOL: {
      addElement(static_cast<bool>(reql_to_bool(val)));
      break;
    }
    case REQL_R_JSON:
    case REQL_R_REQL: break;
    case REQL_R_NULL: {
      addElement();
      break;
    }
    case REQL_R_NUM: {
      addElement(reql_to_number(val));
      break;
    }
    case REQL_R_OBJECT: {
      startObject();

      ReQL_Iter_t it = reql_new_iter(val);
      ReQL_Obj_t *key = NULL;
      ReQL_Obj_t *value = NULL;

      while ((key = reql_iter_next(&it)) != NULL) {
        value = reql_object_get(val, key);
        std::string key_string((char *)reql_string_buf(key), reql_size(key));

        switch (reql_datum_type(value)) {
          case REQL_R_BOOL: {
            addKeyValue(key_string, static_cast<bool>(reql_to_bool(val)));
            break;
          }
          case REQL_R_ARRAY:
          case REQL_R_OBJECT: {
            addKey(key_string);
            parse(value);
            break;
          }
          case REQL_R_NULL: {
            addKeyValue(key_string);
            break;
          }
          case REQL_R_NUM: {
            addKeyValue(key_string, reql_to_number(value));
            break;
          }
          case REQL_R_JSON:
          case REQL_R_REQL: break;
          case REQL_R_STR: {
            addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));
            break;
          }
        }
      }

      endObject();
      break;
    }
    case REQL_R_STR: {
      addElement(std::string((char *)reql_string_buf(val), reql_size(val)));
      break;
    }
  }
}

class ResultBuilder : public Parser {
public:
  Result result() { return p_result; }

private:
  void startObject() {
    p_stack.push_back(Result());
    p_stack.end()->type = REQL_R_OBJECT;
  }

  void addKey(std::string key) {
    p_keys.push_back(key);
  }

  void addKeyValue(std::string key) {
    Result res;
    res.type = REQL_R_NULL;
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, bool value) {
    Result res;
    res.type = REQL_R_BOOL;
    res.value.boolean = new bool(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, double value) {
    Result res;
    res.type = REQL_R_NUM;
    res.value.num = new double(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, std::string value) {
    Result res;
    res.type = REQL_R_STR;
    res.value.string = new std::string(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void endObject() {
    end();
  }

  void startArray() {
    p_stack.push_back(Result());
    p_stack.end()->type = REQL_R_ARRAY;
    p_stack.end()->value.array = new std::vector<Result>;
  }

  void addElement() {
    Result res;
    res.type = REQL_R_NULL;
    addElement(std::move(res));
  }

  void addElement(bool value) {
    Result res;
    res.type = REQL_R_BOOL;
    res.value.boolean = new bool(value);
    addElement(std::move(res));
  }

  void addElement(double value) {
    Result res;
    res.type = REQL_R_NUM;
    res.value.num = new double(value);
    addElement(std::move(res));
  }

  void addElement(std::string value) {
    Result res;
    res.type = REQL_R_STR;
    res.value.string = new std::string(value);
    addElement(std::move(res));
  }

  void endArray() {
    end();
  }

  void addElement(Result &&val) {
    if (p_stack.empty()) {
      p_result = std::move(val);
    } else if (p_stack.end()->type == REQL_R_ARRAY) {
      std::vector<Result> *array = p_stack.end()->value.array;
      array->insert(array->end(), std::move(val));
    } else {
    }
  }

  void end() {
    Result last = *p_stack.end().base();
    p_stack.pop_back();
    if (p_stack.empty()) {
      p_result = last;
    } else if (p_stack.end()->type == REQL_R_OBJECT) {
      std::string key = *p_keys.end();
      p_keys.pop_back();
      p_stack.end()->value.object->insert({key, last});
    } else if (p_stack.end()->type == REQL_R_ARRAY) {
      addElement(std::move(last));
    } else {
    }
  }

  std::vector<Result> p_stack;
  std::vector<std::string> p_keys;
  Result p_result;
};

Cursor::Cursor() : cur(new ReQL_Cur_t) {
  reql_cursor_init(data());
}

Cursor::~Cursor() {
}

bool Cursor::isOpen() const {
  return reql_cur_open(data());
}

Result
Cursor::next() {
  ResultBuilder builder;
  next(builder);
  return builder.result();
}

void
Cursor::next(Parser &p) {
  p.parse(reql_cursor_next(data()));
}

ReQL_Cur_t *
Cursor::data() const {
  return cur.get();
}

void
Cursor::close() {
}

Connection::Connection() : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  reql_conn_set_addr(data(), (char *)host.c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  reql_conn_set_addr(data(), (char *)host.c_str());
  reql_conn_set_port(data(), (char *)std::to_string(port).c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  if (key.size() > UINT32_MAX) {
  }

  std::uint32_t key_len = (std::uint32_t)key.size();

  reql_conn_set_addr(data(), (char *)host.c_str());
  reql_conn_set_port(data(), (char *)std::to_string(port).c_str());
  reql_conn_set_auth(data(), key_len, (char *)key.c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const Connection &other) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  ReQL_Conn_t *o_conn = other.data();

  reql_conn_set_addr(data(), o_conn->addr);
  reql_conn_set_port(data(), o_conn->port);
  reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(Connection &&other) {
  conn = std::move(other.conn);
}

Connection::~Connection() {
  reql_ensure_conn_close(data());
}

Connection &Connection::operator=(const Connection &other) {
  if (this != &other) {
    reql_ensure_conn_close(data());
    reql_connection_init(data());

    ReQL_Conn_t *o_conn = other.data();

    reql_conn_set_addr(data(), o_conn->addr);
    reql_conn_set_port(data(), o_conn->port);
    reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);

    std::uint8_t buf[500];

    if (reql_connect(data(), buf, 500)) {
    }
  }
  return *this;
}

Connection &Connection::operator=(Connection &&other) {
  reql_ensure_conn_close(data());
  conn = std::move(other.conn);
  return *this;
}

void
Connection::close() {
  reql_close_conn(data());
}

bool
Connection::isOpen() const {
  return reql_conn_open(data());
}

ReQL_Conn_t *
Connection::data() const {
  return conn.get();
}

Cursor Query::run(const Connection &conn) const {
  if (!conn.isOpen()) {
  }

  Cursor cur;

  reql_run(cur.data(), p_query.data(), conn.data(), nullptr);

  return cur;
}

Query &Query::operator=(const Query &other) {
  Expr::operator=(other);
  return *this;
}

Query &Query::operator=(Query &&other) {
  Expr::operator=(std::move(other));
  return *this;
}

bool Query::operator<(const Query &other) const {
  return Expr::operator<(other);
}

}
<commit_msg>Compare type limits from c++.<commit_after>/*
Copyright 2014-2015 Adam Grandquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#include "ReQL.hpp"

#include <cstring>

namespace ReQL {

Result::Result() : type(REQL_R_JSON) {}

Result::Result(const Result &other) {
  value.copy(other.value, type);
}

Result::Result(Result &&other) {
  value.move(std::move(other.value), type);
}

Result::~Result() {
  value.release(type);
}

Result &
Result::operator=(const Result &other) {
  if (this != &other) {
    type = other.type;
    value.copy(other.value, type);
  }
  return *this;
}

Result &
Result::operator=(Result &&other) {
  if (this != &other) {
    type = std::move(other.type);
    value.move(std::move(other.value), type);
  }
  return *this;
}

Result::JSON_Value::JSON_Value() {
  std::memset(this, 0, sizeof(Result::JSON_Value));
}

void
Result::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) {
  release(a_type);
  switch (a_type) {
    case REQL_R_ARRAY: {
      array = new std::vector<Result>(*other.array);
      break;
    }
    case REQL_R_BOOL: {
      boolean = new bool(*other.boolean);
      break;
    }
    case REQL_R_NUM: {
      num = new double(*other.num);
      break;
    }
    case REQL_R_OBJECT: {
      object = new std::map<std::string, Result>(*other.object);
      break;
    }
    case REQL_R_STR: {
      string = new std::string(*other.string);
      break;
    }
    case REQL_R_NULL:
    case REQL_R_JSON:
    case REQL_R_REQL: break;
  }
}

void
Result::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) {
  release(a_type);
  switch (a_type) {
    case REQL_R_ARRAY: {
      array = std::move(other.array);
      break;
    }
    case REQL_R_BOOL: {
      boolean = std::move(other.boolean);
      break;
    }
    case REQL_R_NUM: {
      num = std::move(other.num);
      break;
    }
    case REQL_R_OBJECT: {
      object = std::move(other.object);
      break;
    }
    case REQL_R_STR: {
      string = std::move(other.string);
      break;
    }
    case REQL_R_NULL:
    case REQL_R_JSON:
    case REQL_R_REQL: break;
  }
}

void
Result::JSON_Value::release(ReQL_Datum_t a_type) {
  switch (a_type) {
    case REQL_R_ARRAY: {
      if (array != nullptr) {
        delete array;
      }
      break;
    }
    case REQL_R_OBJECT: {
      if (object != nullptr) {
        delete object;
      }
      break;
    }
    case REQL_R_STR: {
      if (string != nullptr) {
        delete string;
      }
      break;
    }
    case REQL_R_BOOL: {
      if (boolean != nullptr) {
        delete boolean;
      }
      break;
    }
    case REQL_R_NUM: {
      if (num != nullptr) {
        delete num;
      }
      break;
    }
    case REQL_R_JSON:
    case REQL_R_NULL:
    case REQL_R_REQL: break;
  }
}

Result::JSON_Value::~JSON_Value() {
  std::memset(this, 0, sizeof(Result::JSON_Value));
}

void
Parser::parse(ReQL_Obj_t *val) {
  switch (reql_datum_type(val)) {
    case REQL_R_ARRAY: {
      startArray();

      ReQL_Iter_t it = reql_new_iter(val);
      ReQL_Obj_t *elem = NULL;

      while ((elem = reql_iter_next(&it)) != NULL) {
        parse(elem);
      }

      endArray();
      break;
    }
    case REQL_R_BOOL: {
      addElement(static_cast<bool>(reql_to_bool(val)));
      break;
    }
    case REQL_R_JSON:
    case REQL_R_REQL: break;
    case REQL_R_NULL: {
      addElement();
      break;
    }
    case REQL_R_NUM: {
      addElement(reql_to_number(val));
      break;
    }
    case REQL_R_OBJECT: {
      startObject();

      ReQL_Iter_t it = reql_new_iter(val);
      ReQL_Obj_t *key = NULL;
      ReQL_Obj_t *value = NULL;

      while ((key = reql_iter_next(&it)) != NULL) {
        value = reql_object_get(val, key);
        std::string key_string((char *)reql_string_buf(key), reql_size(key));

        switch (reql_datum_type(value)) {
          case REQL_R_BOOL: {
            addKeyValue(key_string, static_cast<bool>(reql_to_bool(val)));
            break;
          }
          case REQL_R_ARRAY:
          case REQL_R_OBJECT: {
            addKey(key_string);
            parse(value);
            break;
          }
          case REQL_R_NULL: {
            addKeyValue(key_string);
            break;
          }
          case REQL_R_NUM: {
            addKeyValue(key_string, reql_to_number(value));
            break;
          }
          case REQL_R_JSON:
          case REQL_R_REQL: break;
          case REQL_R_STR: {
            addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));
            break;
          }
        }
      }

      endObject();
      break;
    }
    case REQL_R_STR: {
      addElement(std::string((char *)reql_string_buf(val), reql_size(val)));
      break;
    }
  }
}

class ResultBuilder : public Parser {
public:
  Result result() { return p_result; }

private:
  void startObject() {
    p_stack.push_back(Result());
    p_stack.end()->type = REQL_R_OBJECT;
  }

  void addKey(std::string key) {
    p_keys.push_back(key);
  }

  void addKeyValue(std::string key) {
    Result res;
    res.type = REQL_R_NULL;
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, bool value) {
    Result res;
    res.type = REQL_R_BOOL;
    res.value.boolean = new bool(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, double value) {
    Result res;
    res.type = REQL_R_NUM;
    res.value.num = new double(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void addKeyValue(std::string key, std::string value) {
    Result res;
    res.type = REQL_R_STR;
    res.value.string = new std::string(value);
    p_stack.end()->value.object->insert({key, res});
  }

  void endObject() {
    end();
  }

  void startArray() {
    p_stack.push_back(Result());
    p_stack.end()->type = REQL_R_ARRAY;
    p_stack.end()->value.array = new std::vector<Result>;
  }

  void addElement() {
    Result res;
    res.type = REQL_R_NULL;
    addElement(std::move(res));
  }

  void addElement(bool value) {
    Result res;
    res.type = REQL_R_BOOL;
    res.value.boolean = new bool(value);
    addElement(std::move(res));
  }

  void addElement(double value) {
    Result res;
    res.type = REQL_R_NUM;
    res.value.num = new double(value);
    addElement(std::move(res));
  }

  void addElement(std::string value) {
    Result res;
    res.type = REQL_R_STR;
    res.value.string = new std::string(value);
    addElement(std::move(res));
  }

  void endArray() {
    end();
  }

  void addElement(Result &&val) {
    if (p_stack.empty()) {
      p_result = std::move(val);
    } else if (p_stack.end()->type == REQL_R_ARRAY) {
      std::vector<Result> *array = p_stack.end()->value.array;
      array->insert(array->end(), std::move(val));
    } else {
    }
  }

  void end() {
    Result last = *p_stack.end().base();
    p_stack.pop_back();
    if (p_stack.empty()) {
      p_result = last;
    } else if (p_stack.end()->type == REQL_R_OBJECT) {
      std::string key = *p_keys.end();
      p_keys.pop_back();
      p_stack.end()->value.object->insert({key, last});
    } else if (p_stack.end()->type == REQL_R_ARRAY) {
      addElement(std::move(last));
    } else {
    }
  }

  std::vector<Result> p_stack;
  std::vector<std::string> p_keys;
  Result p_result;
};

Cursor::Cursor() : cur(new ReQL_Cur_t) {
  reql_cursor_init(data());
}

Cursor::~Cursor() {
}

bool Cursor::isOpen() const {
  return reql_cur_open(data());
}

Result
Cursor::next() {
  ResultBuilder builder;
  next(builder);
  return builder.result();
}

void
Cursor::next(Parser &p) {
  p.parse(reql_cursor_next(data()));
}

ReQL_Cur_t *
Cursor::data() const {
  return cur.get();
}

void
Cursor::close() {
}

Connection::Connection() : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  reql_conn_set_addr(data(), (char *)host.c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  reql_conn_set_addr(data(), (char *)host.c_str());
  reql_conn_set_port(data(), (char *)std::to_string(port).c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  std::size_t auth_size = key.size();

  if (auth_size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  reql_conn_set_addr(data(), (char *)host.c_str());
  reql_conn_set_port(data(), (char *)std::to_string(port).c_str());
  reql_conn_set_auth(data(), key_len, (char *)key.c_str());

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(const Connection &other) : conn(new ReQL_Conn_t) {
  reql_connection_init(data());

  ReQL_Conn_t *o_conn = other.data();

  reql_conn_set_addr(data(), o_conn->addr);
  reql_conn_set_port(data(), o_conn->port);
  reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);

  std::uint8_t buf[500];

  if (reql_connect(data(), buf, 500)) {
  }
}

Connection::Connection(Connection &&other) {
  conn = std::move(other.conn);
}

Connection::~Connection() {
  reql_ensure_conn_close(data());
}

Connection &Connection::operator=(const Connection &other) {
  if (this != &other) {
    reql_ensure_conn_close(data());
    reql_connection_init(data());

    ReQL_Conn_t *o_conn = other.data();

    reql_conn_set_addr(data(), o_conn->addr);
    reql_conn_set_port(data(), o_conn->port);
    reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);

    std::uint8_t buf[500];

    if (reql_connect(data(), buf, 500)) {
    }
  }
  return *this;
}

Connection &Connection::operator=(Connection &&other) {
  reql_ensure_conn_close(data());
  conn = std::move(other.conn);
  return *this;
}

void
Connection::close() {
  reql_close_conn(data());
}

bool
Connection::isOpen() const {
  return reql_conn_open(data());
}

ReQL_Conn_t *
Connection::data() const {
  return conn.get();
}

Cursor Query::run(const Connection &conn) const {
  if (!conn.isOpen()) {
  }

  Cursor cur;

  reql_run(cur.data(), p_query.data(), conn.data(), nullptr);

  return cur;
}

Query &Query::operator=(const Query &other) {
  Expr::operator=(other);
  return *this;
}

Query &Query::operator=(Query &&other) {
  Expr::operator=(std::move(other));
  return *this;
}

bool Query::operator<(const Query &other) const {
  return Expr::operator<(other);
}

}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef MIDDLEWARE_COOKIE_PARSER_HPP
#define MIDDLEWARE_COOKIE_PARSER_HPP

#include "../cookie/cookie.hpp"
#include "middleware.hpp"

namespace middleware {

/**
 * @brief A way to parse cookies: Reading cookies that the browser is sending to the server
 * @details
 *
 */

// hpp-declarations first and implement methods further down? Or in own cpp-file?

class CookieParser : public server::Middleware {

public:
  virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override {

    using namespace cookie;

    if(!has_cookie(req)) {
      //No Cookie in header field: We want to create a cookie then??:
      //
      //create cookie:

      (*next)();
      return;
    }

    // Found Cookie in header

  }

  // Just name this method cookie?
  // Return bool or void?
  bool create_cookie(std::string& key, std::string& value);  // new Cookie(...) and add_header: Set-Cookie ?

  // Just name this method cookie?
  // Return bool or void?
  bool create_cookie(std::string& key, std::string& value, std::string& options);  // new Cookie(...) and add_header: Set-Cookie ?
// options: map eller enum

  // Return bool or void?
  bool clear_cookie(std::string& key); // remove Cookie from client

private:
  bool has_cookie(server::Request_ptr req) const {
    auto c_type = http::header_fields::Request::Cookie;

    return req->has_header(c_type);
  }

};

} //< namespace middleware

#endif
<commit_msg>Refactored CookieParser::has_cookie<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef MIDDLEWARE_COOKIE_PARSER_HPP
#define MIDDLEWARE_COOKIE_PARSER_HPP

#include "../cookie/cookie.hpp"
#include "middleware.hpp"

namespace middleware {

/**
 * @brief A way to parse cookies: Reading cookies that the browser is sending to the server
 * @details
 *
 */

// hpp-declarations first and implement methods further down? Or in own cpp-file?

class CookieParser : public server::Middleware {

public:
  virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override {

    using namespace cookie;

    if(!has_cookie(req)) {
      //No Cookie in header field: We want to create a cookie then??:
      //
      //create cookie:

      (*next)();
      return;
    }

    // Found Cookie in header

  }

  // Just name this method cookie?
  // Return bool or void?
  bool create_cookie(std::string& key, std::string& value);  // new Cookie(...) and add_header: Set-Cookie ?

  // Just name this method cookie?
  // Return bool or void?
  bool create_cookie(std::string& key, std::string& value, std::string& options);  // new Cookie(...) and add_header: Set-Cookie ?
// options: map eller enum

  // Return bool or void?
  bool clear_cookie(std::string& key); // remove Cookie from client

private:
  bool has_cookie(server::Request_ptr req) const noexcept;
};

inline bool CookieParser::has_cookie(server::Request_ptr req) const noexcept {
  return req->has_header(http::header_fields::Request::Cookie);
}

} //< namespace middleware

#endif
<|endoftext|>


<commit_before>#include <cassert>

#include "html-escape.hh"

namespace mimosa
{
  namespace stream
  {
    HtmlEscape::HtmlEscape(Stream::Ptr stream)
      : Filter(stream)
    {
    }

    int64_t
    HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout)
    {
      const char * const start = data;
      const char * const end   = data + nbytes;
      const char * p           = data;

      while (data < end)
      {
        while (p < end && *p != '<' && *p != '>' &&
               *p != '&' && *p != '"' && *p != '\'')
          ++p;

        if (data < p)
        {
          auto bytes = stream_->write(data, p - data, timeout);
          if (bytes < 0)
            return data == start ? bytes : data - start;
          if (bytes < p - data)
            return data - start + bytes;
          data = p;
        }

        if (p < end)
        {
          const char * replace = nullptr;
          int          size    = 0;

          switch (*p)
          {
          case '<':  replace = "<";   size = 4; break;
          case '>':  replace = ">";   size = 4; break;
          case '&':  replace = "&";  size = 5; break;
          case '\'': replace = "'"; size = 6; break;
          case '"':  replace = """; size = 6; break;
          default: assert(false); break;
          }

          auto wrote = stream_->loopWrite(replace, size, timeout);
          if (wrote < 0)
            return data - start;
          if (wrote < size)
            return -1;
          ++data;
          ++p;
        }
      }
      return nbytes;
    }

    int64_t
    HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout)
    {
      assert(false && "TODO");
    }
  }
}
<commit_msg>fix a return value error<commit_after>#include <cassert>

#include "html-escape.hh"

namespace mimosa
{
  namespace stream
  {
    HtmlEscape::HtmlEscape(Stream::Ptr stream)
      : Filter(stream)
    {
    }

    int64_t
    HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout)
    {
      const char * const start = data;
      const char * const end   = data + nbytes;
      const char * p           = data;

      while (data < end)
      {
        while (p < end && *p != '<' && *p != '>' &&
               *p != '&' && *p != '"' && *p != '\'')
          ++p;

        if (data < p)
        {
          auto bytes = stream_->write(data, p - data, timeout);
          if (bytes < 0)
            return data == start ? bytes : data - start;
          if (bytes < p - data)
            return data - start + bytes;
          data = p;
        }

        if (p < end)
        {
          const char * replace = nullptr;
          int          size    = 0;

          switch (*p)
          {
          case '<':  replace = "<";   size = 4; break;
          case '>':  replace = ">";   size = 4; break;
          case '&':  replace = "&";  size = 5; break;
          case '\'': replace = "'"; size = 6; break;
          case '"':  replace = """; size = 6; break;
          default: assert(false); break;
          }

          auto wrote = stream_->loopWrite(replace, size, timeout);
          if (wrote < 0)
            return data - start;
          if (wrote < size)
            return -1;
          ++data;
          ++p;
        }
      }
      return nbytes;
    }

    int64_t
    HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout)
    {
      assert(false && "TODO");
      return -1;
    }
  }
}
<|endoftext|>


<commit_before>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH
# define MIMOSA_TPL_ABSTRACT_VALUE_HH

# include "../ref-countable.hh"
# include "../stream/stream.hh"
# include "../string/string-ref.hh"

namespace mimosa
{
  namespace tpl
  {
    class AbstractValue
    {
    public:
      virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;
      virtual void write(stream::Stream::Ptr stream) const = 0;

      AbstractValue * parent_;
    };
  }
}

#endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */
<commit_msg>template: added some mechanism to iterate on "repeated" values<commit_after>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH
# define MIMOSA_TPL_ABSTRACT_VALUE_HH

# include "../ref-countable.hh"
# include "../stream/stream.hh"
# include "../string/string-ref.hh"

namespace mimosa
{
  namespace tpl
  {
    class AbstractValue
    {
    public:
      virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;
      virtual void write(stream::Stream::Ptr stream) const = 0;

      class Iterator
      {
        virtual const AbstractValue & operator*() const = 0;
        virtual const AbstractValue * operator->() const = 0;
        virtual Iterator & operator++() = 0;
        virtual bool operator==(const Iterator &) const = 0;
      };

      virtual Iterator begin() const = 0;
      virtual Iterator end() const = 0;
      virtual bool empty() const = 0;

      AbstractValue * parent_;
    };
  }
}

#endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */
<|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * OU library interface file for Open Dynamics Engine,                   *
 * Copyright (C) 2008 Oleh Derevenko. All rights reserved.               *
 * Email: odar@eleks.com (change all "a" to "e")                         *
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

/*

ODE interface to OU library implementation.

*/

#include <ode/common.h>
#include <ode/memory.h>
#include "config.h"
#include "odeou.h"

#if dOU_ENABLED

template<>
const char *const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *>::m_aetElementArray[] =
{
    "assert", // AFS_ASSERT,
    "check", // AFS_CHECK,
};
static const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *> g_aszAssertionFailureSeverityNames;

static void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity,
                                                              const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine)
{
    dDebug(d_ERR_IASSERT, "Assertion failure in OU Library. Kind: %s, expression: \"%s\", file: \"%s\", line: %u",
        g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity),
        szAssertionExpression, szAssertionFileName, uiAssertionSourceLine);
}

static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize)
{
    return dAlloc(nBlockSize);
}

static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize)
{
    return dRealloc(pv_ExistingBlock, 0, nBlockNewSize);
}

static void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock)
{
    return dFree(pv_ExistingBlock, 0);
}

bool COdeOu::DoOUCustomizations()
{
    CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc,
        &ForwardOUMemoryRealloc, &ForwardOUMemoryFree);

    CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure);

    return true;
}

void COdeOu::UndoOUCustomizations()
{
    CAssertionCheckCustomization::CustomizeAssertionChecks(NULL);

    CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL);
}

#endif // dOU_ENABLED

<commit_msg>Cosmetic: A warning fixed in LLVM compiler<commit_after>/*************************************************************************
 *                                                                       *
 * OU library interface file for Open Dynamics Engine,                   *
 * Copyright (C) 2008 Oleh Derevenko. All rights reserved.               *
 * Email: odar@eleks.com (change all "a" to "e")                         *
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

/*

ODE interface to OU library implementation.

*/

#include <ode/common.h>
#include <ode/memory.h>
#include "config.h"
#include "odeou.h"

#if dOU_ENABLED

BEGIN_NAMESPACE_OU();
template<>
const char *const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *>::m_aetElementArray[] =
{
    "assert", // AFS_ASSERT,
    "check", // AFS_CHECK,
};
END_NAMESPACE_OU();

static const CEnumUnsortedElementArray<EASSERTIONFAILURESEVERITY, AFS__MAX, const char *> g_aszAssertionFailureSeverityNames;

static void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity,
                                                              const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine)
{
    dDebug(d_ERR_IASSERT, "Assertion failure in OU Library. Kind: %s, expression: \"%s\", file: \"%s\", line: %u",
        g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity),
        szAssertionExpression, szAssertionFileName, uiAssertionSourceLine);
}

static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize)
{
    return dAlloc(nBlockSize);
}

static void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize)
{
    return dRealloc(pv_ExistingBlock, 0, nBlockNewSize);
}

static void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock)
{
    return dFree(pv_ExistingBlock, 0);
}

bool COdeOu::DoOUCustomizations()
{
    CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc,
        &ForwardOUMemoryRealloc, &ForwardOUMemoryFree);

    CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure);

    return true;
}

void COdeOu::UndoOUCustomizations()
{
    CAssertionCheckCustomization::CustomizeAssertionChecks(NULL);

    CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL);
}

#endif // dOU_ENABLED

<|endoftext|>


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

#ifndef SIRIKATA_DiskManager_HPP__
#define SIRIKATA_DiskManager_HPP__

#include <sirikata/core/queue/ThreadSafeQueue.hpp>
#include <sirikata/core/util/Thread.hpp>
#include <sirikata/core/util/Singleton.hpp>
#include <sirikata/core/transfer/TransferData.hpp>
#include <boost/filesystem.hpp>

namespace Sirikata {
namespace Transfer {

namespace fs = boost::filesystem;

namespace Filesystem {
    typedef boost::filesystem::path Path;
    typedef boost::filesystem::file_status FileStatus;
    typedef boost::filesystem::file_type FileType;
    namespace boost_fs = boost::filesystem;
    class PathInfo {
    public:
        Path mPath;
        FileStatus mFileStatus;
        PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {}
    };
}

class SIRIKATA_EXPORT DiskManager
    : public AutoSingleton<DiskManager> {

public:

    class DiskRequest {
    protected:
        virtual void execute() = 0;

        virtual ~DiskRequest() {}
    friend class DiskManager;
    };

    class ScanRequest : public DiskRequest {
    public:
        typedef std::vector<Filesystem::PathInfo> DirectoryListing;
        typedef std::tr1::function<void(
                    std::tr1::shared_ptr<DirectoryListing> dirListing
                )> ScanRequestCallback;

        ScanRequest(Filesystem::Path path, ScanRequestCallback cb);
    private:
        ScanRequestCallback mCb;
        Filesystem::Path mPath;
    protected:
        void execute();
    };

    class ReadRequest : public DiskRequest {
    public:
        typedef std::tr1::function<void(
                    std::tr1::shared_ptr<DenseData> fileContents
                )> ReadRequestCallback;

        ReadRequest(Filesystem::Path path, ReadRequestCallback cb);
    private:
        ReadRequestCallback mCb;
        Filesystem::Path mPath;
    protected:
        void execute();
    };

    class WriteRequest : public DiskRequest {
    public:
        typedef std::tr1::function<void(
                    bool status
                )> WriteRequestCallback;

        WriteRequest(Filesystem::Path path, std::tr1::shared_ptr<DenseData> fileContents, WriteRequestCallback cb);
    private:
        WriteRequestCallback mCb;
        Filesystem::Path mPath;
        std::tr1::shared_ptr<DenseData> mFileContents;
    protected:
        void execute();
    };

    DiskManager();
    ~DiskManager();

    void addRequest(std::tr1::shared_ptr<DiskRequest> req);

    static DiskManager& getSingleton();
    static void destroy();

private:
    ThreadSafeQueue<std::tr1::shared_ptr<DiskRequest> > mRequestQueue;
    Thread *mWorkerThread;
    boost::mutex destroyLock;
    boost::condition_variable destroyCV;

    void workerThread();

};

}
}

#endif /* SIRIKATA_DiskManager_HPP__ */
<commit_msg>Add missing SIRIKATA_EXPORT to public nested classes, which some platforms require even when the parent class has SIRIKATA_EXPORT.<commit_after>/*  Sirikata Transfer
 *  DiskManager.hpp
 *
 *  Copyright (c) 2010, Jeff Terrace
 *  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 Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SIRIKATA_DiskManager_HPP__
#define SIRIKATA_DiskManager_HPP__

#include <sirikata/core/queue/ThreadSafeQueue.hpp>
#include <sirikata/core/util/Thread.hpp>
#include <sirikata/core/util/Singleton.hpp>
#include <sirikata/core/transfer/TransferData.hpp>
#include <boost/filesystem.hpp>

namespace Sirikata {
namespace Transfer {

namespace fs = boost::filesystem;

namespace Filesystem {
    typedef boost::filesystem::path Path;
    typedef boost::filesystem::file_status FileStatus;
    typedef boost::filesystem::file_type FileType;
    namespace boost_fs = boost::filesystem;
    class PathInfo {
    public:
        Path mPath;
        FileStatus mFileStatus;
        PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {}
    };
}

class SIRIKATA_EXPORT DiskManager
    : public AutoSingleton<DiskManager> {

public:

    class DiskRequest {
    protected:
        virtual void execute() = 0;

        virtual ~DiskRequest() {}
    friend class DiskManager;
    };

    class SIRIKATA_EXPORT ScanRequest : public DiskRequest {
    public:
        typedef std::vector<Filesystem::PathInfo> DirectoryListing;
        typedef std::tr1::function<void(
                    std::tr1::shared_ptr<DirectoryListing> dirListing
                )> ScanRequestCallback;

        ScanRequest(Filesystem::Path path, ScanRequestCallback cb);
    private:
        ScanRequestCallback mCb;
        Filesystem::Path mPath;
    protected:
        void execute();
    };

    class SIRIKATA_EXPORT ReadRequest : public DiskRequest {
    public:
        typedef std::tr1::function<void(
                    std::tr1::shared_ptr<DenseData> fileContents
                )> ReadRequestCallback;

        ReadRequest(Filesystem::Path path, ReadRequestCallback cb);
    private:
        ReadRequestCallback mCb;
        Filesystem::Path mPath;
    protected:
        void execute();
    };

    class SIRIKATA_EXPORT WriteRequest : public DiskRequest {
    public:
        typedef std::tr1::function<void(
                    bool status
                )> WriteRequestCallback;

        WriteRequest(Filesystem::Path path, std::tr1::shared_ptr<DenseData> fileContents, WriteRequestCallback cb);
    private:
        WriteRequestCallback mCb;
        Filesystem::Path mPath;
        std::tr1::shared_ptr<DenseData> mFileContents;
    protected:
        void execute();
    };

    DiskManager();
    ~DiskManager();

    void addRequest(std::tr1::shared_ptr<DiskRequest> req);

    static DiskManager& getSingleton();
    static void destroy();

private:
    ThreadSafeQueue<std::tr1::shared_ptr<DiskRequest> > mRequestQueue;
    Thread *mWorkerThread;
    boost::mutex destroyLock;
    boost::condition_variable destroyCV;

    void workerThread();

};

}
}

#endif /* SIRIKATA_DiskManager_HPP__ */
<|endoftext|>


<commit_before>// --*-  Mode: C++; c-basic-offset: 8 -*--
#include <complex>
#include "EigenLab.h"

int main(int argc, const char * argv[])
{
  EigenLab::ParserXd parserXd;
  auto failXd = parserXd.test();

  EigenLab::ParserXf parserXf;
  auto failXf = parserXf.test();

  EigenLab::ParserXi parserXi;
  auto failXi = parserXi.test();

  EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd;
  auto failXcd = parserXcd.test();

  std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl;
  return 0;
}
<commit_msg>make test return -1 if fail<commit_after>// --*-  Mode: C++; c-basic-offset: 8 -*--
#include <complex>
#include "EigenLab.h"

int main(int argc, const char * argv[])
{
  EigenLab::ParserXd parserXd;
  auto failXd = parserXd.test();

  EigenLab::ParserXf parserXf;
  auto failXf = parserXf.test();

  EigenLab::ParserXi parserXi;
  auto failXi = parserXi.test();

  EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd;
  auto failXcd = parserXcd.test();

  std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl;

  return (failXd || failXf || failXi || failXcd) ? -1 : 0;
}
<|endoftext|>


<commit_before>#include <../recurse.hpp>
#include <QHash>

int main(int argc, char *argv[])
{
    Recurse app(argc, argv);

    // http options
    QHash<QString, QVariant> http_options;
    http_options["port"] = 3000;

    // https options
    QHash<QString, QVariant> https_options;
    https_options["port"] = 3020;
    https_options["private_key"] = "./priv.pem";
    https_options["certificate"] = "./cert.pem";

    app.http_server(http_options);
    app.https_server(https_options);

    qDebug() << "start listening...";

    auto ret = app.listen();
    if (ret.error()) {
        qDebug() << "error upon listening:" << ret.lastError();
    }
};
<commit_msg>example: update for middleware changes<commit_after>#include <../recurse.hpp>
#include <QHash>

int main(int argc, char *argv[])
{
    Recurse app(argc, argv);

    // http options
    QHash<QString, QVariant> http_options;
    http_options["port"] = 3000;

    // https options
    QHash<QString, QVariant> https_options;
    https_options["port"] = 3020;
    https_options["private_key"] = "./priv.pem";
    https_options["certificate"] = "./cert.pem";

    app.http_server(http_options);
    app.https_server(https_options);

    app.use([](auto &ctx, auto next) {
        qDebug() << "got a new request from" << ctx.request.ip;
        next();
    });

    app.use([](auto &ctx) {
        ctx.response.send("Hello, world");
    });

    qDebug() << "start listening...";

    auto ret = app.listen();
    if (ret.error()) {
        qDebug() << "error upon listening:" << ret.lastError();
    }
};
<|endoftext|>


<commit_before>#include <iostream>
#include <vlf/Types.h>
#include <FaceEngine.h>
#include <IEstimator.h>

int main(int argn, char** argv)
{
    if(argn != 2)
    {
        std::cout << "USAGE: " << argv[0] << " <imagePath>\n";
        return -1;
    }

    const std::string dataPath = "/opt/visionlabs/data/";

    vlf::Image image;
    if( !image.loadFromPPM(argv[1]) )
    {
        std::cout << "Cant load image: " << argv[1] << '\n';
        return -1;
    }

    // Need only R-channel image for feature extraction
    vlf::Image imageR;
    image.convert(imageR, vlf::Format::R8);

    // Create FaceEngine main object
    fsdk::Ref<fsdk::IFaceEngine> faceEngine = fsdk::acquire(fsdk::createFaceEngine());

    // Creating detector
    fsdk::Ref<fsdk::IDetectorFactory> detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory());
    detectorFactory->setDataDirectory(dataPath.c_str());
    fsdk::Ref<fsdk::IDetector> detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM));

    // Creating feature extractor
    fsdk::Ref<fsdk::IFeatureFactory> featureFactory = fsdk::acquire(faceEngine->createFeatureFactory());
    featureFactory->setDataDirectory(dataPath.c_str());
    fsdk::Ref<fsdk::IFeatureDetector> featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG));
    fsdk::Ref<fsdk::IFeatureSet> featureSet = fsdk::acquire(featureFactory->createFeatureSet());

    // Create warper
    fsdk::Ref<fsdk::IDescriptorFactory> descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory());
    fsdk::Ref<fsdk::ICNNDescriptor> descriptor =
        fsdk::acquire(static_cast<fsdk::ICNNDescriptor*>(descriptorFactory->createDescriptor(fsdk::DT_CNN)));
    fsdk::Ref<fsdk::ICNNWarper> warper =
        fsdk::acquire(static_cast<fsdk::ICNNWarper*>(descriptorFactory->createWarper(fsdk::DT_CNN)));

    // Creating estimator
    fsdk::Ref<fsdk::IEstimatorFactory> estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory());
    estimatorFactory->setDataDirectory(dataPath.c_str());
    fsdk::Ref<fsdk::IComplexEstimator> complexEstimator =
        fsdk::acquire(static_cast<fsdk::IComplexEstimator*>(estimatorFactory->createEstimator(fsdk::ET_COMPLEX)));
    fsdk::Ref<fsdk::IQualityEstimator> qualityEstimator =
        fsdk::acquire(static_cast<fsdk::IQualityEstimator*>(estimatorFactory->createEstimator(fsdk::ET_QUALITY)));

    // Detecting faces on the photo
    fsdk::Detection detections[10];
    int count = 10;
    fsdk::Result<fsdk::FSDKError> res = detector->detect(image, image.getRect(), detections, &count);
    if(res.isError())
    {
        std::cout << "Face detection error\n";
        return -1;
    }
    std::cout << "Detections found: " << count << "\n\n";
    for(int i = 0; i < count; i++)
    {
	    fsdk::Detection& detection = detections[i];

	    std::cout << "Detection " << i << "\n";
	    std::cout << "Rect: x=" << detection.rect.x << " y=" << detection.rect.y
            << " w=" << detection.rect.width << " h=" << detection.rect.height << '\n';

        // Extracting face features
        fsdk::Result<fsdk::FSDKError> res = featureDetector->detect(imageR, detection, featureSet);
        if(res.isError())
        {
            std::cout << "Feature extraction error\n";
            continue;
        }

        // Get warped face from detection
        fsdk::Image warp;
        warper->warp(image, detection, featureSet, warp);

        warp.saveAsPPM(("warp_" + std::to_string(i) + ".ppm").c_str());

        // Quality estimating
        float qualityOut;
        res = qualityEstimator->estimate(warp, &qualityOut);
        if(res.isError())
        {
            std::cout << "Quality estimating error\n";
            return -1;
        }
        std::cout << "Quality estimated\n";
        std::cout << "Quality: " << qualityOut << "\n";

        // Complex attributes estimating
        fsdk::ComplexEstimation complexEstimationOut;
        res = complexEstimator->estimate(warp, complexEstimationOut);

        if(res.isError())
        {
            std::cout << "Complex attributes estimating error\n";
            return -1;
        }
        std::cout << "Complex attributes estimated\n";
        std::cout << "Gender: " << complexEstimationOut.gender << " (1 - man, 0 - woman)\n";
        std::cout << "Natural skin color: " << complexEstimationOut.naturSkinColor << " (1 - natural color of skin, 0 - not natural color of skin color)\n";
        std::cout << "Over exposed: " << complexEstimationOut.overExposed << " (1 - image is overexposed, 0 - image isn't overexposed)\n";
        std::cout << "Wear glasses: " << complexEstimationOut.wearGlasses << " (1 - person wears glasses, 0 - person doesn't wear glasses)\n";
        std::cout << "Age: " << complexEstimationOut.age << " (in years)\n";
        std::cout << '\n';
    }

    return 0;
}
<commit_msg>remove dataPath in the example2<commit_after>#include <iostream>
#include <vlf/Types.h>
#include <FaceEngine.h>
#include <IEstimator.h>

int main(int argn, char** argv)
{
    if(argn != 2)
    {
        std::cout << "USAGE: " << argv[0] << " <imagePath>\n";
        return -1;
    }

    vlf::Image image;
    if( !image.loadFromPPM(argv[1]) )
    {
        std::cout << "Cant load image: " << argv[1] << '\n';
        return -1;
    }

    // Need only R-channel image for feature extraction
    vlf::Image imageR;
    image.convert(imageR, vlf::Format::R8);

    // Create FaceEngine main object
    fsdk::Ref<fsdk::IFaceEngine> faceEngine = fsdk::acquire(fsdk::createFaceEngine());

    // Creating detector
    fsdk::Ref<fsdk::IDetectorFactory> detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory());
    fsdk::Ref<fsdk::IDetector> detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM));

    // Creating feature extractor
    fsdk::Ref<fsdk::IFeatureFactory> featureFactory = fsdk::acquire(faceEngine->createFeatureFactory());
    fsdk::Ref<fsdk::IFeatureDetector> featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG));
    fsdk::Ref<fsdk::IFeatureSet> featureSet = fsdk::acquire(featureFactory->createFeatureSet());

    // Create warper
    fsdk::Ref<fsdk::IDescriptorFactory> descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory());
    fsdk::Ref<fsdk::ICNNDescriptor> descriptor =
        fsdk::acquire(static_cast<fsdk::ICNNDescriptor*>(descriptorFactory->createDescriptor(fsdk::DT_CNN)));
    fsdk::Ref<fsdk::ICNNWarper> warper =
        fsdk::acquire(static_cast<fsdk::ICNNWarper*>(descriptorFactory->createWarper(fsdk::DT_CNN)));

    // Creating estimator
    fsdk::Ref<fsdk::IEstimatorFactory> estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory());
    fsdk::Ref<fsdk::IComplexEstimator> complexEstimator =
        fsdk::acquire(static_cast<fsdk::IComplexEstimator*>(estimatorFactory->createEstimator(fsdk::ET_COMPLEX)));
    fsdk::Ref<fsdk::IQualityEstimator> qualityEstimator =
        fsdk::acquire(static_cast<fsdk::IQualityEstimator*>(estimatorFactory->createEstimator(fsdk::ET_QUALITY)));

    // Detecting faces on the photo
    fsdk::Detection detections[10];
    int count = 10;
    fsdk::Result<fsdk::FSDKError> res = detector->detect(image, image.getRect(), detections, &count);
    if(res.isError())
    {
        std::cout << "Face detection error\n";
        return -1;
    }
    std::cout << "Detections found: " << count << "\n\n";
    for(int i = 0; i < count; i++)
    {
	    fsdk::Detection& detection = detections[i];

	    std::cout << "Detection " << i << "\n";
	    std::cout << "Rect: x=" << detection.rect.x << " y=" << detection.rect.y
            << " w=" << detection.rect.width << " h=" << detection.rect.height << '\n';

        // Extracting face features
        fsdk::Result<fsdk::FSDKError> res = featureDetector->detect(imageR, detection, featureSet);
        if(res.isError())
        {
            std::cout << "Feature extraction error\n";
            continue;
        }

        // Get warped face from detection
        fsdk::Image warp;
        warper->warp(image, detection, featureSet, warp);

        warp.saveAsPPM(("warp_" + std::to_string(i) + ".ppm").c_str());

        // Quality estimating
        float qualityOut;
        res = qualityEstimator->estimate(warp, &qualityOut);
        if(res.isError())
        {
            std::cout << "Quality estimating error\n";
            return -1;
        }
        std::cout << "Quality estimated\n";
        std::cout << "Quality: " << qualityOut << "\n";

        // Complex attributes estimating
        fsdk::ComplexEstimation complexEstimationOut;
        res = complexEstimator->estimate(warp, complexEstimationOut);

        if(res.isError())
        {
            std::cout << "Complex attributes estimating error\n";
            return -1;
        }
        std::cout << "Complex attributes estimated\n";
        std::cout << "Gender: " << complexEstimationOut.gender << " (1 - man, 0 - woman)\n";
        std::cout << "Natural skin color: " << complexEstimationOut.naturSkinColor << " (1 - natural color of skin, 0 - not natural color of skin color)\n";
        std::cout << "Over exposed: " << complexEstimationOut.overExposed << " (1 - image is overexposed, 0 - image isn't overexposed)\n";
        std::cout << "Wear glasses: " << complexEstimationOut.wearGlasses << " (1 - person wears glasses, 0 - person doesn't wear glasses)\n";
        std::cout << "Age: " << complexEstimationOut.age << " (in years)\n";
        std::cout << '\n';
    }

    return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
// $Id$

#include <mapnik/map.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/config_error.hpp>

#include <iostream>

int main ( int argc , char** argv)
{
    if (argc != 2)
    {
        std::cout << "usage: ./rundemo <plugins_dir>\n";
        return EXIT_SUCCESS;
    }

    using namespace mapnik;
    try {
        std::cout << " running demo ... \n";
        datasource_cache::instance()->register_datasources(argv[1]);
        freetype_engine::register_font("/usr/local/lib/mapnik/fonts/DejaVuSans.ttf");

        Map m(800,600);
        m.set_background(color_factory::from_string("white"));

        // create styles

        // Provinces (polygon)
        feature_type_style provpoly_style;

        rule_type provpoly_rule_on;
        provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'"));
        provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));
        provpoly_style.add_rule(provpoly_rule_on);

        rule_type provpoly_rule_qc;
        provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'"));
        provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));
        provpoly_style.add_rule(provpoly_rule_qc);

        m.insert_style("provinces",provpoly_style);

        // Provinces (polyline)
        feature_type_style provlines_style;

        stroke provlines_stk (Color(0,0,0),1.0);
        provlines_stk.add_dash(8, 4);
        provlines_stk.add_dash(2, 2);
        provlines_stk.add_dash(2, 2);

        rule_type provlines_rule;
        provlines_rule.append(line_symbolizer(provlines_stk));
        provlines_style.add_rule(provlines_rule);

        m.insert_style("provlines",provlines_style);

        // Drainage
        feature_type_style qcdrain_style;

        rule_type qcdrain_rule;
        qcdrain_rule.set_filter(create_filter("[HYC] = 8"));
        qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));
        qcdrain_style.add_rule(qcdrain_rule);

        m.insert_style("drainage",qcdrain_style);

        // Roads 3 and 4 (The "grey" roads)
        feature_type_style roads34_style;
        rule_type roads34_rule;
        roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4"));
        stroke roads34_rule_stk(Color(171,158,137),2.0);
        roads34_rule_stk.set_line_cap(ROUND_CAP);
        roads34_rule_stk.set_line_join(ROUND_JOIN);
        roads34_rule.append(line_symbolizer(roads34_rule_stk));
        roads34_style.add_rule(roads34_rule);

        m.insert_style("smallroads",roads34_style);

        // Roads 2 (The thin yellow ones)
        feature_type_style roads2_style_1;
        rule_type roads2_rule_1;
        roads2_rule_1.set_filter(create_filter("[CLASS] = 2"));
        stroke roads2_rule_stk_1(Color(171,158,137),4.0);
        roads2_rule_stk_1.set_line_cap(ROUND_CAP);
        roads2_rule_stk_1.set_line_join(ROUND_JOIN);
        roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
        roads2_style_1.add_rule(roads2_rule_1);

        m.insert_style("road-border", roads2_style_1);

        feature_type_style roads2_style_2;
        rule_type roads2_rule_2;
        roads2_rule_2.set_filter(create_filter("[CLASS] = 2"));
        stroke roads2_rule_stk_2(Color(255,250,115),2.0);
        roads2_rule_stk_2.set_line_cap(ROUND_CAP);
        roads2_rule_stk_2.set_line_join(ROUND_JOIN);
        roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
        roads2_style_2.add_rule(roads2_rule_2);

        m.insert_style("road-fill", roads2_style_2);

        // Roads 1 (The big orange ones, the highways)
        feature_type_style roads1_style_1;
        rule_type roads1_rule_1;
        roads1_rule_1.set_filter(create_filter("[CLASS] = 1"));
        stroke roads1_rule_stk_1(Color(188,149,28),7.0);
        roads1_rule_stk_1.set_line_cap(ROUND_CAP);
        roads1_rule_stk_1.set_line_join(ROUND_JOIN);
        roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
        roads1_style_1.add_rule(roads1_rule_1);
        m.insert_style("highway-border", roads1_style_1);

        feature_type_style roads1_style_2;
        rule_type roads1_rule_2;
        roads1_rule_2.set_filter(create_filter("[CLASS] = 1"));
        stroke roads1_rule_stk_2(Color(242,191,36),5.0);
        roads1_rule_stk_2.set_line_cap(ROUND_CAP);
        roads1_rule_stk_2.set_line_join(ROUND_JOIN);
        roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
        roads1_style_2.add_rule(roads1_rule_2);
        m.insert_style("highway-fill", roads1_style_2);

        // Populated Places

        feature_type_style popplaces_style;
        rule_type popplaces_rule;
        text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0));
        popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));
        popplaces_text_symbolizer.set_halo_radius(1);
        popplaces_rule.append(popplaces_text_symbolizer);
        popplaces_style.add_rule(popplaces_rule);

        m.insert_style("popplaces",popplaces_style );

        // Layers
        // Provincial  polygons
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/boundaries";

            Layer lyr("Provinces");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("provinces");
            m.addLayer(lyr);
        }

        // Drainage
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/qcdrainage";
            Layer lyr("Quebec Hydrography");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("drainage");
            m.addLayer(lyr);
        }

        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/ontdrainage";

            Layer lyr("Ontario Hydrography");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("drainage");
            m.addLayer(lyr);
        }

        // Provincial boundaries
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/boundaries_l";
            Layer lyr("Provincial borders");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("provlines");
            m.addLayer(lyr);
        }

        // Roads
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/roads";
            Layer lyr("Roads");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("smallroads");
            lyr.add_style("road-border");
            lyr.add_style("road-fill");
            lyr.add_style("highway-border");
            lyr.add_style("highway-fill");

            m.addLayer(lyr);
        }
        // popplaces
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/popplaces";
            p["encoding"] = "latin1";
            Layer lyr("Populated Places");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("popplaces");
            m.addLayer(lyr);
        }

        m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,
                                     1706357.31328276,-25098.593149577));

        Image32 buf(m.getWidth(),m.getHeight());
        agg_renderer<Image32> ren(m,buf);
        ren.apply();

        save_to_file<ImageData32>("demo.jpg","jpeg",buf.data());
        save_to_file<ImageData32>("demo.png","png",buf.data());

        std::cout << "Two maps have been rendered in the current directory:\n"
            "- demo.jpg\n"
            "- demo.png\n"
            "Have a look!\n";

    }
    catch ( const mapnik::config_error & ex )
    {
        std::cerr << "### Configuration error: " << ex.what();
        return EXIT_FAILURE;
    }
    catch ( const std::exception & ex )
    {
        std::cerr << "### std::exception: " << ex.what();
        return EXIT_FAILURE;
    }
    catch ( ... )
    {
        std::cerr << "### Unknown exception." << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
<commit_msg>1. define BOOST_SPIRIT_THREADSAFE (should be defined in config.hpp??) to be compatible with the core library. 2. use mapnik install_dir as input argument.  3. Generate three images as in rundemo.py<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
// $Id$

// define before any includes
#define BOOST_SPIRIT_THREADSAFE

#include <mapnik/map.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/config_error.hpp>

#include <iostream>

int main ( int argc , char** argv)
{
    if (argc != 2)
    {
        std::cout << "usage: ./rundemo <mapnik_install_dir>\n";
        return EXIT_SUCCESS;
    }

    using namespace mapnik;
    try {
        std::cout << " running demo ... \n";
        std::string mapnik_dir(argv[1]);
        datasource_cache::instance()->register_datasources(mapnik_dir + "/lib/mapnik/input/");
        freetype_engine::register_font(mapnik_dir + "/lib/mapnik/fonts/DejaVuSans.ttf");

        Map m(800,600);
        m.set_background(color_factory::from_string("white"));

        // create styles

        // Provinces (polygon)
        feature_type_style provpoly_style;

        rule_type provpoly_rule_on;
        provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'"));
        provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));
        provpoly_style.add_rule(provpoly_rule_on);

        rule_type provpoly_rule_qc;
        provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'"));
        provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));
        provpoly_style.add_rule(provpoly_rule_qc);

        m.insert_style("provinces",provpoly_style);

        // Provinces (polyline)
        feature_type_style provlines_style;

        stroke provlines_stk (Color(0,0,0),1.0);
        provlines_stk.add_dash(8, 4);
        provlines_stk.add_dash(2, 2);
        provlines_stk.add_dash(2, 2);

        rule_type provlines_rule;
        provlines_rule.append(line_symbolizer(provlines_stk));
        provlines_style.add_rule(provlines_rule);

        m.insert_style("provlines",provlines_style);

        // Drainage
        feature_type_style qcdrain_style;

        rule_type qcdrain_rule;
        qcdrain_rule.set_filter(create_filter("[HYC] = 8"));
        qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));
        qcdrain_style.add_rule(qcdrain_rule);

        m.insert_style("drainage",qcdrain_style);

        // Roads 3 and 4 (The "grey" roads)
        feature_type_style roads34_style;
        rule_type roads34_rule;
        roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4"));
        stroke roads34_rule_stk(Color(171,158,137),2.0);
        roads34_rule_stk.set_line_cap(ROUND_CAP);
        roads34_rule_stk.set_line_join(ROUND_JOIN);
        roads34_rule.append(line_symbolizer(roads34_rule_stk));
        roads34_style.add_rule(roads34_rule);

        m.insert_style("smallroads",roads34_style);

        // Roads 2 (The thin yellow ones)
        feature_type_style roads2_style_1;
        rule_type roads2_rule_1;
        roads2_rule_1.set_filter(create_filter("[CLASS] = 2"));
        stroke roads2_rule_stk_1(Color(171,158,137),4.0);
        roads2_rule_stk_1.set_line_cap(ROUND_CAP);
        roads2_rule_stk_1.set_line_join(ROUND_JOIN);
        roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
        roads2_style_1.add_rule(roads2_rule_1);

        m.insert_style("road-border", roads2_style_1);

        feature_type_style roads2_style_2;
        rule_type roads2_rule_2;
        roads2_rule_2.set_filter(create_filter("[CLASS] = 2"));
        stroke roads2_rule_stk_2(Color(255,250,115),2.0);
        roads2_rule_stk_2.set_line_cap(ROUND_CAP);
        roads2_rule_stk_2.set_line_join(ROUND_JOIN);
        roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
        roads2_style_2.add_rule(roads2_rule_2);

        m.insert_style("road-fill", roads2_style_2);

        // Roads 1 (The big orange ones, the highways)
        feature_type_style roads1_style_1;
        rule_type roads1_rule_1;
        roads1_rule_1.set_filter(create_filter("[CLASS] = 1"));
        stroke roads1_rule_stk_1(Color(188,149,28),7.0);
        roads1_rule_stk_1.set_line_cap(ROUND_CAP);
        roads1_rule_stk_1.set_line_join(ROUND_JOIN);
        roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
        roads1_style_1.add_rule(roads1_rule_1);
        m.insert_style("highway-border", roads1_style_1);

        feature_type_style roads1_style_2;
        rule_type roads1_rule_2;
        roads1_rule_2.set_filter(create_filter("[CLASS] = 1"));
        stroke roads1_rule_stk_2(Color(242,191,36),5.0);
        roads1_rule_stk_2.set_line_cap(ROUND_CAP);
        roads1_rule_stk_2.set_line_join(ROUND_JOIN);
        roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
        roads1_style_2.add_rule(roads1_rule_2);
        m.insert_style("highway-fill", roads1_style_2);

        // Populated Places

        feature_type_style popplaces_style;
        rule_type popplaces_rule;
        text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0));
        popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));
        popplaces_text_symbolizer.set_halo_radius(1);
        popplaces_rule.append(popplaces_text_symbolizer);
        popplaces_style.add_rule(popplaces_rule);

        m.insert_style("popplaces",popplaces_style );

        // Layers
        // Provincial  polygons
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/boundaries";

            Layer lyr("Provinces");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("provinces");
            m.addLayer(lyr);
        }

        // Drainage
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/qcdrainage";
            Layer lyr("Quebec Hydrography");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("drainage");
            m.addLayer(lyr);
        }

        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/ontdrainage";

            Layer lyr("Ontario Hydrography");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("drainage");
            m.addLayer(lyr);
        }

        // Provincial boundaries
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/boundaries_l";
            Layer lyr("Provincial borders");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("provlines");
            m.addLayer(lyr);
        }

        // Roads
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/roads";
            Layer lyr("Roads");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("smallroads");
            lyr.add_style("road-border");
            lyr.add_style("road-fill");
            lyr.add_style("highway-border");
            lyr.add_style("highway-fill");

            m.addLayer(lyr);
        }
        // popplaces
        {
            parameters p;
            p["type"]="shape";
            p["file"]="../data/popplaces";
            p["encoding"] = "latin1";
            Layer lyr("Populated Places");
            lyr.set_datasource(datasource_cache::instance()->create(p));
            lyr.add_style("popplaces");
            m.addLayer(lyr);
        }

        m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,
                                     1706357.31328276,-25098.593149577));

        Image32 buf(m.getWidth(),m.getHeight());
        agg_renderer<Image32> ren(m,buf);
        ren.apply();

        save_to_file<ImageData32>("demo.jpg","jpeg",buf.data());
        save_to_file<ImageData32>("demo.png","png",buf.data());
        save_to_file<ImageData32>("demo256.png","png256",buf.data());
        std::cout << "Three maps have been rendered in the current directory:\n"
           "- demo.jpg\n"
           "- demo.png\n"
           "- demo256.png\n"
           "Have a look!\n";
    }
    catch ( const mapnik::config_error & ex )
    {
        std::cerr << "### Configuration error: " << ex.what();
        return EXIT_FAILURE;
    }
    catch ( const std::exception & ex )
    {
        std::cerr << "### std::exception: " << ex.what();
        return EXIT_FAILURE;
    }
    catch ( ... )
    {
        std::cerr << "### Unknown exception." << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
<|endoftext|>