<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "historycompleter.h"
#include "fancylineedit.h"

#include "qtcassert.h"

#include <QSettings>

#include <QItemDelegate>
#include <QKeyEvent>
#include <QListView>
#include <QPainter>

namespace Utils {
namespace Internal {

static QSettings *theSettings = 0;

class HistoryCompleterPrivate : public QAbstractListModel
{
public:
    HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());

    void clearHistory();
    void saveEntry(const QString &str);

    QStringList list;
    QString historyKey;
    int maxLines;
    FancyLineEdit *lineEdit;
};

class HistoryLineDelegate : public QItemDelegate
{
public:
    HistoryLineDelegate(QObject *parent)
        : QItemDelegate(parent)
        , pixmap(QLatin1String(":/core/images/editclear.png"))
    {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QItemDelegate::paint(painter,option,index);
        QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);
        painter->drawPixmap(r, pixmap);
    }

    QPixmap pixmap;
};

class HistoryLineView : public QListView
{
public:
    HistoryLineView(HistoryCompleterPrivate *model_)
        : model(model_)
    {
        HistoryLineDelegate *delegate = new HistoryLineDelegate(this);
        pixmapWidth = delegate->pixmap.width();
        setItemDelegate(delegate);
    }

private:
    void mousePressEvent(QMouseEvent *event)
    {
        int rr= event->x();
        if (layoutDirection() == Qt::LeftToRight)
            rr = viewport()->width() - event->x();
        if (rr < pixmapWidth) {
            model->removeRow(indexAt(event->pos()).row());
            return;
        }
        QListView::mousePressEvent(event);
    }

    HistoryCompleterPrivate *model;
    int pixmapWidth;
};

} // namespace Internal

using namespace Internal;

int HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : list.count();
}

QVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const
{
    if (index.row() >= list.count() || index.column() != 0)
        return QVariant();
    if (role == Qt::DisplayRole || role == Qt::EditRole)
        return list.at(index.row());
    return QVariant();
}

bool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)
{
    QTC_ASSERT(theSettings, return false);
    if (row + count > list.count())
        return false;
    beginRemoveRows(parent, row, row + count -1);
    for (int i = 0; i < count; ++i)
        list.removeAt(row);
    theSettings->setValue(historyKey, list);
    endRemoveRows();
    return true;
}

void HistoryCompleterPrivate::clearHistory()
{
    beginResetModel();
    list.clear();
    endResetModel();
}

void HistoryCompleterPrivate::saveEntry(const QString &str)
{
    QTC_ASSERT(theSettings, return);
    const QString &entry = str.trimmed();
    int removeIndex = list.indexOf(entry);
    if (removeIndex != -1)
        removeRow(removeIndex);
    beginInsertRows (QModelIndex(), list.count(), list.count());
    list.prepend(entry);
    list = list.mid(0, maxLines);
    endInsertRows();
    theSettings->setValue(historyKey, list);
}

HistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)
    : QCompleter(parent),
      d(new HistoryCompleterPrivate)
{
    QTC_ASSERT(lineEdit, return);
    QTC_ASSERT(!historyKey.isEmpty(), return);
    QTC_ASSERT(theSettings, return);

    d->historyKey = QLatin1String("CompleterHistory/") + historyKey;
    d->list = theSettings->value(d->historyKey).toStringList();
    d->lineEdit = lineEdit;
    if (d->list.count())
        lineEdit->setText(d->list.at(0));

    setModel(d);
    setPopup(new HistoryLineView(d));

    connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));
}

bool HistoryCompleter::removeHistoryItem(int index)
{
    return d->removeRow(index);
}

HistoryCompleter::~HistoryCompleter()
{
    delete d;
}

int HistoryCompleter::historySize() const
{
    return d->rowCount();
}

int HistoryCompleter::maximalHistorySize() const
{
    return d->maxLines;
}

void HistoryCompleter::setMaximalHistorySize(int numberOfEntries)
{
    d->maxLines = numberOfEntries;
}

void HistoryCompleter::clearHistory()
{
    d->clearHistory();
}

void HistoryCompleter::saveHistory()
{
    d->saveEntry(d->lineEdit->text());
}

void HistoryCompleter::setSettings(QSettings *settings)
{
    Internal::theSettings = settings;
}

} // namespace Utils
<commit_msg>HistoryCompleter: Do not overwrite text in the FancyLineEdit<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "historycompleter.h"
#include "fancylineedit.h"

#include "qtcassert.h"

#include <QSettings>

#include <QItemDelegate>
#include <QKeyEvent>
#include <QListView>
#include <QPainter>

namespace Utils {
namespace Internal {

static QSettings *theSettings = 0;

class HistoryCompleterPrivate : public QAbstractListModel
{
public:
    HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());

    void clearHistory();
    void saveEntry(const QString &str);

    QStringList list;
    QString historyKey;
    int maxLines;
    FancyLineEdit *lineEdit;
};

class HistoryLineDelegate : public QItemDelegate
{
public:
    HistoryLineDelegate(QObject *parent)
        : QItemDelegate(parent)
        , pixmap(QLatin1String(":/core/images/editclear.png"))
    {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QItemDelegate::paint(painter,option,index);
        QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);
        painter->drawPixmap(r, pixmap);
    }

    QPixmap pixmap;
};

class HistoryLineView : public QListView
{
public:
    HistoryLineView(HistoryCompleterPrivate *model_)
        : model(model_)
    {
        HistoryLineDelegate *delegate = new HistoryLineDelegate(this);
        pixmapWidth = delegate->pixmap.width();
        setItemDelegate(delegate);
    }

private:
    void mousePressEvent(QMouseEvent *event)
    {
        int rr= event->x();
        if (layoutDirection() == Qt::LeftToRight)
            rr = viewport()->width() - event->x();
        if (rr < pixmapWidth) {
            model->removeRow(indexAt(event->pos()).row());
            return;
        }
        QListView::mousePressEvent(event);
    }

    HistoryCompleterPrivate *model;
    int pixmapWidth;
};

} // namespace Internal

using namespace Internal;

int HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : list.count();
}

QVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const
{
    if (index.row() >= list.count() || index.column() != 0)
        return QVariant();
    if (role == Qt::DisplayRole || role == Qt::EditRole)
        return list.at(index.row());
    return QVariant();
}

bool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)
{
    QTC_ASSERT(theSettings, return false);
    if (row + count > list.count())
        return false;
    beginRemoveRows(parent, row, row + count -1);
    for (int i = 0; i < count; ++i)
        list.removeAt(row);
    theSettings->setValue(historyKey, list);
    endRemoveRows();
    return true;
}

void HistoryCompleterPrivate::clearHistory()
{
    beginResetModel();
    list.clear();
    endResetModel();
}

void HistoryCompleterPrivate::saveEntry(const QString &str)
{
    QTC_ASSERT(theSettings, return);
    const QString &entry = str.trimmed();
    int removeIndex = list.indexOf(entry);
    if (removeIndex != -1)
        removeRow(removeIndex);
    beginInsertRows (QModelIndex(), list.count(), list.count());
    list.prepend(entry);
    list = list.mid(0, maxLines);
    endInsertRows();
    theSettings->setValue(historyKey, list);
}

HistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)
    : QCompleter(parent),
      d(new HistoryCompleterPrivate)
{
    QTC_ASSERT(lineEdit, return);
    QTC_ASSERT(!historyKey.isEmpty(), return);
    QTC_ASSERT(theSettings, return);

    d->historyKey = QLatin1String("CompleterHistory/") + historyKey;
    d->list = theSettings->value(d->historyKey).toStringList();
    d->lineEdit = lineEdit;
    if (d->list.count() && lineEdit->text().isEmpty())
        lineEdit->setText(d->list.at(0));

    setModel(d);
    setPopup(new HistoryLineView(d));

    connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));
}

