<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "EnvisionPPCallbacks.h"

#include <algorithm>

#include <QtCore/QDebug>

#include <clang/Lex/MacroArgs.h>

EnvisionPPCallbacks::EnvisionPPCallbacks(clang::SourceManager& srcManager, std::string fileName,
													  QHash<QString, QString>& attributes)
	: sourceManager_{srcManager}, fileName_{fileName}, attributes_{attributes}  {}

void EnvisionPPCallbacks::MacroExpands(const clang::Token &MacroNameTok, const clang::MacroDirective *,
													clang::SourceRange range, const clang::MacroArgs *Args)
{
	// We only care about ATTRIBUTE macros:
	if (MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE" ||
		 MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE_VALUE_CUSTOM_RETURN")
	{
		// We only care about ATTRIBUTES in the currentFile:
		if (sourceManager_.getFilename(range.getBegin()) != fileName_) return;
		unsigned numArguments = Args->getNumArguments();
		Q_ASSERT(numArguments >= 3); // ATTRIBUTE macros have 3 arguments

		auto attributeName = QString::fromStdString(Args->getUnexpArgument(1u)->getIdentifierInfo()->getName().str());
		auto attributeSetter = QString::fromStdString(Args->getUnexpArgument(2u)->getIdentifierInfo()->getName().str());

		attributes_.insert(attributeName, attributeSetter);
	}
	else if (MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE_OOP_NAME_SYMBOL")
	{
		attributes_.insert("name", "setName");
	}

}

<commit_msg>Wrap ATTRIBUTE_VALUE attributes as well<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "EnvisionPPCallbacks.h"

#include <algorithm>

#include <QtCore/QDebug>

#include <clang/Lex/MacroArgs.h>

EnvisionPPCallbacks::EnvisionPPCallbacks(clang::SourceManager& srcManager, std::string fileName,
													  QHash<QString, QString>& attributes)
	: sourceManager_{srcManager}, fileName_{fileName}, attributes_{attributes}  {}

void EnvisionPPCallbacks::MacroExpands(const clang::Token &MacroNameTok, const clang::MacroDirective *,
													clang::SourceRange range, const clang::MacroArgs *Args)
{
	// We only care about ATTRIBUTE macros:
	if (MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE" ||
		 MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE_VALUE_CUSTOM_RETURN" ||
		 MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE_VALUE")
	{
		// We only care about ATTRIBUTES in the currentFile:
		if (sourceManager_.getFilename(range.getBegin()) != fileName_) return;
		unsigned numArguments = Args->getNumArguments();
		Q_ASSERT(numArguments >= 3); // ATTRIBUTE macros have 3 arguments

		auto attributeName = QString::fromStdString(Args->getUnexpArgument(1u)->getIdentifierInfo()->getName().str());
		auto attributeSetter = QString::fromStdString(Args->getUnexpArgument(2u)->getIdentifierInfo()->getName().str());

		attributes_.insert(attributeName, attributeSetter);
	}
	else if (MacroNameTok.getIdentifierInfo()->getName() == "ATTRIBUTE_OOP_NAME_SYMBOL")
	{
		attributes_.insert("name", "setName");
	}

}

<|endoftext|>


<commit_before>//Adapted from sites.google.com/site/stevenhalim/home/material
//or cpbook.net

#define EPS 0.000000001;

bool equal(double a, double b) { return fabs(a-b) < EPS; }

struct point;
struct line;
struct vec;

// use this whenever possible
//struct point { int x, y
struct point {
  double x,y;
  point();
  point(double _x, double _y);
  bool operator == (const point& o);
  bool operator< (const point& other);
  vec operator- (const point& other);
  point operator+ (const vec& v);
};

double dist(const point& p1, const point& p2) {
  return hypot(p1.x - p2.x, p1.y - p2.y);
}

struct line {
  double a, b, c;
  line (const point& p1, const point& p2);
  bool operator== (const line& other);
  //are they parallel
  bool operator|| (const line& other);
};

bool intersect(const line& l1, const line& l2, point& p) {
  // all points same
  if (l1 == l2) { return false; }
  // no intersection
  if (l1 || l2) { return false; }

  // solve system of 2 linear algebraic equations with 2 unknowns
  p.x = (double)(l2.b * l1.c - l1 b * l2.c) / (l2.a * l1.b - l1.a * l2.b);

  // test for vertical line (avoid div by zero)
  if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) / l1.b; }
  else { p.y = - (l2.a * p.x + l2.c) / l2.b; }

  return true;
}

//struct vec { int dx, dy;
struct vec {
  double dx, dy, mag;
  vec(double x, double y);
  vec(const point& from, const point& to) // convert 2 points to vector
  vec normalize();
  vec operator+ (const vec& other);
  //scale
  vec operator* (double s);
  //cross product
  vec operator* (const vec& other);
};

point::point() :x(0), y(0) {}
point::point(double _x, double _y)
  :x(_x), y(_y)
{}
bool point::operator == (const point& o)
{ return equal(x,o.x) && equal(y,o.y); }
bool point::operator < (const point& other) {
  if (fabs(x - other.x) > EPS) return x < other.x;
  return y < other.y;
}
vec point::operator- (const point& other){ return vec(other,*this); }
point point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); }

line::line (const point& p1, const point& p2) {
  // vertical line is handled nicely below
  //if (p1.x == p2.x) {
  if (equal(p1.x, p2.x)) {
    a = 1.0;
    b = 0.0;
    c = -p1.x;
  }

  else {
    a = -(double)(p1.y - p2.y) / (p1.x - p2.x);
    b = 1.0;
    c = -(double)(a * p1.x) - (b * p1.y);
  }
}

bool line::operator== (const line& other) {
  return (*this || other) && (fabs(c - other.c) < EPS);
}

bool line::operator|| (const line& other){
  // check coefficient a + b
  return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS);
}

vec::vec(double deltaX, double deltaY)
  : dx(deltaX), dy(deltaY)
{
  double magX = fabs(dx);
  double magY = fabs(dy);
  if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); }
  else if (magX < EPS) { mag = magY; }
  else if (magY < EPS) { mag = magX; }
  else { mag = 0; }
}

vec::vec(const point& from, const point& to)
  :vec(to.x - from.x, to.y - from.y)
{}
vec::normalize() { return vec(dx / mag, dy / mag); }
vec vec::operator+ (const vec & other){
  return vec(dx + other.dx, dy + other.dy);
}
vec vec::operator* (double s){ return vec(s * dx, s * dy); }
vec vec::operator* (const vec & other){

}
<commit_msg>Added polygon code<commit_after>//Adapted from sites.google.com/site/stevenhalim/home/material
//or cpbook.net
#include <cmath>
#include <vector>

#define EPS 0.000000001;
#define COLLINEAR 0
#define LEFT 1
#define RIGHT -1
#define polygon vector<point>

using namespace std;

bool equal(double a, double b) { return fabs(a-b) < EPS; }

struct point;
struct line;
struct vec;

// use this whenever possible
//struct point { int x, y
struct point {
  double x,y;
  point();
  point(double _x, double _y);
  bool operator == (const point& o);
  bool operator< (const point& other);
  vec operator- (const point& other);
  point operator+ (const vec& v);
};

struct line {
  double a, b, c;
  line (const point& p1, const point& p2);
  bool operator== (const line& other);
  //are they parallel
  bool operator|| (const line& other);
};