bool HistoryCompleter::removeHistoryItem(int index)
{
    return d->removeRow(index);
}

HistoryCompleter::~HistoryCompleter()
{
    delete d;
}

int HistoryCompleter::historySize() const
{
    return d->rowCount();
}

int HistoryCompleter::maximalHistorySize() const
{
    return d->maxLines;
}

void HistoryCompleter::setMaximalHistorySize(int numberOfEntries)
{
    d->maxLines = numberOfEntries;
}

void HistoryCompleter::clearHistory()
{
    d->clearHistory();
}

void HistoryCompleter::saveHistory()
{
    d->saveEntry(d->lineEdit->text());
}

void HistoryCompleter::setSettings(QSettings *settings)
{
    Internal::theSettings = settings;
}

} // namespace Utils
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"
#include "line_utilities.h"
#include "../control.h"
#include "line_simplification.h"

using namespace std;
using namespace cv;

void LineFollowing::detect_lines(Mat &original_frame) {

  Mat hsv;
  Mat mask;
  width = original_frame.cols;
  height = original_frame.rows;

  cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
  Canny(mask, mask, 50, 200, 3);

  vector<Vec2f> lines;
  HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);

  // printf("Adding in %d lines\n", (int) lines.size());

  vector<Vec2f> tmp = condense_lines(lines, true);
  sort(tmp.begin(), tmp.end(),
       [](const Vec2f &a, const Vec2f &b) {
         return a[0] < b[0];
       });
  if (tmp.size() > 0) {
    found_lines = tmp;
  }

  draw_lines(original_frame, found_lines, Scalar(255, 255, 255));

}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  minH = 50;
  minS = 20;
  minV = 150;
  maxH = 125;
  maxS = 100;
  maxV = 255;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {
  int center_x = 0 + (control_ptr->image.cols / 2);
  int center_y = 0 + (control_ptr->image.rows / 2);
  Point center_point = cvPoint(center_x, center_y);
  int tolerance = 10;
  line_options categorization;
  Point intersection_point;
  double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image);

  if (found_lines.size() < 1) return;

  if (found_lines.size() == 1) {
    categorization.vertical = found_lines[0];
    calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
                                                             control_ptr->image.cols, control_ptr->image.rows);
    calculated_distance_from_horizontal = 0;
    intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);
  } else if (found_lines.size() == 2) {
    //TODO maybe this is a very bad assumption to make, that [0] is the vertical line
    categorization.vertical = found_lines[0];
    categorization.horizontal = found_lines[1];
    calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
                                                             control_ptr->image.cols, control_ptr->image.rows);
    calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],
                                                               categorization.horizontal[0],
                                                               control_ptr->image.cols, control_ptr->image.rows);

    intersection_point = find_intersection(categorization.vertical, categorization.horizontal);

  }
  if (found_lines.size() < 3) {
    //For 1 or 2 lines

    line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); // draw the line to the center

    //draw a cross at the intersection
    line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),
         cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);
    line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),
         cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);

    // I need to snap myself to the line
    if (categorization.vertical[0] >= deg2rad(5)) {
      control_ptr->velocities.vr = -.2;
      // printf("Turning Right\n");
    } else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {
      control_ptr->velocities.vr = .2;
      // printf("Turning Left\n");
    } else {
      // printf("Checking Distance\n");
      // printf("Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\n", offset,

      // (double) control_ptr->image.cols, (control_ptr->image.cols / 2.0));
      if (-100 >= calculated_distance_from_vertical && calculated_distance_from_vertical >= 100) {
        if (calculated_distance_from_vertical < 0) {
          //we are to the right of the line
          //we need to move left
          control_ptr->velocities.vy = 1;
          // printf("Move left\n");
        } else {
          //we need to move right
          control_ptr->velocities.vy = -1;
          // printf("Move right\n");
        }
      }
      if (-100 >= calculated_distance_from_horizontal && calculated_distance_from_horizontal >= 100) {
        //todo move up or down the line

        if (calculated_distance_from_horizontal > 0) {
//          we are above the line
//          so we need to move backwards
//          I think
//          todo check this
          control_ptr->velocities.vx = -1;

        } else {
          control_ptr->velocities.vx = 1;
        }
      }
    }
  } else {
    for (int i = 0; i < found_lines.size(); ++i) {
      float angle = abs(found_lines[i][0]);

      if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {
        categorization.vertical = found_lines[i];
      }
      if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {
        categorization.horizontal = found_lines[i];
      }
      if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {
        categorization.sloped = found_lines[i];
        if (found_lines[i][0] < 0) {
          categorization.d = direction::right;
        } else if (found_lines[i][0] > 0) {
          categorization.d = direction::left;
        }
      }

    }
  }

  if (found_lines.size() > 3) {
    //print out the points of all 4+ lines
    for (int j = 0; j < (int) found_lines.size(); j++) {
      printf("(%5.1f, %5.0f) ", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);
    }
    printf("\n");
  }

  //Draw all the lines
  if (categorization.horizontal != Vec2f()) {
    draw_line(control_ptr->image, categorization.horizontal, color_green);
  }
  if (categorization.vertical != Vec2f()) {
    draw_line(control_ptr->image, categorization.vertical, color_blue);
  }
  if (categorization.sloped != Vec2f()) {
    draw_line(control_ptr->image, categorization.sloped, color_red);
  }

  return;
}

cv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {
  Point rv;
  bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);
  if (!do_intersect) {
    printf("No intersection!\n");
  }

  return rv;
}

<commit_msg>tweaks<commit_after>/*

*/

#include "lineFollowing.h"
#include "line_utilities.h"
#include "../control.h"
#include "line_simplification.h"

using namespace std;
using namespace cv;