//struct vec { int dx, dy;
struct vec {
  double dx, dy, mag;
  vec(double x, double y);
  vec(const point& from, const point& to) // convert 2 points to vector
  vec normalize();
  vec operator+ (const vec& other);
  //scale
  vec operator* (double s);
  //dot product
  double operator* (const vec& other);
};

point::point() :x(0), y(0) {}
point::point(double _x, double _y)
  :x(_x), y(_y)
{}
bool point::operator == (const point& o)
{ return equal(x,o.x) && equal(y,o.y); }
bool point::operator < (const point& other) {
  if (fabs(x - other.x) > EPS) return x < other.x;
  return y < other.y;
}
vec point::operator- (const point& other){ return vec(other,*this); }
point point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); }
double dist(const point& p1, const point& p2) {
  return hypot(p1.x - p2.x, p1.y - p2.y);
}

line::line (const point& p1, const point& p2) {
  // vertical line is handled nicely below
  //if (p1.x == p2.x) {
  if (equal(p1.x, p2.x)) {
    a = 1.0;
    b = 0.0;
    c = -p1.x;
  }

  else {
    a = -(double)(p1.y - p2.y) / (p1.x - p2.x);
    b = 1.0;
    c = -(double)(a * p1.x) - (b * p1.y);
  }
}

bool line::operator== (const line& other) {
  return (*this || other) && (fabs(c - other.c) < EPS);
}

bool line::operator|| (const line& other){
  // check coefficient a + b
  return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS);
}

bool intersect(const line& l1, const line& l2, point& p) {
  // all points same
  if (l1 == l2) { return false; }
  // no intersection
  if (l1 || l2) { return false; }

  // solve system of 2 linear algebraic equations with 2 unknowns
  p.x = (double)(l2.b * l1.c - l1 b * l2.c) / (l2.a * l1.b - l1.a * l2.b);

  // test for vertical line (avoid div by zero)
  if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) / l1.b; }
  else { p.y = - (l2.a * p.x + l2.c) / l2.b; }

  return true;
}

vec::vec(double deltaX, double deltaY)
  : dx(deltaX), dy(deltaY)
{
  double magX = fabs(dx);
  double magY = fabs(dy);
  if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); }
  else if (magX < EPS) { mag = magY; }
  else if (magY < EPS) { mag = magX; }
  else { mag = 0; }
}

vec::vec(const point& from, const point& to)
  :vec(to.x - from.x, to.y - from.y)
{}
vec::normalize() { return vec(dx / mag, dy / mag); }
vec vec::operator+ (const vec & other){
  return vec(dx + other.dx, dy + other.dy);
}
vec vec::operator* (double s){ return vec(s * dx, s * dy); }
double vec::operator* (const vec & other){
  return dx * other.dx + dy * other.dy;
}

//square of triangle area
/*
int area2(point a, point b, point c) {
  return a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x;
}
*/

// square of distance between 2 points
int dist2(point a, point b) {
  int dx = a.x - b.x, dy = a.y - b.y; return dx * dx + dy * dy;
}

int turn(const point& a, const point& b, const point& c) {
  double result = (c.x - b.x) * (a.y - b.y) - (c.y - b.y) * (a.x - b.x);

  if (result < 0) return RIGHT; // a->B->C is a right turn
  if (result > 0) return LEFT; // a->B->C is a left turn

  return COLLINEAR; // a->B->C is a straight line, i.e. a, B, C are collinear
}

//important angle-sorting functor
class LeftTurnCmp{
private:
  point pivot;
public:
  LeftTurnCmp(const point& pivot) :pivot(pivot) {}
  bool operator()(const point& a, const& point b){
    if (turn(pivot, a, b) == COLLINEAR)
      return dist2(pivot, a) < dist2(pivot, b); // which one closer
    int d1x = a.x - pivot.x, d1y = a.y - pivot.y;
    int d2x = b.x - pivot.x, d2y = b.y - pivot.y;
    return (atan2((double)d1y, (double)d1x)
	    - atan2((double)d2y, (double)d2x)) < 0;
  }
};

//Counterclockwise starting from bottom-most point
void orderByAngle(polygon& p){
  // first, find p0 = point with lowest Y and if tie: rightmost X
  int lowestIndex = 0;
  int n = p.size();

  for (int i = 1; i < n; i++) {
    if (p[i].y < p[lowestIndex].y ||
	(p[i].y == p[lowestIndex].y && p[i].x > p[lowestIndex].x))
      { lowestIndex = i; }
  }

  swap(p[0],p[lowestIndex]);

  // second, sort points by angle w.r.t. lowest
  LeftTurnCmp angle_cmp(p[0]);
  sort(++p.begin(), p.end(), angle_cmp);
}

/* The following code assumes you have ordered the points! */

double perimeter(polygon& p) {
  double result = 0.0;

  //double x1, y1, x2, y2, dx, dy;
  for (int i = 0; i < p.size(); i++) {
    result += distance(p[i],p[(i+1)%p.size()]);
  }

  return result;
}

double determinant(polygon& p) {
  double result = 0;

  double x1, y1, x2, y2;
  for (int i = 0; i < p.size(); i++) {
    x1 = p[i].x; x2 = p[(i + 1) % p.size()].x;
    y1 = p[i].y; y2 = p[(i + 1) % p.size()].y;
    result += (x1 * y2 - x2 * y1);
  }

  return result;
}

// area is half of the determinant and the result may be a non-integer
double area(polygon& p)
{ return fabs(determinant(p)) / 2.0); }

//n must be >= 3 for this method to work
void getConvexHull(polygon& p, polygon& convexHull){
  int n = p.size();

  stack<point> S;
  point prev, now;
  S.push(p[n - 1]); // put two starting vertices into stack S
  S.push(p[0]);

  int i = 1; // and start checking the rest

  while (i < n) {
    // get the 2nd item from top of S
    now = S.top();
    S.pop();
    prev = S.top();
    S.push(now);

    if (turn(prev, now, p[i]) == LEFT) {
      S.push(p[i]); // accept
      i++;
    }

    // otherwise pop this point until we have a left turn
    else { S.pop(); }
  }

  while (!S.empty()) { // from stack back to vector
    convexHull.push_back(S.top());
    S.pop();
  }

  convexHull.pop_back(); // the last one is a duplicate of first one
}
<|endoftext|>


<commit_before>/*
    This file is part of KDE Kontact.

    Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
    Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <dcopclient.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kuniqueapplication.h>

#include <qlabel.h>
#if (QT_VERSION-0 >= 0x030200)
#include <qsplashscreen.h>
#else
#include "splash.h"
#endif

#include "mainwindow.h"

static const char description[] =
    I18N_NOOP( "A KDE Personal Information Manager" );

static const char version[] = "0.7.3 (Beta 1)";

int main(int argc, char **argv)
{
  KAboutData about( "kontact", I18N_NOOP( "Kontact" ), version, description,
                    KAboutData::License_GPL, I18N_NOOP("(C) 2001-2003 The Kontact developers"), 0, "http://kontact.kde.org", "kde-pim@kde.org" );
  about.addAuthor( "Daniel Molkentin", 0, "molkentin@kde.org" );
  about.addAuthor( "Don Sanders", 0, "sanders@kde.org" );
  about.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
  about.addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );
  about.addAuthor( "Sven Lüppken", 0, "sven@kde.org" );
  about.addAuthor( "Matthias Hoelzer-Kluepfel", I18N_NOOP("Original Author"), "mhk@kde.org" );

  KCmdLineArgs::init( argc, argv, &about );
  KUniqueApplication app;

  // show splash
#if (QT_VERSION-0 >= 0x030200)
  QPixmap splashPixmap( UserIcon( "splash" ) );

  QSplashScreen *splash = new QSplashScreen( splashPixmap );
  splash->show();
#else
  Kontact::Splash *splash = new Kontact::Splash( 0, "splash" );
  splash->show();
#endif

  // see if we are starting with session management
  if ( app.isRestored() ) {
      if (Kontact::MainWindow::canBeRestored(1))
	  //only restore a single main window! (Don);
	  (new Kontact::MainWindow)->restore(1);
  } else {
    // no session.. just start up normally
    Kontact::MainWindow *mw = new Kontact::MainWindow;
     mw->show();
  }

  // delete splash
  delete splash;

  bool ret = app.exec();
  while (KMainWindow::memberList->first())
      delete KMainWindow::memberList->first();
  return ret;
}
<commit_msg>Bring Kontact window to front when you start a new instance but an old one is still running. That fixes #68340.<commit_after>/*
    This file is part of KDE Kontact.

    Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
    Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <dcopclient.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kstartupinfo.h>
#include <kuniqueapplication.h>
#include <kwin.h>

#include <qlabel.h>
#if (QT_VERSION-0 >= 0x030200)
#include <qsplashscreen.h>
#else
#include "splash.h"
#endif

#include "mainwindow.h"

static const char description[] =
    I18N_NOOP( "A KDE Personal Information Manager" );

static const char version[] = "0.7.3 (Beta 1)";

class KontactApp : public KUniqueApplication {
  public:
    KontactApp() : mMainWindow( 0 ) {}
    ~KontactApp() {}

    int newInstance();

  private:
    Kontact::MainWindow *mMainWindow;
};

int KontactApp::newInstance()
{
  // show splash
#if (QT_VERSION-0 >= 0x030200)
  QPixmap splashPixmap( UserIcon( "splash" ) );

  QSplashScreen *splash = new QSplashScreen( splashPixmap );
  splash->show();
#else
  Kontact::Splash *splash = new Kontact::Splash( 0, "splash" );
  splash->show();
#endif

  if ( isRestored() ) {
    // There can only be one main window
    if ( KMainWindow::canBeRestored( 1 ) ) {
      mMainWindow = new Kontact::MainWindow;
      mMainWindow->show();
      mMainWindow->restore( 1 );
    }
  } else {
    if ( mMainWindow ) {
      mMainWindow->show();
      KWin::forceActiveWindow( mMainWindow->winId() );
      KStartupInfo::appStarted();
    } else {
      mMainWindow = new Kontact::MainWindow;
      mMainWindow->show();
    }
  }

  delete splash;

  return 0;
}

int main(int argc, char **argv)
{
  KAboutData about( "kontact", I18N_NOOP( "Kontact" ), version, description,
                    KAboutData::License_GPL, I18N_NOOP("(C) 2001-2003 The Kontact developers"), 0, "http://kontact.kde.org", "kde-pim@kde.org" );
  about.addAuthor( "Daniel Molkentin", 0, "molkentin@kde.org" );
  about.addAuthor( "Don Sanders", 0, "sanders@kde.org" );
  about.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
  about.addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );
  about.addAuthor( "Sven Lüppken", 0, "sven@kde.org" );
  about.addAuthor( "Matthias Hoelzer-Kluepfel", I18N_NOOP("Original Author"), "mhk@kde.org" );

  KCmdLineArgs::init( argc, argv, &about );

  if ( !KontactApp::start() ) {
    kdError() << "Kontact is already running!" << endl;
    return 0;
  }

  KontactApp app;

  bool ret = app.exec();
  while ( KMainWindow::memberList->first() )
    delete KMainWindow::memberList->first();

  return ret;
}
<|endoftext|>


<commit_before>/*
 * opencog/atomspace/Link.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/atomspace/AtomTable.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/Node.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>

#include "Link.h"

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

struct HandleComparison
{
    bool operator()(const Handle& h1, const Handle& h2) const {
        return (Handle::compare(h1, h2) < 0);
    }
};

void Link::resort(void)
{
    std::sort(_outgoing.begin(), _outgoing.end(), HandleComparison());
}

void Link::init(const std::vector<Handle>& outgoingVector)
{
    if (not classserver().isA(_type, LINK)) {
        throw InvalidParamException(TRACE_INFO,
            "Link ctor: Atom type is not a Link: '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }

    _outgoing = outgoingVector;
    // If the link is unordered, it will be normalized by sorting the
    // elements in the outgoing list.
    if (classserver().isA(_type, UNORDERED_LINK)) {
        resort();
    }
}

Link::~Link()
{
    DPRINTF("Deleting link:\n%s\n", this->toString().c_str());
}

std::string Link::toShortString(std::string indent)
{
    std::stringstream answer;
    std::string more_indent = indent + "  ";

    answer << indent << "(" << classserver().getTypeName(_type);
    answer << " " << getTruthValue()->toString() << "\n";

    // Here the target string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer << h->toShortString(more_indent);
        else
            answer << indent << "Undefined Atom!\n";
    }

    answer << indent << ") ; [" << _uuid << "]";

    if (_atomTable)
        answer << "[" << _atomTable->get_uuid() << "]\n";
    else
        answer << "[NULL]\n";

    return answer.str();
}

std::string Link::toString(std::string indent)
{
    std::string answer;
    std::string more_indent = indent + "  ";
#define BUFSZ 1024
    static char buf[BUFSZ];

    snprintf(buf, BUFSZ, "(%s (av %d %d %d) %s\n",
             classserver().getTypeName(_type).c_str(),
             (int)getAttentionValue()->getSTI(),
             (int)getAttentionValue()->getLTI(),
             (int)getAttentionValue()->getVLTI(),
             getTruthValue()->toString().c_str());
    answer = indent + buf;
    // Here the targets string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer += h->toString(more_indent);
        else
            answer += indent + "Undefined Atom!\n";
    }

    answer += indent + ") ; [" +
            std::to_string(_uuid).c_str() + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Link::isSource(Handle handle) const
{
    // On ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the handle given is equal to the first position,
    // true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        return arity > 0 && _outgoing[0] == handle;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the link is unordered, the outgoing set is scanned, and the
        // method returns true if any position is equal to the handle given.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isSource(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::isSource(size_t) invalid index argument");
    }

    // on ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the int passed is 0, true is returned.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i == 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unordered links, the only thing that matters is if the int passed
        // is valid (if it is within 0..arity).
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(int) unknown link type %d", _type);
    }
}

bool Link::isTarget(Handle handle) const
{
    // On ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets. So, it scans the
    // outgoing set from the second position searching for the given handle. If
    // it is found, true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        for (Arity i = 1; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the links is unordered, all the outgoing set is scanned.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isTarget(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::istarget(int) invalid index argument");
    }

    // on ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i != 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unorderd links, the only thing that matter is if the position is
        // valid.
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(int) unkown link type");
    }
    return false;
}

bool Link::operator==(const Atom& other) const
{
    if (getType() != other.getType()) return false;
    const Link& olink = dynamic_cast<const Link&>(other);

    Arity arity = getArity();
    if (arity != olink.getArity()) return false;
    for (Arity i = 0; i < arity; i++)
        if (_outgoing[i] != olink._outgoing[i]) return false;
    return true;
}

bool Link::operator!=(const Atom& other) const
{
    return !(*this == other);
}

<commit_msg>Perform an explicit atom compare<commit_after>/*
 * opencog/atomspace/Link.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/atomspace/AtomTable.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/Node.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>

#include "Link.h"

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

struct HandleComparison
{
    bool operator()(const Handle& h1, const Handle& h2) const {
        return (Handle::compare(h1, h2) < 0);
    }
};

void Link::resort(void)
{
    std::sort(_outgoing.begin(), _outgoing.end(), HandleComparison());
}

void Link::init(const std::vector<Handle>& outgoingVector)
{
    if (not classserver().isA(_type, LINK)) {
        throw InvalidParamException(TRACE_INFO,
            "Link ctor: Atom type is not a Link: '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }

    _outgoing = outgoingVector;
    // If the link is unordered, it will be normalized by sorting the
    // elements in the outgoing list.
    if (classserver().isA(_type, UNORDERED_LINK)) {
        resort();
    }
}

Link::~Link()
{
    DPRINTF("Deleting link:\n%s\n", this->toString().c_str());
}

std::string Link::toShortString(std::string indent)
{
    std::stringstream answer;
    std::string more_indent = indent + "  ";

    answer << indent << "(" << classserver().getTypeName(_type);
    answer << " " << getTruthValue()->toString() << "\n";

    // Here the target string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer << h->toShortString(more_indent);
        else
            answer << indent << "Undefined Atom!\n";
    }

    answer << indent << ") ; [" << _uuid << "]";

    if (_atomTable)
        answer << "[" << _atomTable->get_uuid() << "]\n";
    else
        answer << "[NULL]\n";

    return answer.str();
}

std::string Link::toString(std::string indent)
{
    std::string answer;
    std::string more_indent = indent + "  ";
#define BUFSZ 1024
    static char buf[BUFSZ];

    snprintf(buf, BUFSZ, "(%s (av %d %d %d) %s\n",
             classserver().getTypeName(_type).c_str(),
             (int)getAttentionValue()->getSTI(),
             (int)getAttentionValue()->getLTI(),
             (int)getAttentionValue()->getVLTI(),
             getTruthValue()->toString().c_str());
    answer = indent + buf;
    // Here the targets string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer += h->toString(more_indent);
        else
            answer += indent + "Undefined Atom!\n";
    }

    answer += indent + ") ; [" +
            std::to_string(_uuid).c_str() + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Link::isSource(Handle handle) const
{
    // On ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the handle given is equal to the first position,
    // true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        return arity > 0 && _outgoing[0] == handle;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the link is unordered, the outgoing set is scanned, and the
        // method returns true if any position is equal to the handle given.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isSource(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::isSource(size_t) invalid index argument");
    }

    // on ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the int passed is 0, true is returned.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i == 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unordered links, the only thing that matters is if the int passed
        // is valid (if it is within 0..arity).
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(int) unknown link type %d", _type);
    }
}

bool Link::isTarget(Handle handle) const
{
    // On ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets. So, it scans the
    // outgoing set from the second position searching for the given handle. If
    // it is found, true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        for (Arity i = 1; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the links is unordered, all the outgoing set is scanned.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isTarget(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::istarget(int) invalid index argument");
    }

    // on ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i != 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unorderd links, the only thing that matter is if the position is
        // valid.
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(int) unkown link type");
    }
    return false;
}

bool Link::operator==(const Atom& other) const
{
    if (getType() != other.getType()) return false;
    const Link& olink = dynamic_cast<const Link&>(other);

    Arity arity = getArity();
    if (arity != olink.getArity()) return false;
    for (Arity i = 0; i < arity; i++)
    {
        NodePtr tn(NodeCast(_outgoing[i]));
        NodePtr on(NodeCast(olink._outgoing[i]));
        if (tn and on and *tn != *on) return false;

        LinkPtr tl(LinkCast(_outgoing[i]));
        LinkPtr ol(LinkCast(olink._outgoing[i]));
        if (tl and ol and *tl != *ol) return false;
    }
    return true;
}

bool Link::operator!=(const Atom& other) const
{
    return !(*this == other);
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: test "x`uname -m|sed 's,i.86,i386,'`" = "xi386" || cat %s | %cling -Xclang -verify | FileCheck %s
// Not running on 32 bit due to aggregate return in getWithDtor(); see ROOT-5860

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"

cling::StoredValueRef V;
V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 1]

// Returns must put the result in the StoredValueRef.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(const char [5]) "true"]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 0]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::StoredValueRef) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

cling::StoredValueRef Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.
Result // CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef &) &0x{{.*}}]
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]
one // CHECK: (double) 1.000
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Check lifetime of objects in StoredValue
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::StoredValueRef* VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0
<commit_msg>We have more accurate results so adjust the test.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: test "x`uname -m|sed 's,i.86,i386,'`" = "xi386" || cat %s | %cling -Xclang -verify | FileCheck %s
// Not running on 32 bit due to aggregate return in getWithDtor(); see ROOT-5860

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"

cling::StoredValueRef V;
V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 1]

// Returns must put the result in the StoredValueRef.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(const char [5]) "true"]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 0]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::StoredValueRef) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

cling::StoredValueRef Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.
Result // CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef) boxes [(int *) 0x12]]
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]
one // CHECK: (double) 1.000
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Check lifetime of objects in StoredValue
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::StoredValueRef* VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010-2011 Dmitry Marakasov
 *
 * This file is part of glosm.
 *
 * glosm is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * glosm is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with glosm.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <glosm/GeometryOperations.hh>
#include <glosm/geomath.h>
#include <math.h>

bool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {
	if (one.y < y && two.y < y)
		return false;

	if (one.y > y && two.y > y)
		return false;

	float t = (float)(one.y - y) / (float)(one.y - two.y);

	float x = (float)(two.x - one.x) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(one.x + round(x), y, one.z + round(z));
	return true;
}

bool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {
	if (one.x < x && two.x < x)
		return false;

	if (one.x > x && two.x > x)
		return false;

	float t = (float)(one.x - x) / (float)(one.x - two.x);

	float y = (float)(two.y - one.y) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(x, one.y + round(y), one.z + round(z));
	return true;
}

bool IntersectPlaneWithVertical(const Vector3i& a, const Vector3i& b, const Vector3i& c, const Vector2i& xy, Vector3i& out) {
	/* Equation of a plane:
	 * |  x-x1  y-y1  z-z1 |
	 * | x2-x1 y2-y1 z2-y1 | = 0
	 * | x3-x1 y3-y1 z3-y1 |
	 *
	 * Determinant:
	 * | a11 a12 a13 |
	 * | a21 a22 a23 | = a11a22a33 − a11a23a32 − a12a21a33 + a12a23a31 + a13a21a32 − a13a22a31
	 * | a31 a32 a33 |
	 *
	 * In terms of array:
	 * | 0 1 2 |
	 * | 3 4 5 | = 0*4*8 - 0*5*7 - 1*3*8 + 1*5*6 + 2*3*7 - 2*4*6
	 * | 6 7 8 |
	 */
	float m[9] = {
		(float)(xy.x - a.x), (float)(xy.y - a.y), 0.0 /* to find */,
		(float)(b.x - a.x), (float)(b.y - a.y), (float)(b.z - a.z),
		(float)(c.x - a.x), (float)(c.y - a.y), (float)(c.z - a.z)
	};

	float divisor = m[3]*m[7] - m[4]*m[6];

	if (fabsf(divisor) < std::numeric_limits<float>::epsilon())
		return false;

	float divided = -m[0]*m[4]*m[8] + m[0]*m[5]*m[7] + m[1]*m[3]*m[8] - m[1]*m[5]*m[6];

	out = Vector3i(xy.x, xy.y, (osmint_t)round(divided/divisor) + a.z);
	return true;
}