void LineFollowing::detect_lines(Mat &original_frame) {

  Mat hsv;
  Mat mask;
  width = original_frame.cols;
  height = original_frame.rows;

  cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
  Canny(mask, mask, 50, 200, 3);

  vector<Vec2f> lines;
  HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);

  // printf("Adding in %d lines\n", (int) lines.size());

  vector<Vec2f> tmp = condense_lines(lines, true);

  sort(tmp.begin(), tmp.end(),
       [](const Vec2f &a, const Vec2f &b) {
         return a[0] < b[0];
       });
  if (tmp.size() > 0) {
    found_lines = tmp;
  }

  draw_lines(original_frame, found_lines, Scalar(255, 255, 255));

}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  minH = 50;
  minS = 20;
  minV = 150;
  maxH = 125;
  maxS = 100;
  maxV = 255;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {
  int center_x = 0 + (control_ptr->image.cols / 2);
  int center_y = 0 + (control_ptr->image.rows / 2);
  Point center_point = cvPoint(center_x, center_y);
  int tolerance = 10;
  line_options categorization;
  Point intersection_point;
  double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image);

  if (found_lines.size() < 1) return;

  if (found_lines.size() == 1) {
    categorization.vertical = found_lines[0];
    calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
                                                             control_ptr->image.cols, control_ptr->image.rows);
    calculated_distance_from_horizontal = 0;
    intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);

    if (true) {
      printf("Width of %7.1f with (%5.1f, %5.1f)\n", calculated_distance_from_vertical, categorization.vertical[0],
             categorization.vertical[1]);
    }
  } else if (found_lines.size() == 2) {
    //TODO maybe this is a very bad assumption to make, that [0] is the vertical line
    categorization.vertical = found_lines[1];
    categorization.horizontal = found_lines[0];
    calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
                                                             control_ptr->image.cols, control_ptr->image.rows);
    calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],
                                                               categorization.horizontal[0],
                                                               control_ptr->image.cols, control_ptr->image.rows);

    intersection_point = find_intersection(categorization.vertical, categorization.horizontal);

  }
  if (found_lines.size() < 3) {
    //For 1 or 2 lines

    line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); // draw the line to the center

    //draw a cross at the intersection
    line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),
         cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);
    line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),
         cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);

    // I need to snap myself to the line
    if (categorization.vertical[0] >= deg2rad(5)) {
      control_ptr->velocities.vr = -.2;
      // printf("Turning Right\n");
    } else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {
      control_ptr->velocities.vr = .2;
      // printf("Turning Left\n");
    } else {
      // printf("Checking Distance\n");
      // printf("Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\n", offset,

      // (double) control_ptr->image.cols, (control_ptr->image.cols / 2.0));
      int vertical_tolerance = 50;
      int horizontal_tolerance = 100;
      if (-1 * vertical_tolerance >= calculated_distance_from_vertical &&
          calculated_distance_from_vertical >= vertical_tolerance) {
        if (calculated_distance_from_vertical < 0) {
          //we are to the right of the line
          //we need to move left
          control_ptr->velocities.vy = 1;
          // printf("Move left\n");
        } else {
          //we need to move right
          control_ptr->velocities.vy = -1;
          // printf("Move right\n");
        }
      }
      if (-1 * horizontal_tolerance >= calculated_distance_from_horizontal &&
          calculated_distance_from_horizontal >= horizontal_tolerance) {
        //todo move up or down the line

        if (calculated_distance_from_horizontal > 0) {
//          we are above the line
//          so we need to move backwards
//          I think
//          todo check this
          control_ptr->velocities.vx = -1;

        } else {
          control_ptr->velocities.vx = 1;
        }
      }
    }
  } else {
    for (int i = 0; i < found_lines.size(); ++i) {
      float angle = abs(found_lines[i][0]);

      if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {
        categorization.vertical = found_lines[i];
      }
      if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {
        categorization.horizontal = found_lines[i];
      }
      if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {
        categorization.sloped = found_lines[i];
        if (found_lines[i][0] < 0) {
          categorization.d = direction::right;
        } else if (found_lines[i][0] > 0) {
          categorization.d = direction::left;
        }
      }

    }
  }

  if (found_lines.size() > 3) {
    //print out the points of all 4+ lines
    for (int j = 0; j < (int) found_lines.size(); j++) {
      printf("(%5.1f, %5.0f) ", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);
    }
    printf("\n");
  }

  //Draw all the lines
  if (categorization.horizontal != Vec2f()) {
    draw_line(control_ptr->image, categorization.horizontal, color_green);
  }
  if (categorization.vertical != Vec2f()) {
    draw_line(control_ptr->image, categorization.vertical, color_blue);
  }
  if (categorization.sloped != Vec2f()) {
    draw_line(control_ptr->image, categorization.sloped, color_red);
  }

  return;
}

cv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {
  Point rv;
  bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);
  if (!do_intersect) {
    printf("No intersection!\n");
  }

  return rv;
}

<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

//    medianBlur(mask, mask, 5);

    erode(mask, mask, Mat(), Point(-1,-1), 20);
    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>messing with erode<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

//    medianBlur(mask, mask, 5);

    erode(mask, mask, Mat(), Point(-1,-1), 12);
    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