bool IntersectSegmentWithBBoxSide(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, BBoxi::Side side, Vector3i& out) {
	switch (side) {
	case BBoxi::LEFT:
		return IntersectSegmentWithVertical(one, two, bbox.left, out);
	case BBoxi::BOTTOM:
		return IntersectSegmentWithHorizontal(one, two, bbox.bottom, out);
	case BBoxi::RIGHT:
		return IntersectSegmentWithVertical(one, two, bbox.right, out);
	case BBoxi::TOP:
		return IntersectSegmentWithHorizontal(one, two, bbox.top, out);
	default:
		return false;
	}
}

BBoxi::Side IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	if (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))
		return BBoxi::LEFT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out)  && bbox.Contains(out))
		return BBoxi::BOTTOM;

	if (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))
		return BBoxi::RIGHT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))
		return BBoxi::TOP;

	return BBoxi::NONE;
}

BBoxi::Side IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	if (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))
		return BBoxi::TOP;

	if (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))
		return BBoxi::RIGHT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out)  && bbox.Contains(out))
		return BBoxi::BOTTOM;

	if (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))
		return BBoxi::LEFT;

	return BBoxi::NONE;
}

bool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {
	if (bbox.Contains(one)) {
		/* one is in the bbox */
		outone = one;
		if (bbox.Contains(two)) {
			/* both points are in the bbox */
			outtwo = two;
		} else {
			/* other point is outside - find intersection */
			return IntersectSegmentWithBBox(one, two, bbox, outtwo);
		}
	} else if (bbox.Contains(two)) {
		/* two is inside, one is outside */
		outtwo = two;
		return IntersectSegmentWithBBox(one, two, bbox, outone);
	}

	/* both points are outside, find two points of intersection */
	return IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo);
}