void detect_lines(Mat &original_frame, double scale_factor);

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
//  printf("Hello, this is Caleb\n");
//  no this is patric

  VideoCapture cap("../../tests/videos/top_down_1.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

//  Mat edges;
  for (; ;) {
    Mat frame;
    cap >> frame; // get a new frame from camera

    detect_lines(frame, .2);

    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor

  return;
}
#pragma clang diagnostic pop

void detect_lines(Mat &original_frame, double scale_factor) {
  Mat hsv;
  Mat mask;
  Mat image;

  resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame

  cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV

  double minH = 50;
  double minS = 20;
  double minV = 150;
  double maxH = 125;
  double maxS = 100;
  double maxV = 255;

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color

  vector<Vec4i> lines;
  HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image

  printf("Adding in %d lines\n", (int) lines.size());
  for (size_t i = 0; i < lines.size(); i++) {
    Vec4i l = lines[i];
    line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
    // break;
  }
//    if (lines.size() < 1) continue;

//  imshow("line_window", image);
  original_frame = image;
}

void LineFollowing::initialize() {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  return;
}

void LineFollowing::close() {
  return;
}

ControlMovements LineFollowing::fly(cv::Mat *image) {
  ControlMovements velocities;

  velocities.vx = 0;
  velocities.vy = 0;
  velocities.vz = 0;
  velocities.vr = 0;

  detect_lines(*image, .3);

  return velocities;
}
<commit_msg>shows lines on the main screen<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

void detect_lines(Mat &original_frame, double scale_factor);

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
//  printf("Hello, this is Caleb\n");
//  no this is patric

  VideoCapture cap("../../tests/videos/top_down_1.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

//  Mat edges;
  for (; ;) {
    Mat frame;
    cap >> frame; // get a new frame from camera

    detect_lines(frame, .2);

    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor

  return;
}
#pragma clang diagnostic pop

void detect_lines(Mat &original_frame, double scale_factor) {
  Mat hsv;
  Mat mask;
  Mat image;

  resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame

  cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV

  double minH = 50;
  double minS = 20;
  double minV = 150;
  double maxH = 125;
  double maxS = 100;
  double maxV = 255;

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color

  vector<Vec4i> lines;
  HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image

  printf("Adding in %d lines\n", (int) lines.size());
  for (size_t i = 0; i < lines.size(); i++) {
    Vec4i l = lines[i];
    line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
    // break;
  }
//    if (lines.size() < 1) continue;

//  imshow("line_window", image);
  resize(image, original_frame, Size(), 1/scale_factor, 1/scale_factor);
}

void LineFollowing::initialize() {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  return;
}

void LineFollowing::close() {
  return;
}

ControlMovements LineFollowing::fly(cv::Mat *image) {
  ControlMovements velocities;

  velocities.vx = 0;
  velocities.vy = 0;
  velocities.vz = 0;
  velocities.vr = 0;

  detect_lines(*image, .3);

  return velocities;
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Definitions for the Connections class in C++
 */

#ifndef NTA_CONNECTIONS_HPP
#define NTA_CONNECTIONS_HPP

#include <vector>
#include <utility>
#include <nta/types/Types.hpp>
#include <nta/math/Math.hpp>

namespace nta
{

  namespace algorithms
  {

    namespace connections
    {
      typedef UInt32 CellIdx;
      typedef unsigned char SegmentIdx;
      typedef unsigned char SynapseIdx;
      typedef Real32 Permanence;

      /**
       * Cell class used in Connections.
       *
       * @b Description
       * The Cell class is a data structure that points to a particular cell.
       *
       * @param idx Index of cell.
       *
       */
      struct Cell
      {
        CellIdx idx;

        Cell(CellIdx idx) : idx(idx) {}
        Cell() {}

        bool operator==(const Cell &other) const;
        bool operator<=(const Cell &other) const;
        bool operator<(const Cell &other) const;
        bool operator>=(const Cell &other) const;
        bool operator>(const Cell &other) const;
      };

      /**
       * Segment class used in Connections.
       *
       * @b Description
       * The Segment class is a data structure that points to a particular
       * segment on a particular cell.
       *
       * @param idx     Index of segment.
       * @param cellIdx Index of cell.
       *
       */
      struct Segment
      {
        SegmentIdx idx;
        Cell cell;

        Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}
        Segment() {}

        bool operator==(const Segment &other) const;
        bool operator<=(const Segment &other) const;
        bool operator<(const Segment &other) const;
        bool operator>=(const Segment &other) const;
        bool operator>(const Segment &other) const;
      };

      /**
       * Synapse class used in Connections.
       *
       * @b Description
       * The Synapse class is a data structure that points to a particular
       * synapse on a particular segment on a particular cell.
       *
       * @param idx        Index of synapse in segment.
       * @param segmentIdx Index of segment in cell.
       * @param cellIdx    Index of cell.
       *
       */
      struct Synapse
      {
        SynapseIdx idx;
        Segment segment;

        Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}
        Synapse() {}

        bool operator==(const Synapse &other) const;
      };

      /**
       * SynapseData class used in Connections.
       *
       * @b Description
       * The SynapseData class is a data structure that contains the data for a
       * synapse on a segment.
       *
       * @param presynapticCellIdx Cell that this synapse gets input from.
       * @param permanence         Permanence of synapse.
       *
       */
      struct SynapseData
      {
        Cell presynapticCell;
        Permanence permanence;
      };

      /**
       * SegmentData class used in Connections.
       *
       * @b Description
       * The SegmentData class is a data structure that contains the data for a
       * segment on a cell.
       *
       * @param synapses Data for synapses that this segment contains.
       *
       */
      struct SegmentData
      {
        std::vector<SynapseData> synapses;
      };

      /**
       * CellData class used in Connections.
       *
       * @b Description
       * The CellData class is a data structure that contains the data for a
       * cell.
       *
       * @param segments Data for segments that this cell contains.
       *
       */
      struct CellData
      {
        std::vector<SegmentData> segments;
      };

      /**
       * Activity class used in Connections.
       *
       * @b Description
       * The Activity class is a data structure that represents the
       * activity of a collection of cells, as computed by propagating
       * input through connections.
       *
       */
      struct Activity
      {
        std::map< Cell, std::vector<Segment> > activeSegmentsForCell;
        std::map<Segment, UInt> numActiveSynapsesForSegment;
      };

      /**
       * Connections implementation in C++.
       *
       * @b Description
       * The Connections class is a data structure that represents the
       * connections of a collection of cells. It is used in the HTM
       * learning algorithms to store and access data related to the
       * connectivity of cells.
       *
       * It's main utility is to provide a common, optimized data structure
       * that all HTM learning algorithms can use. It is flexible enough to
       * support any learning algorithm that operates on a collection of cells.
       *
       * Each type of connection (proximal, distal, apical) should be
       * represented by a different instantiation of this class. This class
       * will help compute the activity along those connections due to active
       * input cells. The responsibility for what effect that activity has on
       * the cells and connections lies in the user of this class.
       *
       * This class is optimized to store connections between cells, and
       * compute the activity of cells due to input over the connections.
       *
       */
      class Connections
      {
      public:
        Connections(CellIdx numCells);

        virtual ~Connections() {}

        /**
         Creates a segment on the specified cell.

         @param cell Cell to create segment on.

         @retval Created segment.
        */
        Segment createSegment(const Cell& cell);

        /**
         Creates a synapse on the specified segment.

         @param segment         Segment to create synapse on.
         @param presynapticCell Cell to synapse on.
         @param permanence      Initial permanence of new synapse.

         @reval Created synapse.
        */
        Synapse createSynapse(const Segment& segment,
                              const Cell& presynapticCell,
                              Permanence permanence);

        /**
         Updates a synapse's permanence.

         @param synapse    Synapse to update.
         @param permanence New permanence.
        */
        void updateSynapsePermanence(const Synapse& synapse,
                                     Permanence permanence);

        /**
         Gets the segments for a cell.

         @param cell Cell to get segments for.

         @retval Segments on cell.
        */
        std::vector<Segment> segmentsForCell(const Cell& cell);

        /**
         Gets the synapses for a segment.

         @param segment Segment to get synapses for.

         @retval Synapses on segment.
        */
        std::vector<Synapse> synapsesForSegment(const Segment& segment);

        /**
         Gets the data for a synapse.

         @param synapse Synapse to get data for.

         @retval Synapse data.
        */
        SynapseData dataForSynapse(const Synapse& synapse) const;

        /**
         Gets the segment with the most active synapses due to given input,
         from among all the segments on all the given cells.

         @param cells            Cells to look among.
         @param input            Active cells in the input.
         @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
         @param segment          Segment to return.

         @retval Segment found?
        */
        bool mostActiveSegmentForCells(const std::vector<Cell>& cells,
                                       std::vector<Cell> input,
                                       UInt synapseThreshold,
                                       Segment& retSegment) const;

        /**
         Forward-propagates input to synapses, dendrites, and cells, to
         compute their activity.

         @param input               Active cells in the input.
         @param permanenceThreshold Only consider synapses with permanences greater than this threshold.
         @param synapseThreshold    Only consider segments with number of active synapses greater than this threshold.

         @retval Activity to return.
        */
        Activity computeActivity(const std::vector<Cell>& input,
                                 Permanence permanenceThreshold,
                                 UInt synapseThreshold) const;

        /**
         Gets the active segments from activity.

         @param activity Activity.

         @retval Active segments.
        */
        std::vector<Segment> activeSegments(const Activity& activity);

        /**
         Gets the active cells from activity.

         @param activity Activity.

         @retval Active cells.
        */
        std::vector<Cell> activeCells(const Activity& activity);

        // Debugging

        /**
         Gets the number of segments.

         @retval Number of segments.
        */
        UInt numSegments() const;

        /**
         Gets the number of synapses.

         @retval Number of synapses.
        */
        UInt numSynapses() const;

      private:
        std::vector<CellData> cells_;
        // Mapping (presynaptic cell => synapses) used in forward propagation
        std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;
      }; // end class Connections

    } // end namespace connections

  } // end namespace algorithms

} // end namespace nta

#endif // NTA_CONNECTIONS_HPP
<commit_msg>Formatting of documentation<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Definitions for the Connections class in C++
 */

#ifndef NTA_CONNECTIONS_HPP
#define NTA_CONNECTIONS_HPP

#include <vector>
#include <utility>
#include <nta/types/Types.hpp>
#include <nta/math/Math.hpp>

namespace nta
{

  namespace algorithms
  {

    namespace connections
    {
      typedef UInt32 CellIdx;
      typedef unsigned char SegmentIdx;
      typedef unsigned char SynapseIdx;
      typedef Real32 Permanence;

      /**
       * Cell class used in Connections.
       *
       * @b Description
       * The Cell class is a data structure that points to a particular cell.
       *
       * @param idx Index of cell.
       *
       */
      struct Cell
      {
        CellIdx idx;

        Cell(CellIdx idx) : idx(idx) {}
        Cell() {}

        bool operator==(const Cell &other) const;
        bool operator<=(const Cell &other) const;
        bool operator<(const Cell &other) const;
        bool operator>=(const Cell &other) const;
        bool operator>(const Cell &other) const;
      };

      /**
       * Segment class used in Connections.
       *
       * @b Description
       * The Segment class is a data structure that points to a particular
       * segment on a particular cell.
       *
       * @param idx     Index of segment.
       * @param cellIdx Index of cell.
       *
       */
      struct Segment
      {
        SegmentIdx idx;
        Cell cell;

        Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}
        Segment() {}

        bool operator==(const Segment &other) const;
        bool operator<=(const Segment &other) const;
        bool operator<(const Segment &other) const;
        bool operator>=(const Segment &other) const;
        bool operator>(const Segment &other) const;
      };

      /**
       * Synapse class used in Connections.
       *
       * @b Description
       * The Synapse class is a data structure that points to a particular
       * synapse on a particular segment on a particular cell.
       *
       * @param idx        Index of synapse in segment.
       * @param segmentIdx Index of segment in cell.
       * @param cellIdx    Index of cell.
       *
       */
      struct Synapse
      {
        SynapseIdx idx;
        Segment segment;

        Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}
        Synapse() {}

        bool operator==(const Synapse &other) const;
      };

      /**
       * SynapseData class used in Connections.
       *
       * @b Description
       * The SynapseData class is a data structure that contains the data for a
       * synapse on a segment.
       *
       * @param presynapticCellIdx Cell that this synapse gets input from.
       * @param permanence         Permanence of synapse.
       *
       */
      struct SynapseData
      {
        Cell presynapticCell;
        Permanence permanence;
      };

      /**
       * SegmentData class used in Connections.
       *
       * @b Description
       * The SegmentData class is a data structure that contains the data for a
       * segment on a cell.
       *
       * @param synapses Data for synapses that this segment contains.
       *
       */
      struct SegmentData
      {
        std::vector<SynapseData> synapses;
      };

      /**
       * CellData class used in Connections.
       *
       * @b Description
       * The CellData class is a data structure that contains the data for a
       * cell.
       *
       * @param segments Data for segments that this cell contains.
       *
       */
      struct CellData
      {
        std::vector<SegmentData> segments;
      };

      /**
       * Activity class used in Connections.
       *
       * @b Description
       * The Activity class is a data structure that represents the
       * activity of a collection of cells, as computed by propagating
       * input through connections.
       *
       */
      struct Activity
      {
        std::map< Cell, std::vector<Segment> > activeSegmentsForCell;
        std::map<Segment, UInt> numActiveSynapsesForSegment;
      };

      /**
       * Connections implementation in C++.
       *
       * @b Description
       * The Connections class is a data structure that represents the
       * connections of a collection of cells. It is used in the HTM
       * learning algorithms to store and access data related to the
       * connectivity of cells.
       *
       * It's main utility is to provide a common, optimized data structure
       * that all HTM learning algorithms can use. It is flexible enough to
       * support any learning algorithm that operates on a collection of cells.
       *
       * Each type of connection (proximal, distal, apical) should be
       * represented by a different instantiation of this class. This class
       * will help compute the activity along those connections due to active
       * input cells. The responsibility for what effect that activity has on
       * the cells and connections lies in the user of this class.
       *
       * This class is optimized to store connections between cells, and
       * compute the activity of cells due to input over the connections.
       *
       */
      class Connections
      {
      public:
        Connections(CellIdx numCells);

        virtual ~Connections() {}

        /**
         * Creates a segment on the specified cell.
         *
         * @param cell Cell to create segment on.
         *
         * @retval Created segment.
         */
        Segment createSegment(const Cell& cell);

        /**
         * Creates a synapse on the specified segment.
         *
         * @param segment         Segment to create synapse on.
         * @param presynapticCell Cell to synapse on.
         * @param permanence      Initial permanence of new synapse.
         *
         * @reval Created synapse.
         */
        Synapse createSynapse(const Segment& segment,
                              const Cell& presynapticCell,
                              Permanence permanence);

        /**
         * Updates a synapse's permanence.
         *
         * @param synapse    Synapse to update.
         * @param permanence New permanence.
         */
        void updateSynapsePermanence(const Synapse& synapse,
                                     Permanence permanence);

        /**
         * Gets the segments for a cell.
         *
         * @param cell Cell to get segments for.
         *
         * @retval Segments on cell.
         */
        std::vector<Segment> segmentsForCell(const Cell& cell);

        /**
         * Gets the synapses for a segment.
         *
         * @param segment Segment to get synapses for.
         *
         * @retval Synapses on segment.
         */
        std::vector<Synapse> synapsesForSegment(const Segment& segment);

        /**
         * Gets the data for a synapse.
         *
         * @param synapse Synapse to get data for.
         *
         * @retval Synapse data.
         */
        SynapseData dataForSynapse(const Synapse& synapse) const;

        /**
         * Gets the segment with the most active synapses due to given input,
         * from among all the segments on all the given cells.
         *
         * @param cells            Cells to look among.
         * @param input            Active cells in the input.
         * @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
         * @param segment          Segment to return.
         *
         * @retval Segment found?
         */
        bool mostActiveSegmentForCells(const std::vector<Cell>& cells,
                                       std::vector<Cell> input,
                                       UInt synapseThreshold,
                                       Segment& retSegment) const;

        /**
         * Forward-propagates input to synapses, dendrites, and cells, to
         * compute their activity.
         *
         * @param input               Active cells in the input.
         * @param permanenceThreshold Only consider synapses with permanences greater than this threshold.
         * @param synapseThreshold    Only consider segments with number of active synapses greater than this threshold.
         *
         * @retval Activity to return.
         */
        Activity computeActivity(const std::vector<Cell>& input,
                                 Permanence permanenceThreshold,
                                 UInt synapseThreshold) const;

        /**
         * Gets the active segments from activity.
         *
         * @param activity Activity.
         *
         * @retval Active segments.
         */
        std::vector<Segment> activeSegments(const Activity& activity);

        /**
         * Gets the active cells from activity.
         *
         * @param activity Activity.
         *
         * @retval Active cells.
         */
        std::vector<Cell> activeCells(const Activity& activity);

        // Debugging

        /**
         * Gets the number of segments.
         *
         * @retval Number of segments.
         */
        UInt numSegments() const;

        /**
         * Gets the number of synapses.
         *
         * @retval Number of synapses.
         */
        UInt numSynapses() const;

      private:
        std::vector<CellData> cells_;
        // Mapping (presynaptic cell => synapses) used in forward propagation
        std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;
      }; // end class Connections

    } // end namespace connections

  } // end namespace algorithms

} // end namespace nta

#endif // NTA_CONNECTIONS_HPP
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

// @brief: lane_post_processing_subnode source file

#include "modules/perception/obstacle/onboard/lane_post_processing_subnode.h"

#include <unordered_map>
#include <cfloat>

#include "Eigen/Dense"
#include "opencv2/opencv.hpp"
#include "yaml-cpp/yaml.h"

#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/common/time/time_util.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/camera/lane_post_process/cc_lane_post_processor/cc_lane_post_processor.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/types.h"
#include "modules/perception/proto/perception_obstacle.pb.h"

namespace apollo {
namespace perception {

using std::string;
using std::unordered_map;
using std::shared_ptr;
using apollo::common::Status;
using apollo::common::ErrorCode;
using apollo::common::time::Timer;

bool LanePostProcessingSubnode::InitInternal() {
  // get Subnode config in DAG streaming
  unordered_map<string, string> fields;
  SubnodeHelper::ParseReserveField(reserve_, &fields);
  if (fields.count("publish") && stoi(fields["publish"]) != 0) {
    publish_ = true;
  }

  // init shared data
  if (!InitSharedData()) {
    AERROR << "failed to init shared data.";
    return false;
  }

  RegistAllAlgorithms();

  // init plugins
  if (!InitAlgorithmPlugin()) {
    AERROR << "failed to init algorithm plugins.";
    return false;
  }

  AINFO << "init LanePostProcessing subnode successfully.";
  return true;
}

bool LanePostProcessingSubnode::InitSharedData() {
  if (shared_data_manager_ == nullptr) {
    AERROR << "shared data manager is a null pointer.";
    return false;
  }

  // init preprocess_data
  camera_object_data_ = dynamic_cast<CameraObjectData *>(
      shared_data_manager_->GetSharedData("CameraObjectData"));
  if (camera_object_data_ == nullptr) {
    AERROR << "failed to get shared data instance: CameraObjectData ";
    return false;
  }
  lane_shared_data_ = dynamic_cast<LaneSharedData *>(
      shared_data_manager_->GetSharedData("LaneSharedData"));
  if (lane_shared_data_ == nullptr) {
    AERROR << "failed to get shared data instance: LaneSharedData ";
    return false;
  }

  AINFO << "init shared data successfully, data: "
        << camera_object_data_->name() << " and " << lane_shared_data_->name();

  return true;
}

void LanePostProcessingSubnode::RegistAllAlgorithms() {
  RegisterFactoryCCLanePostProcessor();
}

bool LanePostProcessingSubnode::InitAlgorithmPlugin() {
  // init lane post-processer
  lane_post_processor_.reset(
      BaseCameraLanePostProcessorRegisterer::GetInstanceByName(
          FLAGS_onboard_lane_post_processor));
  if (!lane_post_processor_) {
    AERROR << "failed to get instance: " << FLAGS_onboard_lane_post_processor;
    return false;
  }
  if (!lane_post_processor_->Init()) {
    AERROR << "failed to init lane post-processor: "
           << lane_post_processor_->name();
    return false;
  }

  AINFO << "init alg pulgins successfully\n"
        << " lane post-processer:     " << FLAGS_onboard_lane_post_processor;
  return true;
}

bool LanePostProcessingSubnode::InitWorkRoot() {
  ConfigManager *config_manager = ConfigManager::instance();
  if (config_manager == NULL) {
    AERROR << "failed to get ConfigManager instance.";
    return false;
  }

  if (!config_manager->Init()) {
    AERROR << "failed to init ConfigManager";
    return false;
  }

  return true;
}

bool LanePostProcessingSubnode::GetSharedData(const Event &event,
                                              shared_ptr<SensorObjects> *objs) {
  double timestamp = event.timestamp;
  string device_id = event.reserve;
  device_id_ = device_id;
  string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
    AERROR << "failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }

  if (!camera_object_data_->Get(data_key, objs)) {
    AERROR << "failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

void LanePostProcessingSubnode::PublishDataAndEvent(
    const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {
  string key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
    AERROR << "failed to produce shared key. time: "
           << GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
    return;
  }

  if (!lane_shared_data_->Add(key, lane_objects)) {
    AWARN << "failed to add LaneSharedData. key: " << key
          << " num_detected_objects: " << lane_objects->size();
    return;
  }

  // pub events
  for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
    const EventMeta &event_meta = pub_meta_events_[idx];
    Event event;
    event.event_id = event_meta.event_id;
    event.timestamp = timestamp;
    event.reserve = device_id_;
    event_manager_->Publish(event);
  }
  AINFO << "succeed to publish data and event.";
}

Status LanePostProcessingSubnode::ProcEvents() {
  // fusion output subnode only subcribe the fusion subnode
  CHECK_EQ(sub_meta_events_.size(), 1u) << "only subcribe one event.";
  const EventMeta &event_meta = sub_meta_events_[0];
  Event event;
  event_manager_->Subscribe(event_meta.event_id, &event);
  ++seq_num_;
  shared_ptr<SensorObjects> objs;
  if (!GetSharedData(event, &objs)) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
  }

  Timer timer;
  timer.Start();

  cv::Mat lane_map = objs->camera_frame_supplement->lane_map;
  if (lane_map.empty()) {
    AERROR << "Get NULL lane_map from camera frame supplement";
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
  }

  LaneObjectsPtr lane_objects(new LaneObjects());
  CameraLanePostProcessOptions options;
  options.timestamp = event.timestamp;
  timestamp_ns_ = event.timestamp * 1e9;

  lane_post_processor_->Process(lane_map, options, &lane_objects);
  for (size_t i = 0; i < lane_objects->size(); ++i) {
    (*lane_objects)[i].timestamp = event.timestamp;
    (*lane_objects)[i].seq_num = seq_num_;
  }
  AINFO << "Before publish lane objects, objects num: "
        << lane_objects->size();

  uint64_t t = timer.End("lane post-processing");
  min_processing_time_ = std::min(min_processing_time_, t);
  max_processing_time_ = std::max(max_processing_time_, t);
  tot_processing_time_ += t;
  AINFO << "Lane Post Processing Runtime: "
        << "MIN (" << min_processing_time_ << " ms), "
        << "MAX (" << max_processing_time_ << " ms), "
        << "AVE (" << tot_processing_time_ / seq_num_ << " ms).";

  PublishDataAndEvent(event.timestamp, lane_objects);

  if (publish_) {
    PublishPerceptionPb(lane_objects);
  }

  AINFO << "Successfully finished lane post processing";
  return Status::OK();
}

void LanePostProcessingSubnode::PublishPerceptionPb(
    const LaneObjectsPtr &lane_objects) {
  ADEBUG << "Lane post-processor publish lane object pb data";

  PerceptionObstacles obstacles;

  // Header
  common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
      "perception_obstacle", &obstacles);
  common::Header *header = obstacles.mutable_header();
  header->set_lidar_timestamp(0);
  header->set_camera_timestamp(timestamp_ns_);
  header->set_radar_timestamp(0);