Vector3d ToLocalMetric(Vector3i what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	double dx = (double)(what.x - ref.x)/3600000000.0*WGS84_EARTH_EQ_LENGTH*cos(lat);
	double dy = (double)(what.y - ref.y)/3600000000.0*WGS84_EARTH_EQ_LENGTH;
	double dz = (double)(what.z - ref.z)/1000.0;

	return Vector3f(dx, dy, dz);
}

Vector3i FromLocalMetric(Vector3d what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	int x = ref.x + round(what.x*3600000000.0/WGS84_EARTH_EQ_LENGTH/cos(lat));
	int y = ref.y + round(what.y*3600000000.0/WGS84_EARTH_EQ_LENGTH);
	int z = ref.z + round(what.z*1000.0);

	return Vector3i(x, y, z);
}

<commit_msg>Fix edge case bug in FromLocalMetric()<commit_after>/*
 * Copyright (C) 2010-2011 Dmitry Marakasov
 *
 * This file is part of glosm.
 *
 * glosm is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * glosm is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with glosm.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <glosm/GeometryOperations.hh>
#include <glosm/geomath.h>
#include <math.h>

bool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {
	if (one.y < y && two.y < y)
		return false;

	if (one.y > y && two.y > y)
		return false;

	float t = (float)(one.y - y) / (float)(one.y - two.y);

	float x = (float)(two.x - one.x) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(one.x + round(x), y, one.z + round(z));
	return true;
}

bool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {
	if (one.x < x && two.x < x)
		return false;

	if (one.x > x && two.x > x)
		return false;

	float t = (float)(one.x - x) / (float)(one.x - two.x);

	float y = (float)(two.y - one.y) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(x, one.y + round(y), one.z + round(z));
	return true;
}

bool IntersectPlaneWithVertical(const Vector3i& a, const Vector3i& b, const Vector3i& c, const Vector2i& xy, Vector3i& out) {
	/* Equation of a plane:
	 * |  x-x1  y-y1  z-z1 |
	 * | x2-x1 y2-y1 z2-y1 | = 0
	 * | x3-x1 y3-y1 z3-y1 |
	 *
	 * Determinant:
	 * | a11 a12 a13 |
	 * | a21 a22 a23 | = a11a22a33 − a11a23a32 − a12a21a33 + a12a23a31 + a13a21a32 − a13a22a31
	 * | a31 a32 a33 |
	 *
	 * In terms of array:
	 * | 0 1 2 |
	 * | 3 4 5 | = 0*4*8 - 0*5*7 - 1*3*8 + 1*5*6 + 2*3*7 - 2*4*6
	 * | 6 7 8 |
	 */
	float m[9] = {
		(float)(xy.x - a.x), (float)(xy.y - a.y), 0.0 /* to find */,
		(float)(b.x - a.x), (float)(b.y - a.y), (float)(b.z - a.z),
		(float)(c.x - a.x), (float)(c.y - a.y), (float)(c.z - a.z)
	};

	float divisor = m[3]*m[7] - m[4]*m[6];

	if (fabsf(divisor) < std::numeric_limits<float>::epsilon())
		return false;

	float divided = -m[0]*m[4]*m[8] + m[0]*m[5]*m[7] + m[1]*m[3]*m[8] - m[1]*m[5]*m[6];

	out = Vector3i(xy.x, xy.y, (osmint_t)round(divided/divisor) + a.z);
	return true;
}

bool IntersectSegmentWithBBoxSide(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, BBoxi::Side side, Vector3i& out) {
	switch (side) {
	case BBoxi::LEFT:
		return IntersectSegmentWithVertical(one, two, bbox.left, out);
	case BBoxi::BOTTOM:
		return IntersectSegmentWithHorizontal(one, two, bbox.bottom, out);
	case BBoxi::RIGHT:
		return IntersectSegmentWithVertical(one, two, bbox.right, out);
	case BBoxi::TOP:
		return IntersectSegmentWithHorizontal(one, two, bbox.top, out);
	default:
		return false;
	}
}

BBoxi::Side IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	if (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))
		return BBoxi::LEFT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out)  && bbox.Contains(out))
		return BBoxi::BOTTOM;

	if (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))
		return BBoxi::RIGHT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))
		return BBoxi::TOP;

	return BBoxi::NONE;
}

BBoxi::Side IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	if (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))
		return BBoxi::TOP;

	if (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))
		return BBoxi::RIGHT;

	if (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out)  && bbox.Contains(out))
		return BBoxi::BOTTOM;

	if (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))
		return BBoxi::LEFT;

	return BBoxi::NONE;
}

bool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {
	if (bbox.Contains(one)) {
		/* one is in the bbox */
		outone = one;
		if (bbox.Contains(two)) {
			/* both points are in the bbox */
			outtwo = two;
		} else {
			/* other point is outside - find intersection */
			return IntersectSegmentWithBBox(one, two, bbox, outtwo);
		}
	} else if (bbox.Contains(two)) {
		/* two is inside, one is outside */
		outtwo = two;
		return IntersectSegmentWithBBox(one, two, bbox, outone);
	}

	/* both points are outside, find two points of intersection */
	return IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo);
}