  // generate lane marker protobuf messages
  LaneMarkers* lane_markers = obstacles.mutable_lane_marker();
  LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);

  common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
  ADEBUG << "Lane Markers: " << obstacles.ShortDebugString();

  ADEBUG << "Succeed to publish lane object pb data.";
}

}  // namespace perception
}  // namespace apollo
<commit_msg>fix lint issue<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

// @brief: lane_post_processing_subnode source file

#include "modules/perception/obstacle/onboard/lane_post_processing_subnode.h"

#include <unordered_map>
#include <cfloat>
#include <algorithm>

#include "Eigen/Dense"
#include "opencv2/opencv.hpp"
#include "yaml-cpp/yaml.h"

#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/common/time/time_util.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/camera/lane_post_process/cc_lane_post_processor/cc_lane_post_processor.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/types.h"
#include "modules/perception/proto/perception_obstacle.pb.h"

namespace apollo {
namespace perception {

using std::string;
using std::unordered_map;
using std::shared_ptr;
using apollo::common::Status;
using apollo::common::ErrorCode;
using apollo::common::time::Timer;

bool LanePostProcessingSubnode::InitInternal() {
  // get Subnode config in DAG streaming
  unordered_map<string, string> fields;
  SubnodeHelper::ParseReserveField(reserve_, &fields);
  if (fields.count("publish") && stoi(fields["publish"]) != 0) {
    publish_ = true;
  }

  // init shared data
  if (!InitSharedData()) {
    AERROR << "failed to init shared data.";
    return false;
  }

  RegistAllAlgorithms();

  // init plugins
  if (!InitAlgorithmPlugin()) {
    AERROR << "failed to init algorithm plugins.";
    return false;
  }

  AINFO << "init LanePostProcessing subnode successfully.";
  return true;
}

bool LanePostProcessingSubnode::InitSharedData() {
  if (shared_data_manager_ == nullptr) {
    AERROR << "shared data manager is a null pointer.";
    return false;
  }

  // init preprocess_data
  camera_object_data_ = dynamic_cast<CameraObjectData *>(
      shared_data_manager_->GetSharedData("CameraObjectData"));
  if (camera_object_data_ == nullptr) {
    AERROR << "failed to get shared data instance: CameraObjectData ";
    return false;
  }
  lane_shared_data_ = dynamic_cast<LaneSharedData *>(
      shared_data_manager_->GetSharedData("LaneSharedData"));
  if (lane_shared_data_ == nullptr) {
    AERROR << "failed to get shared data instance: LaneSharedData ";
    return false;
  }

  AINFO << "init shared data successfully, data: "
        << camera_object_data_->name() << " and " << lane_shared_data_->name();

  return true;
}

void LanePostProcessingSubnode::RegistAllAlgorithms() {
  RegisterFactoryCCLanePostProcessor();
}

bool LanePostProcessingSubnode::InitAlgorithmPlugin() {
  // init lane post-processer
  lane_post_processor_.reset(
      BaseCameraLanePostProcessorRegisterer::GetInstanceByName(
          FLAGS_onboard_lane_post_processor));
  if (!lane_post_processor_) {
    AERROR << "failed to get instance: " << FLAGS_onboard_lane_post_processor;
    return false;
  }
  if (!lane_post_processor_->Init()) {
    AERROR << "failed to init lane post-processor: "
           << lane_post_processor_->name();
    return false;
  }

  AINFO << "init alg pulgins successfully\n"
        << " lane post-processer:     " << FLAGS_onboard_lane_post_processor;
  return true;
}

bool LanePostProcessingSubnode::InitWorkRoot() {
  ConfigManager *config_manager = ConfigManager::instance();
  if (config_manager == NULL) {
    AERROR << "failed to get ConfigManager instance.";
    return false;
  }

  if (!config_manager->Init()) {
    AERROR << "failed to init ConfigManager";
    return false;
  }

  return true;
}

bool LanePostProcessingSubnode::GetSharedData(const Event &event,
                                              shared_ptr<SensorObjects> *objs) {
  double timestamp = event.timestamp;
  string device_id = event.reserve;
  device_id_ = device_id;
  string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
    AERROR << "failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }

  if (!camera_object_data_->Get(data_key, objs)) {
    AERROR << "failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

void LanePostProcessingSubnode::PublishDataAndEvent(
    const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {
  string key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
    AERROR << "failed to produce shared key. time: "
           << GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
    return;
  }

  if (!lane_shared_data_->Add(key, lane_objects)) {
    AWARN << "failed to add LaneSharedData. key: " << key
          << " num_detected_objects: " << lane_objects->size();
    return;
  }

  // pub events
  for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
    const EventMeta &event_meta = pub_meta_events_[idx];
    Event event;
    event.event_id = event_meta.event_id;
    event.timestamp = timestamp;
    event.reserve = device_id_;
    event_manager_->Publish(event);
  }
  AINFO << "succeed to publish data and event.";
}

Status LanePostProcessingSubnode::ProcEvents() {
  // fusion output subnode only subcribe the fusion subnode
  CHECK_EQ(sub_meta_events_.size(), 1u) << "only subcribe one event.";
  const EventMeta &event_meta = sub_meta_events_[0];
  Event event;
  event_manager_->Subscribe(event_meta.event_id, &event);
  ++seq_num_;
  shared_ptr<SensorObjects> objs;
  if (!GetSharedData(event, &objs)) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
  }

  Timer timer;
  timer.Start();

  cv::Mat lane_map = objs->camera_frame_supplement->lane_map;
  if (lane_map.empty()) {
    AERROR << "Get NULL lane_map from camera frame supplement";
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
  }

  LaneObjectsPtr lane_objects(new LaneObjects());
  CameraLanePostProcessOptions options;
  options.timestamp = event.timestamp;
  timestamp_ns_ = event.timestamp * 1e9;

  lane_post_processor_->Process(lane_map, options, &lane_objects);
  for (size_t i = 0; i < lane_objects->size(); ++i) {
    (*lane_objects)[i].timestamp = event.timestamp;
    (*lane_objects)[i].seq_num = seq_num_;
  }
  AINFO << "Before publish lane objects, objects num: "
        << lane_objects->size();

  uint64_t t = timer.End("lane post-processing");
  min_processing_time_ = std::min(min_processing_time_, t);
  max_processing_time_ = std::max(max_processing_time_, t);
  tot_processing_time_ += t;
  AINFO << "Lane Post Processing Runtime: "
        << "MIN (" << min_processing_time_ << " ms), "
        << "MAX (" << max_processing_time_ << " ms), "
        << "AVE (" << tot_processing_time_ / seq_num_ << " ms).";

  PublishDataAndEvent(event.timestamp, lane_objects);

  if (publish_) {
    PublishPerceptionPb(lane_objects);
  }

  AINFO << "Successfully finished lane post processing";
  return Status::OK();
}

void LanePostProcessingSubnode::PublishPerceptionPb(
    const LaneObjectsPtr &lane_objects) {
  ADEBUG << "Lane post-processor publish lane object pb data";

  PerceptionObstacles obstacles;

  // Header
  common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
      "perception_obstacle", &obstacles);
  common::Header *header = obstacles.mutable_header();
  header->set_lidar_timestamp(0);
  header->set_camera_timestamp(timestamp_ns_);
  header->set_radar_timestamp(0);

  // generate lane marker protobuf messages
  LaneMarkers* lane_markers = obstacles.mutable_lane_marker();
  LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);

  common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
  ADEBUG << "Lane Markers: " << obstacles.ShortDebugString();

  ADEBUG << "Succeed to publish lane object pb data.";
}

}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LConnection.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:43:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_
#include "LConnection.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_
#include "LDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_
#include "LCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_MODULECONTEXT_HXX_
#include "ModuleContext.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_
#include "LPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_
#include "LStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX
#include "LDebug.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace vos;

typedef connectivity::file::OConnection  OConnection_B;

//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )
{
     ::rtl::OUString aExceptionType = aExceptionType_;
     if( aExceptionType.getLength() == 0 )
         aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) );

     ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) );
     aTypeLine += aExceptionType;

     ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) );
         aMessageLine += ::rtl::OUString( e.Message );

     ::rtl::OUString aMsg(aTypeLine);
     aMsg += aMessageLine;
         return aMsg;
}

 // Exception type unknown
::rtl::OUString implGetExceptionMsg( Exception& e )
{
         ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );
         return aMsg;
}

// --------------------------------------------------------------------------------
OEvoabConnection::OEvoabConnection(OEvoabDriver*    _pDriver) : OConnection(_pDriver)
    ,m_bHeaderLine(sal_True)
    ,m_cFieldDelimiter(',')
    ,m_cStringDelimiter('"')
    ,m_cDecimalDelimiter('.')
    ,m_cThousandDelimiter(' ')
{
    // Initialise m_aColumnAlias.
    m_aColumnAlias.setAlias(_pDriver->getFactory());
}
//-----------------------------------------------------------------------------
OEvoabConnection::~OEvoabConnection()
{
}

// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection")