Vector3d ToLocalMetric(Vector3i what, Vector3i ref) {
	const double coslat = cos(ref.y/1800000000.0*M_PI);

	double dx = (double)(what.x - ref.x)/3600000000.0*WGS84_EARTH_EQ_LENGTH*coslat;
	double dy = (double)(what.y - ref.y)/3600000000.0*WGS84_EARTH_EQ_LENGTH;
	double dz = (double)(what.z - ref.z)/1000.0;

	return Vector3f(dx, dy, dz);
}

Vector3i FromLocalMetric(Vector3d what, Vector3i ref) {
	const double coslat = cos(ref.y/1800000000.0*M_PI);

	int x = ref.x;
	if (coslat > std::numeric_limits<double>::epsilon())
		x += round(what.x*3600000000.0/WGS84_EARTH_EQ_LENGTH/coslat);

	int y = ref.y + round(what.y*3600000000.0/WGS84_EARTH_EQ_LENGTH);
	int z = ref.z + round(what.z*1000.0);

	return Vector3i(x, y, z);
}

<|endoftext|>


<commit_before>#include "task_synthetic_shapes.h"
#include "libnanocv/loss.h"
#include "libnanocv/util/math.hpp"
#include "libnanocv/util/random.hpp"

namespace ncv
{
        synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration)
                :       task_t(configuration),
                        m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)),
                        m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)),
                        m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)),
                        m_folds(1),
                        m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)),
                        m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024))
        {
        }

        namespace
        {
                rgba_t make_transparent_color()
                {
                        return 0;
                }

                rgba_t make_light_color()
                {
                        random_t<rgba_t> rng_red(175, 255);
                        random_t<rgba_t> rng_green(175, 255);
                        random_t<rgba_t> rng_blue(175, 255);

                        return color::make_rgba(rng_red(), rng_green(), rng_blue());
                }

                rect_t make_rect(coord_t rows, coord_t cols)
                {
                        random_t<coord_t> rng(2, std::min(rows / 4, cols / 4));

                        const coord_t dx = rng();
                        const coord_t dy = rng();
                        const coord_t dw = rng();
                        const coord_t dh = rng();

                        return rect_t(dx, dy, cols - dx - dw, rows - dy - dh);
                }

                rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h)
                {
                        random_t<coord_t> rng(2, std::min(w / 4, h / 4));

                        const coord_t dx = rng();
                        const coord_t dy = rng();
                        const coord_t dw = rng();
                        const coord_t dh = rng();

                        return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh);
                }

                rect_t make_interior_rect(const rect_t& rect)
                {
                        return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height());
                }

                image_t make_filled_rect(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        image.fill(rect, make_light_color());

                        return image;
                }

                image_t make_hollow_rect(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        image.fill(rect, make_light_color());
                        image.fill(make_interior_rect(rect), make_transparent_color());

                        return image;
                }

                void fill_circle(image_t& image, const rect_t& rect)
                {
                        const point_t center = rect.center();
                        const coord_t cx = center.x();
                        const coord_t cy = center.y();

                        const coord_t radius = (std::min(rect.width(), rect.height()) + 1) / 2;

                        const rgba_t rgba = make_light_color();

                        for (coord_t x = rect.left(); x < rect.right(); x ++)
                        {
                                for (coord_t y = rect.top(); y < rect.bottom(); y ++)
                                {
                                        if (math::square(x - cx) + math::square(y - cy) < radius * radius)
                                        {
                                                image.set(y, x, rgba);
                                        }
                                }
                        }
                }

                image_t make_filled_circle(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        fill_circle(image, rect);

                        return image;
                }
        }

        bool synthetic_shapes_task_t::load(const string_t &)
        {
                random_t<size_t> rng_protocol(1, 10);
                random_t<size_t> rng_output(1, osize());

                random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) / scalar_t(8));

                const coord_t rows = static_cast<coord_t>(irows());
                const coord_t cols = static_cast<coord_t>(icols());

                clear_memory(0);

                for (size_t f = 0; f < fsize(); f ++)
                {
                        for (size_t i = 0; i < m_size; i ++)
                        {
                                // random protocol: train vs. test
                                const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test;

                                // random output class: #dots
                                const size_t o = rng_output();

                                // generate random image background
                                image_t image(irows(), icols(), color());
                                image.fill(make_light_color());
                                image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss());

                                // generate random shapes
                                image_t shape;

                                switch (o)
                                {
                                case 1:         shape = make_filled_rect(rows, cols); break;
                                case 2:         shape = make_hollow_rect(rows, cols); break;
                                case 3:         shape = make_filled_circle(rows, cols); break;
                                default:        break;
                                }

                                image.alpha_blend(shape.rgba());

                                add_image(image);

                                // generate sample
                                sample_t sample(n_images() - 1, sample_region(0, 0));
                                switch (o)
                                {
                                case 1:         sample.m_label = "filled_rectangle"; break;
                                case 2:         sample.m_label = "hollow_rectangle"; break;
                                case 3:         sample.m_label = "filled_circle"; break;
                                default:        sample.m_label = "unkown"; break;
                                }

                                sample.m_target = ncv::class_target(o - 1, osize());
                                sample.m_fold = {f, p};
                                add_sample(sample);
                        }
                }

                return true;
        }
}
<commit_msg>draw hallow circles<commit_after>#include "task_synthetic_shapes.h"
#include "libnanocv/loss.h"
#include "libnanocv/util/math.hpp"
#include "libnanocv/util/random.hpp"

namespace ncv
{
        synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration)
                :       task_t(configuration),
                        m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)),
                        m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)),
                        m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)),
                        m_folds(1),
                        m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)),
                        m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024))
        {
        }

        namespace
        {
                rgba_t make_transparent_color()
                {
                        return 0;
                }

                rgba_t make_light_color()
                {
                        random_t<rgba_t> rng_red(175, 255);
                        random_t<rgba_t> rng_green(175, 255);
                        random_t<rgba_t> rng_blue(175, 255);

                        return color::make_rgba(rng_red(), rng_green(), rng_blue());
                }

                rect_t make_rect(coord_t rows, coord_t cols)
                {
                        random_t<coord_t> rng(2, std::min(rows / 4, cols / 4));

                        const coord_t dx = rng();
                        const coord_t dy = rng();
                        const coord_t dw = rng();
                        const coord_t dh = rng();

                        return rect_t(dx, dy, cols - dx - dw, rows - dy - dh);
                }

                rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h)
                {
                        random_t<coord_t> rng(2, std::min(w / 4, h / 4));

                        const coord_t dx = rng();
                        const coord_t dy = rng();
                        const coord_t dw = rng();
                        const coord_t dh = rng();

                        return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh);
                }

                rect_t make_interior_rect(const rect_t& rect)
                {
                        return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height());
                }

                image_t make_filled_rect(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        image.fill(rect, make_light_color());

                        return image;
                }

                image_t make_hollow_rect(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        image.fill(rect, make_light_color());
                        image.fill(make_interior_rect(rect), make_transparent_color());

                        return image;
                }

                void fill_circle(image_t& image, const rect_t& rect, rgba_t rgba)
                {
                        const point_t center = rect.center();
                        const coord_t cx = center.x();
                        const coord_t cy = center.y();

                        const coord_t radius = (std::min(rect.width(), rect.height()) + 1) / 2;

                        for (coord_t x = rect.left(); x < rect.right(); x ++)
                        {
                                for (coord_t y = rect.top(); y < rect.bottom(); y ++)
                                {
                                        if (math::square(x - cx) + math::square(y - cy) < radius * radius)
                                        {
                                                image.set(y, x, rgba);
                                        }
                                }
                        }
                }

                image_t make_filled_circle(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        fill_circle(image, rect, make_light_color());

                        return image;
                }

                image_t make_hollow_circle(coord_t rows, coord_t cols)
                {
                        const rect_t rect = make_rect(rows, cols);

                        image_t image(rows, cols, color_mode::rgba);

                        image.fill(make_transparent_color());
                        fill_circle(image, rect, make_light_color());
                        fill_circle(image, make_interior_rect(rect), make_transparent_color());

                        return image;
                }
        }

        bool synthetic_shapes_task_t::load(const string_t &)
        {
                random_t<size_t> rng_protocol(1, 10);
                random_t<size_t> rng_output(1, osize());

                random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) / scalar_t(8));

                const coord_t rows = static_cast<coord_t>(irows());
                const coord_t cols = static_cast<coord_t>(icols());

                clear_memory(0);

                for (size_t f = 0; f < fsize(); f ++)
                {
                        for (size_t i = 0; i < m_size; i ++)
                        {
                                // random protocol: train vs. test
                                const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test;

                                // random output class: #dots
                                const size_t o = rng_output();

                                // generate random image background
                                image_t image(irows(), icols(), color());
                                image.fill(make_light_color());
                                image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss());

                                // generate random shapes
                                image_t shape;

                                switch (o)
                                {
                                case 1:         shape = make_filled_rect(rows, cols); break;
                                case 2:         shape = make_hollow_rect(rows, cols); break;
                                case 3:         shape = make_filled_circle(rows, cols); break;
                                case 4:         shape = make_hollow_circle(rows, cols); break;
                                default:        break;
                                }

                                shape.random_noise(color_channel::rgba, -10.0, +10.0, rng_gauss() * 0.5);
                                image.alpha_blend(shape.rgba());

                                add_image(image);

                                // generate sample
                                sample_t sample(n_images() - 1, sample_region(0, 0));
                                switch (o)
                                {
                                case 1:         sample.m_label = "filled_rectangle"; break;
                                case 2:         sample.m_label = "hollow_rectangle"; break;
                                case 3:         sample.m_label = "filled_circle"; break;
                                case 4:         sample.m_label = "hollow_circle"; break;
                                default:        sample.m_label = "unkown"; break;
                                }

                                sample.m_target = ncv::class_target(o - 1, osize());
                                sample.m_fold = {f, p};
                                add_sample(sample);
                        }
                }

                return true;
        }
}
<|endoftext|>


<commit_before>/*
 *  Author(s):
 *  - Chris  Kilner <ckilner@aldebaran-robotics.com>
 *  - Cedric Gestes <gestes@aldebaran-robotics.com>
 *
 *  Copyright (C) 2010, 2011, 2012 Aldebaran Robotics
 */

#pragma once
#ifndef _QIMESSAGING_DATASTREAM_HPP_
#define _QIMESSAGING_DATASTREAM_HPP_

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <stdint.h>
#include <qimessaging/api.hpp>
#include <qimessaging/value.hpp>
#include <qimessaging/buffer.hpp>

namespace qi {

#if 0
#include <iostream>
#define __QI_DEBUG_SERIALIZATION_W(x, extra) {                  \
    std::string sig = qi::signature< x >::value();              \
    std::cout << "write(" << sig << ")" << extra << std::endl;  \
  }

#define __QI_DEBUG_SERIALIZATION_R(x, extra) {                  \
    std::string sig = qi::signature< x >::value();              \
    std::cout << "read (" << sig << ")" << extra << std::endl;  \
  }

#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) {                    \
    std::string sig = qi::signature< x >::value();                      \
    std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
  }