//-----------------------------------------------------------------------------
void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)  throw(SQLException)
{
    osl_incrementInterlockedCount( &m_refCount );
    EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url );

    ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();
    ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();
    ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());
    ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());
    aArg2 += aWorkingDirPath;
    aArg2 += getDriver()->getEvoFolderListFileName();
    OArgumentList aArgs(2,&aArg1,&aArg2);

    EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 );
    OProcess aApp( aCLICommand,aWorkingDirPath);
    OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);
    DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards");

    Sequence<PropertyValue> aDriverParam;
    ::std::vector<PropertyValue> aParam;

    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE));
     ::dbtools::OCharsetMap aLookupIanaName;
     ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);
     aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0,
                                    makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));

    // build a new parameter sequence from the original parameters, appended by the new parameters from above
        PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];
        aDriverParam = ::comphelper::concatSequences(
        info,
        Sequence< PropertyValue >( pParams, aParam.size() )
    );

    // transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..."
    //
    sal_Int32 nLen = url.indexOf(':');
    nLen = url.indexOf(':',nLen+1);
    ::rtl::OUString aAddrbookURI(url.copy(nLen+1));
    // Get Scheme
    nLen = aAddrbookURI.indexOf(':');
    ::rtl::OUString aAddrbookScheme;
    if ( nLen == -1 )
    {
        // There isn't any subschema: - but could be just subschema
        if ( aAddrbookURI.getLength() > 0 )
        {
            aAddrbookScheme= aAddrbookURI;
        }
        else
        {
            OSL_TRACE( "No subschema given!!!\n");
            ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii("No subschema provided"),NULL);
        }
    }
    else
    {
        aAddrbookScheme = aAddrbookURI.copy(0, nLen);
    }

    EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI );
    EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme );

    //
    // Now we have a URI convert it to a Evolution CLI flat file URI
    //
    // The Mapping being used is:
    //
    // * for Evolution
    //      "sdbc:address:evolution:"        -> "sdbc:flat:file:///(file path generated)

    rtl::OUString aEvoFlatURI;
    if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )
    {
        aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" ));
    }

    aEvoFlatURI += getDriver()->getWorkingDirURL();
    EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI );
    //setURL(aEvoFlatURI);
    m_aEvoFlatURI = aEvoFlatURI;

    osl_decrementInterlockedCount( &m_refCount );
    OConnection::construct(aEvoFlatURI,aDriverParam);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
    if(!xMetaData.is())
    {
        xMetaData = new OEvoabDatabaseMetaData(this);
        m_xMetaData = xMetaData;
    }

    return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    Reference< XTablesSupplier > xTab = m_xCatalog;
    if(!xTab.is())
    {
        OEvoabCatalog *pCat = new OEvoabCatalog(this);
        xTab = pCat;
        m_xCatalog = xTab;
    }
    return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OEvoabConnection::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OEvoabStatement* pStmt = new OEvoabStatement(this);

    Reference< XStatement > xStmt = pStmt;
    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);
    Reference< XPreparedStatement > xStmt = pStmt;
    pStmt->construct(sql);

    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    return NULL;
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba203a (1.7.76); FILE MERGED 2006/03/20 13:11:15 fs 1.7.76.1: #i10000#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LConnection.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-29 12:15:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_
#include "LConnection.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_
#include "LDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_
#include "LCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_
#include "LPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_
#include "LStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX
#include "LDebug.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace vos;

typedef connectivity::file::OConnection  OConnection_B;

//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )
{
     ::rtl::OUString aExceptionType = aExceptionType_;
     if( aExceptionType.getLength() == 0 )
         aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) );

     ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) );
     aTypeLine += aExceptionType;

     ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) );
         aMessageLine += ::rtl::OUString( e.Message );

     ::rtl::OUString aMsg(aTypeLine);
     aMsg += aMessageLine;
         return aMsg;
}

 // Exception type unknown
::rtl::OUString implGetExceptionMsg( Exception& e )
{
         ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );
         return aMsg;
}

// --------------------------------------------------------------------------------
OEvoabConnection::OEvoabConnection(OEvoabDriver*    _pDriver) : OConnection(_pDriver)
    ,m_bHeaderLine(sal_True)
    ,m_cFieldDelimiter(',')
    ,m_cStringDelimiter('"')
    ,m_cDecimalDelimiter('.')
    ,m_cThousandDelimiter(' ')
{
    // Initialise m_aColumnAlias.
    m_aColumnAlias.setAlias(_pDriver->getFactory());
}
//-----------------------------------------------------------------------------
OEvoabConnection::~OEvoabConnection()
{
}

// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection")

//-----------------------------------------------------------------------------
void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)  throw(SQLException)
{
    osl_incrementInterlockedCount( &m_refCount );
    EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url );

    ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();
    ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();
    ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());
    ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());
    aArg2 += aWorkingDirPath;
    aArg2 += getDriver()->getEvoFolderListFileName();
    OArgumentList aArgs(2,&aArg1,&aArg2);

    EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 );
    EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 );
    OProcess aApp( aCLICommand,aWorkingDirPath);
    OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);
    DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards");

    Sequence<PropertyValue> aDriverParam;
    ::std::vector<PropertyValue> aParam;

    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE));
     ::dbtools::OCharsetMap aLookupIanaName;
     ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);
     aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0,
                                    makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));
    aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));

    // build a new parameter sequence from the original parameters, appended by the new parameters from above
        PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];
        aDriverParam = ::comphelper::concatSequences(
        info,
        Sequence< PropertyValue >( pParams, aParam.size() )
    );

    // transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..."
    //
    sal_Int32 nLen = url.indexOf(':');
    nLen = url.indexOf(':',nLen+1);
    ::rtl::OUString aAddrbookURI(url.copy(nLen+1));
    // Get Scheme
    nLen = aAddrbookURI.indexOf(':');
    ::rtl::OUString aAddrbookScheme;
    if ( nLen == -1 )
    {
        // There isn't any subschema: - but could be just subschema
        if ( aAddrbookURI.getLength() > 0 )
        {
            aAddrbookScheme= aAddrbookURI;
        }
        else
        {
            OSL_TRACE( "No subschema given!!!\n");
            ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii("No subschema provided"),NULL);
        }
    }
    else
    {
        aAddrbookScheme = aAddrbookURI.copy(0, nLen);
    }

    EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI );
    EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme );

    //
    // Now we have a URI convert it to a Evolution CLI flat file URI
    //
    // The Mapping being used is:
    //
    // * for Evolution
    //      "sdbc:address:evolution:"        -> "sdbc:flat:file:///(file path generated)

    rtl::OUString aEvoFlatURI;
    if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )
    {
        aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" ));
    }

    aEvoFlatURI += getDriver()->getWorkingDirURL();
    EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI );
    //setURL(aEvoFlatURI);
    m_aEvoFlatURI = aEvoFlatURI;

    osl_decrementInterlockedCount( &m_refCount );
    OConnection::construct(aEvoFlatURI,aDriverParam);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
    if(!xMetaData.is())
    {
        xMetaData = new OEvoabDatabaseMetaData(this);
        m_xMetaData = xMetaData;
    }

    return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    Reference< XTablesSupplier > xTab = m_xCatalog;
    if(!xTab.is())
    {
        OEvoabCatalog *pCat = new OEvoabCatalog(this);
        xTab = pCat;
        m_xCatalog = xTab;
    }
    return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OEvoabConnection::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OEvoabStatement* pStmt = new OEvoabStatement(this);

    Reference< XStatement > xStmt = pStmt;
    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);
    Reference< XPreparedStatement > xStmt = pStmt;
    pStmt->construct(sql);

    m_aStatements.push_back(WeakReferenceHelper(*pStmt));
    return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnection_B::rBHelper.bDisposed);

    return NULL;
}
// -------------------------------------------------------------------------
<|endoftext|>