#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) {                    \
    std::string sig = qi::signature< x >::value();                      \
    std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
  }
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif

  class QIMESSAGING_API DataStream {
  public:

    /// Default constructor.
    /// <param name="data">The data.</param>
    explicit DataStream(const qi::Buffer &buffer);
    explicit DataStream(qi::Buffer &buffer);

    size_t read(void *data, size_t len);
    void writeString(const char *str, size_t len);

    DataStream& operator<<(bool     b);
    DataStream& operator<<(char     c);
    DataStream& operator<<(int8_t   c);
    DataStream& operator<<(int16_t  s);
    DataStream& operator<<(int32_t  i);
    DataStream& operator<<(int64_t  l);

    DataStream& operator<<(uint8_t  uc);
    DataStream& operator<<(uint16_t us);
    DataStream& operator<<(uint32_t ui);
    DataStream& operator<<(uint64_t ul);
    DataStream& operator<<(float    f);
    DataStream& operator<<(double   d);
    DataStream& operator<<(const char *);
    DataStream& operator<<(const std::string& i);

    DataStream& operator>>(bool     &b);
    DataStream& operator>>(char     &c);

    DataStream& operator>>(int8_t   &c);
    DataStream& operator>>(int16_t  &i);
    DataStream& operator>>(int32_t  &i);
    DataStream& operator>>(int64_t  &l);

    DataStream& operator>>(uint8_t  &uc);
    DataStream& operator>>(uint16_t &us);
    DataStream& operator>>(uint32_t &ui);
    DataStream& operator>>(uint64_t &ul);

    DataStream& operator>>(float  &i);
    DataStream& operator>>(double &i);
    DataStream& operator>>(std::string& i);

    /// Gets the string.
    /// <returns> The string representation of the serialized message</returns>
    //void *data() { return _buffer->data(); }

  private:
    qi::Buffer  _buffer;
    bool        _ro;

    /// Default constructor.
    DataStream()
    {}

  };

  template<typename T>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::list<T> &v) {
    typedef std::list<T> _typefordebug;
    typename std::list<T>::const_iterator it = v.begin();
    typename std::list<T>::const_iterator end = v.end();

    sd << (uint32_t)v.size();
    for (; it != end; ++it) {
      sd << *it;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator>>(qi::DataStream &sd, std::list<T> &v) {
    typedef std::list<T> _typefordebug;
    uint32_t sz;
    sd >> sz;
    v.clear();
    if (sz) {
      try {
        v.resize(sz);
      } catch (const std::exception &e) {
        qiLogError("qi.DataStream") << "std::list<T> serialization error, could not resize to "
                                    << sz;
        return sd;
      }
      typename std::list<T>::iterator it = v.begin();
      typename std::list<T>::iterator end = v.end();
      for (; it != end; ++it) {
        sd >> *it;
      }
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::vector<T> &v) {
    typedef std::vector<T> _typefordebug;
    typename std::vector<T>::const_iterator it = v.begin();
    typename std::vector<T>::const_iterator end = v.end();

    sd << (uint32_t)v.size();
    for (; it != end; ++it) {
      sd << *it;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator>>(qi::DataStream &sd, std::vector<T> &v) {
    typedef std::vector<T> _typefordebug;
    uint32_t sz = 0;
    sd >> sz;
    v.clear();
    if (sz) {
      try {
        v.resize(sz);
      } catch (const std::exception &e) {
        qiLogError("qi.DataStream") << "std::vector<T> serialization error, could not resize to "
                                    << sz;
        return sd;
      }
      typename std::vector<T>::iterator it = v.begin();
      typename std::vector<T>::iterator end = v.end();
      for (; it != end; ++it) {
        sd >> *it;
      }
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);
    return sd;
  }

  template<typename K, typename V>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::map<K, V> &m) {
    typedef  std::map<K,V> _typefordebug;
    typename std::map<K,V>::const_iterator it = m.begin();
    typename std::map<K,V>::const_iterator end = m.end();

    sd << (uint32_t)m.size();

    for (; it != end; ++it) {
      sd << it->first;
      sd << it->second;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, m);
    return sd;
  }

  template<typename K, typename V>
  qi::DataStream &operator>>(qi::DataStream &sd, std::map<K, V>  &m) {
    typedef  std::map<K,V> _typefordebug;
    uint32_t sz;
    sd >> sz;
    m.clear();

    for(uint32_t i=0; i < sz; ++i) {
      K k;
      V v;
      sd >> k;
      sd >> v;
      m[k] = v;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, m);
    return sd;
  };

  QIMESSAGING_API qi::DataStream &operator>>(qi::DataStream &sd, qi::Value &value);
  QIMESSAGING_API qi::DataStream &operator<<(qi::DataStream &sd, const qi::Value &value);
}

#endif  // _QIMESSAGING_DATASTREAM_HPP_
<commit_msg>Fix compilation warning on windows<commit_after>/*
 *  Author(s):
 *  - Chris  Kilner <ckilner@aldebaran-robotics.com>
 *  - Cedric Gestes <gestes@aldebaran-robotics.com>
 *
 *  Copyright (C) 2010, 2011, 2012 Aldebaran Robotics
 */

#pragma once
#ifndef _QIMESSAGING_DATASTREAM_HPP_
#define _QIMESSAGING_DATASTREAM_HPP_

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <stdint.h>
#include <qimessaging/api.hpp>
#include <qimessaging/value.hpp>
#include <qimessaging/buffer.hpp>

namespace qi {

#if 0
#include <iostream>
#define __QI_DEBUG_SERIALIZATION_W(x, extra) {                  \
    std::string sig = qi::signature< x >::value();              \
    std::cout << "write(" << sig << ")" << extra << std::endl;  \
  }

#define __QI_DEBUG_SERIALIZATION_R(x, extra) {                  \
    std::string sig = qi::signature< x >::value();              \
    std::cout << "read (" << sig << ")" << extra << std::endl;  \
  }

#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) {                    \
    std::string sig = qi::signature< x >::value();                      \
    std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
  }

#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) {                    \
    std::string sig = qi::signature< x >::value();                      \
    std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
  }
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif

  class QIMESSAGING_API DataStream {
  public:

    /// Default constructor.
    /// <param name="data">The data.</param>
    explicit DataStream(const qi::Buffer &buffer);
    explicit DataStream(qi::Buffer &buffer);

    size_t read(void *data, size_t len);
    void writeString(const char *str, size_t len);

    DataStream& operator<<(bool     b);
    DataStream& operator<<(char     c);
    DataStream& operator<<(int8_t   c);
    DataStream& operator<<(int16_t  s);
    DataStream& operator<<(int32_t  i);
    DataStream& operator<<(int64_t  l);

    DataStream& operator<<(uint8_t  uc);
    DataStream& operator<<(uint16_t us);
    DataStream& operator<<(uint32_t ui);
    DataStream& operator<<(uint64_t ul);
    DataStream& operator<<(float    f);
    DataStream& operator<<(double   d);
    DataStream& operator<<(const char *);
    DataStream& operator<<(const std::string& i);

    DataStream& operator>>(bool     &b);
    DataStream& operator>>(char     &c);

    DataStream& operator>>(int8_t   &c);
    DataStream& operator>>(int16_t  &i);
    DataStream& operator>>(int32_t  &i);
    DataStream& operator>>(int64_t  &l);

    DataStream& operator>>(uint8_t  &uc);
    DataStream& operator>>(uint16_t &us);
    DataStream& operator>>(uint32_t &ui);
    DataStream& operator>>(uint64_t &ul);

    DataStream& operator>>(float  &i);
    DataStream& operator>>(double &i);
    DataStream& operator>>(std::string& i);

    /// Gets the string.
    /// <returns> The string representation of the serialized message</returns>
    //void *data() { return _buffer->data(); }

  private:
    qi::Buffer  _buffer;
    bool        _ro;

    /// Default constructor.
    DataStream()
    {}

  };

  template<typename T>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::list<T> &v) {
    typedef std::list<T> _typefordebug;
    typename std::list<T>::const_iterator it = v.begin();
    typename std::list<T>::const_iterator end = v.end();

    sd << (uint32_t)v.size();
    for (; it != end; ++it) {
      sd << *it;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator>>(qi::DataStream &sd, std::list<T> &v) {
    typedef std::list<T> _typefordebug;
    uint32_t sz;
    sd >> sz;
    v.clear();
    if (sz) {
      try {
        v.resize(sz);
      } catch (const std::exception &) {
        qiLogError("qi.DataStream") << "std::list<T> serialization error, could not resize to "
                                    << sz;
        return sd;
      }
      typename std::list<T>::iterator it = v.begin();
      typename std::list<T>::iterator end = v.end();
      for (; it != end; ++it) {
        sd >> *it;
      }
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::vector<T> &v) {
    typedef std::vector<T> _typefordebug;
    typename std::vector<T>::const_iterator it = v.begin();
    typename std::vector<T>::const_iterator end = v.end();

    sd << (uint32_t)v.size();
    for (; it != end; ++it) {
      sd << *it;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);
    return sd;
  }

  template<typename T>
  qi::DataStream &operator>>(qi::DataStream &sd, std::vector<T> &v) {
    typedef std::vector<T> _typefordebug;
    uint32_t sz = 0;
    sd >> sz;
    v.clear();
    if (sz) {
      try {
        v.resize(sz);
      } catch (const std::exception &) {
        qiLogError("qi.DataStream") << "std::vector<T> serialization error, could not resize to "
                                    << sz;
        return sd;
      }
      typename std::vector<T>::iterator it = v.begin();
      typename std::vector<T>::iterator end = v.end();
      for (; it != end; ++it) {
        sd >> *it;
      }
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);
    return sd;
  }

  template<typename K, typename V>
  qi::DataStream &operator<<(qi::DataStream &sd, const std::map<K, V> &m) {
    typedef  std::map<K,V> _typefordebug;
    typename std::map<K,V>::const_iterator it = m.begin();
    typename std::map<K,V>::const_iterator end = m.end();

    sd << (uint32_t)m.size();

    for (; it != end; ++it) {
      sd << it->first;
      sd << it->second;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, m);
    return sd;
  }

  template<typename K, typename V>
  qi::DataStream &operator>>(qi::DataStream &sd, std::map<K, V>  &m) {
    typedef  std::map<K,V> _typefordebug;
    uint32_t sz;
    sd >> sz;
    m.clear();

    for(uint32_t i=0; i < sz; ++i) {
      K k;
      V v;
      sd >> k;
      sd >> v;
      m[k] = v;
    }
    __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, m);
    return sd;
  };

  QIMESSAGING_API qi::DataStream &operator>>(qi::DataStream &sd, qi::Value &value);
  QIMESSAGING_API qi::DataStream &operator<<(qi::DataStream &sd, const qi::Value &value);
}

#endif  // _QIMESSAGING_DATASTREAM_HPP_
<|endoftext|>