<commit_before>/*
 * Copyright 2013  David Edmundson <davidedmundson@kde.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU 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/>.
 *
 */

#include "akonadidatasource.h"

#include <Akonadi/Item>
#include <Akonadi/ItemFetchJob>
#include <Akonadi/ItemFetchScope>
#include <Akonadi/Collection>
#include <Akonadi/CollectionFetchJob>
#include <Akonadi/CollectionFetchScope>

#include <KABC/Addressee>

#include <KPluginFactory>
#include <KPluginLoader>

#include <QDebug>

using namespace Akonadi;

class AkonadiAllContacts : public KPeople::AllContactsMonitor
{
    Q_OBJECT
public:
    AkonadiAllContacts();
    ~AkonadiAllContacts();
    virtual KABC::Addressee::Map contacts();
private Q_SLOTS:
    void onCollectionsFetched(KJob* job);
    void onItemsFetched(KJob* job);
    void onItemAdded(const Akonadi::Item &item);
    void onItemChanged(const Akonadi::Item &item);
    void onItemRemoved(const Akonadi::Item &item);
private:
    Akonadi::Monitor *m_monitor;
    KABC::Addressee::Map m_contacts;
    int m_activeFetchJobsCount;
};

AkonadiAllContacts::AkonadiAllContacts():
    m_monitor(new Akonadi::Monitor(this)),
    m_activeFetchJobsCount(0)
{
    connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(onItemAdded(Akonadi::Item)));
    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onItemChanged(Akonadi::Item)));
    connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), SLOT(onItemRemoved(Akonadi::Item)));

    m_monitor->setMimeTypeMonitored("text/directory");
    m_monitor->itemFetchScope().fetchFullPayload();
    m_monitor->itemFetchScope().setFetchModificationTime(false);
#ifdef HAVE_KDEPIM_ATLEAST_412
    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);
#endif

    CollectionFetchJob *fetchJob = new CollectionFetchJob(Collection::root(), CollectionFetchJob::Recursive, this);
    fetchJob->fetchScope().setContentMimeTypes( QStringList() << "text/directory" );
    connect(fetchJob, SIGNAL(finished(KJob*)), SLOT(onCollectionsFetched(KJob*)));
}

AkonadiAllContacts::~AkonadiAllContacts()
{
}

KABC::Addressee::Map AkonadiAllContacts::contacts()
{
    return m_contacts;
}

QString AkonadiDataSource::sourcePluginId() const
{
    return "akonadi";
}

void AkonadiAllContacts::onItemAdded(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    const KABC::Addressee contact = item.payload<KABC::Addressee>();
    m_contacts[id] = contact;
    Q_EMIT contactAdded(item.url().prettyUrl(), contact);
}

void AkonadiAllContacts::onItemChanged(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    const KABC::Addressee contact = item.payload<KABC::Addressee>();
    m_contacts[id] = contact;
    Q_EMIT contactChanged(item.url().prettyUrl(), contact);
}

void AkonadiAllContacts::onItemRemoved(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    m_contacts.remove(id);
    Q_EMIT contactRemoved(id);
}

//or we could add items as we go along...
void AkonadiAllContacts::onItemsFetched(KJob *job)
{
    ItemFetchJob *itemFetchJob = qobject_cast<ItemFetchJob*>(job);
    foreach (const Item &item, itemFetchJob->items()) {
        onItemAdded(item);
    }

    if (--m_activeFetchJobsCount == 0) {
        emitInitialFetchComplete();
    }
}

void AkonadiAllContacts::onCollectionsFetched(KJob* job)
{
    CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);
    QList<Collection> contactCollections;
    foreach (const Collection &collection, fetchJob->collections()) {
        // Skip virtual collections - we will get contacts linked into virtual
        // collections from their real parent collections
        if (collection.isVirtual()) {
            continue;
        }
        if (collection.contentMimeTypes().contains( KABC::Addressee::mimeType() ) ) {
            ItemFetchJob *itemFetchJob = new ItemFetchJob(collection);
            itemFetchJob->fetchScope().fetchFullPayload();
            connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onItemsFetched(KJob*)));
            ++m_activeFetchJobsCount;
        }
    }
}

class AkonadiContact: public KPeople::ContactMonitor
{
    Q_OBJECT
public:
    AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId);
    ~AkonadiContact();
private Q_SLOTS:
    void onContactFetched(KJob*);
    void onContactChanged(const Akonadi::Item &);
private:
    Akonadi::Monitor *m_monitor;
    Akonadi::Item m_item;
};

AkonadiContact::AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId):
    ContactMonitor(contactId),
    m_monitor(monitor)
{
    //TODO: optimiZation, base class could copy across from the model if the model exists
    //then we should check if contact is already set to something and avoid the initial fetch

    //load the contact initially
    m_item = Item::fromUrl(QUrl(contactId));
    ItemFetchJob* itemFetchJob = new ItemFetchJob(m_item);
    itemFetchJob->fetchScope().fetchFullPayload();
    connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onContactFetched(KJob*)));

    //then watch for that item changing
    m_monitor->setItemMonitored(m_item, true);
    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onContactChanged(Akonadi::Item)));
}

AkonadiContact::~AkonadiContact()
{
    m_monitor->setItemMonitored(m_item, false);
}

void AkonadiContact::onContactFetched(KJob *job)
{
    ItemFetchJob* fetchJob = qobject_cast<ItemFetchJob*>(job);
    if (fetchJob->items().count() && fetchJob->items().first().hasPayload<KABC::Addressee>()) {
        setContact(fetchJob->items().first().payload<KABC::Addressee>());
    }
}

void AkonadiContact::onContactChanged(const Item &item)
{
    if (item != m_item) {
        return;
    }
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    setContact(item.payload<KABC::Addressee>());
}

AkonadiDataSource::AkonadiDataSource(QObject *parent, const QVariantList &args):
    BasePersonsDataSource(parent),
    m_monitor(new Akonadi::Monitor(this))
{
    Q_UNUSED(args);
    m_monitor->itemFetchScope().fetchFullPayload();
    m_monitor->itemFetchScope().setFetchModificationTime(false);
#ifdef HAVE_KDEPIM_ATLEAST_412
    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);
#endif
}

AkonadiDataSource::~AkonadiDataSource()
{

}

KPeople::AllContactsMonitor* AkonadiDataSource::createAllContactsMonitor()
{
    return new AkonadiAllContacts();
}

KPeople::ContactMonitor* AkonadiDataSource::createContactMonitor(const QString& contactId)
{
    return new AkonadiContact(m_monitor, contactId);
}

K_PLUGIN_FACTORY( AkonadiDataSourceFactory, registerPlugin<AkonadiDataSource>(); )
K_EXPORT_PLUGIN( AkonadiDataSourceFactory("akonadi_kpeople_plugin") )

#include "akonadidatasource.moc"
<commit_msg>Emit finished if there are no akonadi collections<commit_after>/*
 * Copyright 2013  David Edmundson <davidedmundson@kde.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU 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/>.
 *
 */

#include "akonadidatasource.h"

#include <Akonadi/Item>
#include <Akonadi/ItemFetchJob>
#include <Akonadi/ItemFetchScope>
#include <Akonadi/Collection>
#include <Akonadi/CollectionFetchJob>
#include <Akonadi/CollectionFetchScope>

#include <KABC/Addressee>

#include <KPluginFactory>
#include <KPluginLoader>

#include <QDebug>

using namespace Akonadi;

class AkonadiAllContacts : public KPeople::AllContactsMonitor
{
    Q_OBJECT
public:
    AkonadiAllContacts();
    ~AkonadiAllContacts();
    virtual KABC::Addressee::Map contacts();
private Q_SLOTS:
    void onCollectionsFetched(KJob* job);
    void onItemsFetched(KJob* job);
    void onItemAdded(const Akonadi::Item &item);
    void onItemChanged(const Akonadi::Item &item);
    void onItemRemoved(const Akonadi::Item &item);
private:
    Akonadi::Monitor *m_monitor;
    KABC::Addressee::Map m_contacts;
    int m_activeFetchJobsCount;
};

AkonadiAllContacts::AkonadiAllContacts():
    m_monitor(new Akonadi::Monitor(this)),
    m_activeFetchJobsCount(0)
{
    connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(onItemAdded(Akonadi::Item)));
    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onItemChanged(Akonadi::Item)));
    connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), SLOT(onItemRemoved(Akonadi::Item)));

    m_monitor->setMimeTypeMonitored("text/directory");
    m_monitor->itemFetchScope().fetchFullPayload();
    m_monitor->itemFetchScope().setFetchModificationTime(false);
#ifdef HAVE_KDEPIM_ATLEAST_412
    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);
#endif

    CollectionFetchJob *fetchJob = new CollectionFetchJob(Collection::root(), CollectionFetchJob::Recursive, this);
    fetchJob->fetchScope().setContentMimeTypes( QStringList() << "text/directory" );
    connect(fetchJob, SIGNAL(finished(KJob*)), SLOT(onCollectionsFetched(KJob*)));
}

AkonadiAllContacts::~AkonadiAllContacts()
{
}

KABC::Addressee::Map AkonadiAllContacts::contacts()
{
    return m_contacts;
}

QString AkonadiDataSource::sourcePluginId() const
{
    return "akonadi";
}

void AkonadiAllContacts::onItemAdded(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    const KABC::Addressee contact = item.payload<KABC::Addressee>();
    m_contacts[id] = contact;
    Q_EMIT contactAdded(item.url().prettyUrl(), contact);
}

void AkonadiAllContacts::onItemChanged(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    const KABC::Addressee contact = item.payload<KABC::Addressee>();
    m_contacts[id] = contact;
    Q_EMIT contactChanged(item.url().prettyUrl(), contact);
}

void AkonadiAllContacts::onItemRemoved(const Item& item)
{
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    const QString id = item.url().prettyUrl();
    m_contacts.remove(id);
    Q_EMIT contactRemoved(id);
}

//or we could add items as we go along...
void AkonadiAllContacts::onItemsFetched(KJob *job)
{
    ItemFetchJob *itemFetchJob = qobject_cast<ItemFetchJob*>(job);
    foreach (const Item &item, itemFetchJob->items()) {
        onItemAdded(item);
    }

    if (--m_activeFetchJobsCount == 0) {
        emitInitialFetchComplete();
    }
}

void AkonadiAllContacts::onCollectionsFetched(KJob* job)
{
    CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);
    QList<Collection> contactCollections;
    foreach (const Collection &collection, fetchJob->collections()) {
        // Skip virtual collections - we will get contacts linked into virtual
        // collections from their real parent collections
        if (collection.isVirtual()) {
            continue;
        }
        if (collection.contentMimeTypes().contains( KABC::Addressee::mimeType() ) ) {
            ItemFetchJob *itemFetchJob = new ItemFetchJob(collection);
            itemFetchJob->fetchScope().fetchFullPayload();
            connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onItemsFetched(KJob*)));
            ++m_activeFetchJobsCount;
        }
    }
    if (m_activeFetchJobsCount == 0) {
        emitInitialFetchComplete();
    }
}

class AkonadiContact: public KPeople::ContactMonitor
{
    Q_OBJECT
public:
    AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId);
    ~AkonadiContact();
private Q_SLOTS:
    void onContactFetched(KJob*);
    void onContactChanged(const Akonadi::Item &);
private:
    Akonadi::Monitor *m_monitor;
    Akonadi::Item m_item;
};

AkonadiContact::AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId):
    ContactMonitor(contactId),
    m_monitor(monitor)
{
    //TODO: optimiZation, base class could copy across from the model if the model exists
    //then we should check if contact is already set to something and avoid the initial fetch

    //load the contact initially
    m_item = Item::fromUrl(QUrl(contactId));
    ItemFetchJob* itemFetchJob = new ItemFetchJob(m_item);
    itemFetchJob->fetchScope().fetchFullPayload();
    connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onContactFetched(KJob*)));

    //then watch for that item changing
    m_monitor->setItemMonitored(m_item, true);
    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onContactChanged(Akonadi::Item)));
}

AkonadiContact::~AkonadiContact()
{
    m_monitor->setItemMonitored(m_item, false);
}

void AkonadiContact::onContactFetched(KJob *job)
{
    ItemFetchJob* fetchJob = qobject_cast<ItemFetchJob*>(job);
    if (fetchJob->items().count() && fetchJob->items().first().hasPayload<KABC::Addressee>()) {
        setContact(fetchJob->items().first().payload<KABC::Addressee>());
    }
}

void AkonadiContact::onContactChanged(const Item &item)
{
    if (item != m_item) {
        return;
    }
    if(!item.hasPayload<KABC::Addressee>()) {
        return;
    }
    setContact(item.payload<KABC::Addressee>());
}

AkonadiDataSource::AkonadiDataSource(QObject *parent, const QVariantList &args):
    BasePersonsDataSource(parent),
    m_monitor(new Akonadi::Monitor(this))
{
    Q_UNUSED(args);
    m_monitor->itemFetchScope().fetchFullPayload();
    m_monitor->itemFetchScope().setFetchModificationTime(false);
#ifdef HAVE_KDEPIM_ATLEAST_412
    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);
#endif
}

AkonadiDataSource::~AkonadiDataSource()
{

}

KPeople::AllContactsMonitor* AkonadiDataSource::createAllContactsMonitor()
{
    return new AkonadiAllContacts();
}

KPeople::ContactMonitor* AkonadiDataSource::createContactMonitor(const QString& contactId)
{
    return new AkonadiContact(m_monitor, contactId);
}

K_PLUGIN_FACTORY( AkonadiDataSourceFactory, registerPlugin<AkonadiDataSource>(); )
K_EXPORT_PLUGIN( AkonadiDataSourceFactory("akonadi_kpeople_plugin") )

#include "akonadidatasource.moc"
<|endoftext|>


<commit_before>#include <plugins/owlexporter/OwlIndividual.h>

namespace beliefstate {
  std::list<std::string> OwlIndividual::m_lstIssuedProperties;
  std::list<std::string> OwlIndividual::m_lstIssuedTypes;

  OwlIndividual::OwlIndividual() {
    //
  }

  OwlIndividual::~OwlIndividual() {
    //
  }

  void OwlIndividual::setID(std::string strID) {
    m_strID = strID;
  }

  void OwlIndividual::setType(std::string strType) {
    m_strType = strType;

    this->issueType(strType);
  }

  void OwlIndividual::addDataProperty(std::string strTag, std::string strDataType, std::string strContent) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strDataType = strDataType;
    opProperty.strContent = strContent;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::addResourceProperty(std::string strTag, std::string strResource) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strResource = strResource;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::addContentProperty(std::string strTag, std::string strContent) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strContent = strContent;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::issueProperty(std::string strProperty) {
    std::string strPropertyFormatted = strProperty;

    size_t posColon = strPropertyFormatted.find(":");
    if(posColon != std::string::npos) {
      // Namespace found, convert it into short form
      strPropertyFormatted = "&" + strPropertyFormatted.substr(0, posColon) + ";" + strPropertyFormatted.substr(posColon + 1);
    }

    if(std::find(m_lstIssuedProperties.begin(), m_lstIssuedProperties.end(), strPropertyFormatted) == m_lstIssuedProperties.end()) {
      m_lstIssuedProperties.push_back(strPropertyFormatted);
    }
  }

  void OwlIndividual::issueType(std::string strType) {
    if(std::find(m_lstIssuedTypes.begin(), m_lstIssuedTypes.end(), strType) == m_lstIssuedTypes.end()) {
      m_lstIssuedTypes.push_back(strType);
    }
  }

  std::string OwlIndividual::indent(int nSpaces) {
    std::string strIndentation = "";

    for(int nI = 0; nI < nSpaces; nI++) {
      strIndentation += " ";
    }

    return strIndentation;
  }

  std::string OwlIndividual::print(int nIndentation, int nIndentationPerLevel) {
    std::string strOwl = "";

    if(strOwl != "") {
      strOwl += this->indent(nIndentation * nIndentationPerLevel) + "\n";
    }

    strOwl += this->indent(nIndentation * nIndentationPerLevel) +
      "<owl:namedIndividual rdf:about=\"" + m_strID + "\">\n";

    strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel) +
      "<rdf:type rdf:resource=\"" + m_strType + "\"/>\n";

    for(OwlProperty opProperty : m_lstProperties) {
      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel);
      strOwl += "<" + opProperty.strTag;

      if(opProperty.strDataType != "") {
	strOwl += " rdf:datatype=\"" + opProperty.strDataType + "\">" + opProperty.strContent;
	strOwl += "</" + opProperty.strTag + ">";
      } else if(opProperty.strResource != "") {
	strOwl += " rdf:resource=\"" + opProperty.strResource + "\"/>";
      } else {
	strOwl += ">" + opProperty.strContent;
	strOwl += "</" + opProperty.strTag + ">";
      }

      strOwl += "\n";
    }

    strOwl += this->indent(nIndentation * nIndentationPerLevel) +
      "</owl:namedIndividual>\n";
    strOwl += this->indent(nIndentation * nIndentationPerLevel) + "\n";

    return strOwl;
  }

  void OwlIndividual::resetIssuedProperties() {
    m_lstIssuedProperties.clear();
  }

  void OwlIndividual::resetIssuedTypes() {
    m_lstIssuedTypes.clear();
  }

  void OwlIndividual::resetIssuedInformation() {
    OwlIndividual::resetIssuedProperties();
    OwlIndividual::resetIssuedTypes();
  }

  std::list<std::string> OwlIndividual::issuedProperties() {
    return m_lstIssuedProperties;
  }

  std::list<std::string> OwlIndividual::issuedTypes() {
    return m_lstIssuedTypes;
  }
}
<commit_msg>Make sure no empty types are printed<commit_after>#include <plugins/owlexporter/OwlIndividual.h>

namespace beliefstate {
  std::list<std::string> OwlIndividual::m_lstIssuedProperties;
  std::list<std::string> OwlIndividual::m_lstIssuedTypes;

  OwlIndividual::OwlIndividual() {
    //
  }

  OwlIndividual::~OwlIndividual() {
    //
  }

  void OwlIndividual::setID(std::string strID) {
    m_strID = strID;
  }

  void OwlIndividual::setType(std::string strType) {
    m_strType = strType;

    this->issueType(strType);
  }

  void OwlIndividual::addDataProperty(std::string strTag, std::string strDataType, std::string strContent) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strDataType = strDataType;
    opProperty.strContent = strContent;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::addResourceProperty(std::string strTag, std::string strResource) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strResource = strResource;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::addContentProperty(std::string strTag, std::string strContent) {
    OwlProperty opProperty;
    opProperty.strTag = strTag;
    opProperty.strContent = strContent;

    m_lstProperties.push_back(opProperty);

    this->issueProperty(strTag);
  }

  void OwlIndividual::issueProperty(std::string strProperty) {
    std::string strPropertyFormatted = strProperty;

    size_t posColon = strPropertyFormatted.find(":");
    if(posColon != std::string::npos) {
      // Namespace found, convert it into short form
      strPropertyFormatted = "&" + strPropertyFormatted.substr(0, posColon) + ";" + strPropertyFormatted.substr(posColon + 1);
    }

    if(std::find(m_lstIssuedProperties.begin(), m_lstIssuedProperties.end(), strPropertyFormatted) == m_lstIssuedProperties.end()) {
      m_lstIssuedProperties.push_back(strPropertyFormatted);
    }
  }

  void OwlIndividual::issueType(std::string strType) {
    if(std::find(m_lstIssuedTypes.begin(), m_lstIssuedTypes.end(), strType) == m_lstIssuedTypes.end()) {
      m_lstIssuedTypes.push_back(strType);
    }
  }

  std::string OwlIndividual::indent(int nSpaces) {
    std::string strIndentation = "";

    for(int nI = 0; nI < nSpaces; nI++) {
      strIndentation += " ";
    }

    return strIndentation;
  }

  std::string OwlIndividual::print(int nIndentation, int nIndentationPerLevel) {
    std::string strOwl = "";

    if(strOwl != "") {
      strOwl += this->indent(nIndentation * nIndentationPerLevel) + "\n";
    }

    strOwl += this->indent(nIndentation * nIndentationPerLevel) +
      "<owl:namedIndividual rdf:about=\"" + m_strID + "\">\n";

    if(m_strType != "") {
      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel) +
	"<rdf:type rdf:resource=\"" + m_strType + "\"/>\n";
    }

    for(OwlProperty opProperty : m_lstProperties) {
      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel);
      strOwl += "<" + opProperty.strTag;

      if(opProperty.strDataType != "") {
	strOwl += " rdf:datatype=\"" + opProperty.strDataType + "\">" + opProperty.strContent;
	strOwl += "</" + opProperty.strTag + ">";
      } else if(opProperty.strResource != "") {
	strOwl += " rdf:resource=\"" + opProperty.strResource + "\"/>";
      } else {
	strOwl += ">" + opProperty.strContent;
	strOwl += "</" + opProperty.strTag + ">";
      }

      strOwl += "\n";
    }

    strOwl += this->indent(nIndentation * nIndentationPerLevel) +
      "</owl:namedIndividual>\n";
    strOwl += this->indent(nIndentation * nIndentationPerLevel) + "\n";

    return strOwl;
  }

  void OwlIndividual::resetIssuedProperties() {
    m_lstIssuedProperties.clear();
  }

  void OwlIndividual::resetIssuedTypes() {
    m_lstIssuedTypes.clear();
  }

  void OwlIndividual::resetIssuedInformation() {
    OwlIndividual::resetIssuedProperties();
    OwlIndividual::resetIssuedTypes();
  }

  std::list<std::string> OwlIndividual::issuedProperties() {
    return m_lstIssuedProperties;
  }

  std::list<std::string> OwlIndividual::issuedTypes() {
    return m_lstIssuedTypes;
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "snippetsparser.h"

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1String>
#include <QtCore/QLatin1Char>
#include <QtCore/QVariant>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDebug>

using namespace TextEditor;

SnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)
{}

const QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,
                                                     const QIcon &icon,
                                                     int order)
{
    if (!QFile::exists(m_fileName)) {
        m_snippets.clear();
    } else {
        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();
        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {
            m_snippets.clear();
            QFile file(m_fileName);
            file.open(QIODevice::ReadOnly);
            QXmlStreamReader xml(&file);
            if (xml.readNextStartElement()) {
                if (xml.name() == QLatin1String("snippets")) {
                    while (xml.readNextStartElement()) {
                        if (xml.name() == QLatin1String("snippet")) {
                            TextEditor::CompletionItem item(collector);
                            QString title;
                            QString data;
                            QString description = xml.attributes().value("description").toString();

                            while (!xml.atEnd()) {
                                xml.readNext();
                                if (xml.isEndElement()) {
                                    int i = 0;
                                    while (i < data.size() && data.at(i).isLetterOrNumber())
                                        ++i;
                                    title = data.left(i);
                                    item.text = title;
                                    if (!description.isEmpty()) {
                                        item.text +=  QLatin1Char(' ');
                                        item.text += description;
                                    }
                                    item.data = QVariant::fromValue(data);

                                    QString infotip = data;
                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())
                                        infotip.chop(1);
                                    infotip.replace(QLatin1Char('\n'), QLatin1String("
"));
                                    infotip.replace(QLatin1Char(' '), QLatin1String(" "));
                                    {
                                        QString s = QLatin1String("<nobr>");
                                        int count = 0;
                                        for (int i = 0; i < infotip.count(); ++i) {
                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {
                                                s += infotip.at(i);
                                                continue;
                                            }
                                            if (++count % 2) {
                                                s += QLatin1String("");
                                            } else {
                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)
                                                    s += QLatin1String("...");
                                                s += QLatin1String("");
                                            }
                                        }
                                        infotip = s;
                                    }
                                    item.details = infotip;

                                    item.icon = icon;
                                    item.order = order;
                                    item.isSnippet = true;
                                    m_snippets.append(item);
                                    break;
                                }

                                if (xml.isCharacters())
                                    data += xml.text();
                                else if (xml.isStartElement()) {
                                    if (xml.name() != QLatin1String("tab"))
                                        xml.raiseError(QLatin1String("invalid snippets file"));
                                    else {
                                        data += QChar::ObjectReplacementCharacter;
                                        data += xml.readElementText();
                                        data += QChar::ObjectReplacementCharacter;
                                    }
                                }
                            }
                        } else {
                            xml.skipCurrentElement();
                        }
                    }
                } else {
                    xml.skipCurrentElement();
                }
            }
            if (xml.hasError())
                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();
            file.close();

            m_lastTrackedFileChange = lastModified;
        }
    }

    return m_snippets;
}
<commit_msg>Snippets: Escape characters for the tip preview.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "snippetsparser.h"

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1String>
#include <QtCore/QLatin1Char>
#include <QtCore/QVariant>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDebug>
#include <QtGui/QTextDocument>

using namespace TextEditor;

SnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)
{}

const QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,
                                                     const QIcon &icon,
                                                     int order)
{
    if (!QFile::exists(m_fileName)) {
        m_snippets.clear();
    } else {
        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();
        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {
            m_snippets.clear();
            QFile file(m_fileName);
            file.open(QIODevice::ReadOnly);
            QXmlStreamReader xml(&file);
            if (xml.readNextStartElement()) {
                if (xml.name() == QLatin1String("snippets")) {
                    while (xml.readNextStartElement()) {
                        if (xml.name() == QLatin1String("snippet")) {
                            TextEditor::CompletionItem item(collector);
                            QString title;
                            QString data;
                            QString description = xml.attributes().value("description").toString();

                            while (!xml.atEnd()) {
                                xml.readNext();
                                if (xml.isEndElement()) {
                                    int i = 0;
                                    while (i < data.size() && data.at(i).isLetterOrNumber())
                                        ++i;
                                    title = data.left(i);
                                    item.text = title;
                                    if (!description.isEmpty()) {
                                        item.text +=  QLatin1Char(' ');
                                        item.text += description;
                                    }
                                    item.data = QVariant::fromValue(data);

                                    QString infotip = data;
                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())
                                        infotip.chop(1);
                                    infotip = Qt::escape(infotip);
                                    infotip.replace(QLatin1Char('\n'), QLatin1String("
"));
                                    infotip.replace(QLatin1Char(' '), QLatin1String(" "));
                                    {
                                        QString s = QLatin1String("<nobr>");
                                        int count = 0;
                                        for (int i = 0; i < infotip.count(); ++i) {
                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {
                                                s += infotip.at(i);
                                                continue;
                                            }
                                            if (++count % 2) {
                                                s += QLatin1String("");
                                            } else {
                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)
                                                    s += QLatin1String("...");
                                                s += QLatin1String("");
                                            }
                                        }
                                        infotip = s;
                                    }
                                    item.details = infotip;

                                    item.icon = icon;
                                    item.order = order;
                                    item.isSnippet = true;
                                    m_snippets.append(item);
                                    break;
                                }

                                if (xml.isCharacters())
                                    data += xml.text();
                                else if (xml.isStartElement()) {
                                    if (xml.name() != QLatin1String("tab"))
                                        xml.raiseError(QLatin1String("invalid snippets file"));
                                    else {
                                        data += QChar::ObjectReplacementCharacter;
                                        data += xml.readElementText();
                                        data += QChar::ObjectReplacementCharacter;
                                    }
                                }
                            }
                        } else {
                            xml.skipCurrentElement();
                        }
                    }
                } else {
                    xml.skipCurrentElement();
                }
            }
            if (xml.hasError())
                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();
            file.close();

            m_lastTrackedFileChange = lastModified;
        }
    }

    return m_snippets;
}
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "number_process.h"

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <boost/foreach.hpp>

namespace vistk
{

class number_process::priv
{
  public:
    typedef uint32_t number_t;

    priv(number_t s, number_t e);
    ~priv();

    number_t const start;
    number_t const end;
    number_t current;

    edges_t output_edges;

    static number_t const DEFAULT_START_VALUE;
    static number_t const DEFAULT_END_VALUE;
    static config::key_t const START_CONFIG_NAME;
    static config::key_t const END_CONFIG_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

number_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;
number_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;
config::key_t const number_process::priv::START_CONFIG_NAME = config::key_t("start");
config::key_t const number_process::priv::END_CONFIG_NAME = config::key_t("end");
process::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t("number");

number_process
::number_process(config_t const& config)
  : process(config)
{
  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);
  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);

  d = boost::shared_ptr<priv>(new priv(start, end));
}

number_process
::~number_process()
{
}

config::keys_t
number_process
::available_config() const
{
  config::keys_t keys;

  keys.push_back(priv::START_CONFIG_NAME);
  keys.push_back(priv::END_CONFIG_NAME);

  return keys;
}

config::value_t
number_process
::config_default(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE);
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE);
  }

  return process::config_default(key);
}

config::description_t
number_process
::config_description(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return config::description_t("The value to start counting at");
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return config::description_t("The value to stop counting at");
  }

  return process::config_description(key);
}

process_registry::type_t
number_process
::type() const
{
  return process_registry::type_t("number_process");
}

void
number_process
::_init()
{
  // Check the configuration.
  if (d->end <= d->start)
  {
    throw invalid_configuration(name(), "The start value must be greater than the end value");
  }

  // Ensure the output port is connected.
  if (!d->output_edges.size())
  {
    throw missing_connection(name(), priv::OUTPUT_PORT_NAME, "The " + type() + " process is not much use without something out output to");
  }
}

void
number_process
::_step()
{
  datum_t dat;

  if (d->current == d->end)
  {
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::new_datum(d->current);

    ++d->current;
  }

  BOOST_FOREACH (edge_t& edge, d->output_edges)
  {
    edge->push_datum(edge_datum_t(dat, heartbeat_stamp()));
  }

  process::_step();
}

void
number_process
::_connect_output_port(port_t const& port, edge_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge);
  }

  process::_connect_output_port(port, edge);
}

process::ports_t
number_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

number_process::priv
::priv(number_t s, number_t e)
  : start(s)
  , end(e)
  , current(s)
{
}

number_process::priv
::~priv()
{
}

} // end namespace vistk
<commit_msg>Use the convenience method for pushing data<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "number_process.h"

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

namespace vistk
{

class number_process::priv
{
  public:
    typedef uint32_t number_t;

    priv(number_t s, number_t e);
    ~priv();

    number_t const start;
    number_t const end;
    number_t current;

    edges_t output_edges;

    static number_t const DEFAULT_START_VALUE;
    static number_t const DEFAULT_END_VALUE;
    static config::key_t const START_CONFIG_NAME;
    static config::key_t const END_CONFIG_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

number_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;
number_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;
config::key_t const number_process::priv::START_CONFIG_NAME = config::key_t("start");
config::key_t const number_process::priv::END_CONFIG_NAME = config::key_t("end");
process::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t("number");

number_process
::number_process(config_t const& config)
  : process(config)
{
  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);
  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);

  d = boost::shared_ptr<priv>(new priv(start, end));
}

number_process
::~number_process()
{
}

config::keys_t
number_process
::available_config() const
{
  config::keys_t keys;

  keys.push_back(priv::START_CONFIG_NAME);
  keys.push_back(priv::END_CONFIG_NAME);

  return keys;
}

config::value_t
number_process
::config_default(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE);
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE);
  }

  return process::config_default(key);
}

config::description_t
number_process
::config_description(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return config::description_t("The value to start counting at");
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return config::description_t("The value to stop counting at");
  }

  return process::config_description(key);
}

process_registry::type_t
number_process
::type() const
{
  return process_registry::type_t("number_process");
}

void
number_process
::_init()
{
  // Check the configuration.
  if (d->end <= d->start)
  {
    throw invalid_configuration(name(), "The start value must be greater than the end value");
  }

  // Ensure the output port is connected.
  if (!d->output_edges.size())
  {
    throw missing_connection(name(), priv::OUTPUT_PORT_NAME, "The " + type() + " process is not much use without something out output to");
  }
}

void
number_process
::_step()
{
  datum_t dat;

  if (d->current == d->end)
  {
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::new_datum(d->current);

    ++d->current;
  }

  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());

  push_to_edges(d->output_edges, edat);

  process::_step();
}

void
number_process
::_connect_output_port(port_t const& port, edge_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge);
  }

  process::_connect_output_port(port, edge);
}

process::ports_t
number_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

number_process::priv
::priv(number_t s, number_t e)
  : start(s)
  , end(e)
  , current(s)
{
}

number_process::priv
::~priv()
{
}

} // end namespace vistk
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "number_process.h"

#include <vistk/pipeline_types/port_types.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

namespace vistk
{

class number_process::priv
{
  public:
    typedef uint32_t number_t;

    priv(number_t s, number_t e);
    ~priv();

    number_t const start;
    number_t const end;

    conf_info_t start_conf_info;
    conf_info_t end_conf_info;

    edge_group_t output_edges;

    port_info_t output_port_info;

    number_t current;

    static number_t const DEFAULT_START_VALUE;
    static number_t const DEFAULT_END_VALUE;
    static config::key_t const START_CONFIG_NAME;
    static config::key_t const END_CONFIG_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

number_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;
number_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;
config::key_t const number_process::priv::START_CONFIG_NAME = config::key_t("start");
config::key_t const number_process::priv::END_CONFIG_NAME = config::key_t("end");
process::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t("number");

number_process
::number_process(config_t const& config)
  : process(config)
{
  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);
  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);

  d = boost::shared_ptr<priv>(new priv(start, end));
}

number_process
::~number_process()
{
}

void
number_process
::_init()
{
  // Check the configuration.
  if (d->end <= d->start)
  {
    throw invalid_configuration_exception(name(), "The start value must be greater than the end value");
  }
}

void
number_process
::_step()
{
  datum_t dat;

  if (d->current == d->end)
  {
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::new_datum(d->current);

    ++d->current;
  }

  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());

  push_to_edges(d->output_edges, edat);

  process::_step();
}

void
number_process
::_connect_output_port(port_t const& port, edge_ref_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge);

    return;
  }

  process::_connect_output_port(port, edge);
}

process::port_info_t
number_process
::_output_port_info(port_t const& port) const
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    return d->output_port_info;
  }

  return process::_output_port_info(port);
}

process::ports_t
number_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

config::keys_t
number_process
::_available_config() const
{
  config::keys_t keys = process::_available_config();

  keys.push_back(priv::START_CONFIG_NAME);
  keys.push_back(priv::END_CONFIG_NAME);

  return keys;
}

process::conf_info_t
number_process
::_config_info(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return d->start_conf_info;
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return d->end_conf_info;
  }

  return process::_config_info(key);
}

number_process::priv
::priv(number_t s, number_t e)
  : start(s)
  , end(e)
  , current(s)
{
  port_flags_t required;

  required.insert(flag_required);

  output_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("Where the numbers will be available.")));

  start_conf_info = conf_info_t(new conf_info(
    boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE),
    config::description_t("The value to start counting at.")));
  end_conf_info = conf_info_t(new conf_info(
    boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE),
    config::description_t("The value to stop counting at.")));
}

number_process::priv
::~priv()
{
}

}
<commit_msg>Mark the number_process as complete<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "number_process.h"

#include <vistk/pipeline_types/port_types.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

namespace vistk
{

class number_process::priv
{
  public:
    typedef uint32_t number_t;

    priv(number_t s, number_t e);
    ~priv();

    number_t const start;
    number_t const end;

    conf_info_t start_conf_info;
    conf_info_t end_conf_info;

    edge_group_t output_edges;

    port_info_t output_port_info;

    number_t current;

    static number_t const DEFAULT_START_VALUE;
    static number_t const DEFAULT_END_VALUE;
    static config::key_t const START_CONFIG_NAME;
    static config::key_t const END_CONFIG_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

number_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;
number_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;
config::key_t const number_process::priv::START_CONFIG_NAME = config::key_t("start");
config::key_t const number_process::priv::END_CONFIG_NAME = config::key_t("end");
process::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t("number");

number_process
::number_process(config_t const& config)
  : process(config)
{
  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);
  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);

  d = boost::shared_ptr<priv>(new priv(start, end));
}

number_process
::~number_process()
{
}

void
number_process
::_init()
{
  // Check the configuration.
  if (d->end <= d->start)
  {
    throw invalid_configuration_exception(name(), "The start value must be greater than the end value");
  }
}

void
number_process
::_step()
{
  datum_t dat;

  if (d->current == d->end)
  {
    mark_as_complete();
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::new_datum(d->current);

    ++d->current;
  }

  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());

  push_to_edges(d->output_edges, edat);

  process::_step();
}

void
number_process
::_connect_output_port(port_t const& port, edge_ref_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge);

    return;
  }

  process::_connect_output_port(port, edge);
}

process::port_info_t
number_process
::_output_port_info(port_t const& port) const
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    return d->output_port_info;
  }

  return process::_output_port_info(port);
}

process::ports_t
number_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

config::keys_t
number_process
::_available_config() const
{
  config::keys_t keys = process::_available_config();

  keys.push_back(priv::START_CONFIG_NAME);
  keys.push_back(priv::END_CONFIG_NAME);

  return keys;
}

process::conf_info_t
number_process
::_config_info(config::key_t const& key) const
{
  if (key == priv::START_CONFIG_NAME)
  {
    return d->start_conf_info;
  }
  if (key == priv::END_CONFIG_NAME)
  {
    return d->end_conf_info;
  }

  return process::_config_info(key);
}

number_process::priv
::priv(number_t s, number_t e)
  : start(s)
  , end(e)
  , current(s)
{
  port_flags_t required;

  required.insert(flag_required);

  output_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("Where the numbers will be available.")));

  start_conf_info = conf_info_t(new conf_info(
    boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE),
    config::description_t("The value to start counting at.")));
  end_conf_info = conf_info_t(new conf_info(
    boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE),
    config::description_t("The value to stop counting at.")));
}

number_process::priv
::~priv()
{
}

}
<|endoftext|>


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

#include "boost/python.hpp"

#include <iostream>

#include "ri.h"

#if defined(_WIN32)
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif

using namespace std;
using namespace boost::python;

/// We use a static instance of this struct to initialise python when the dso is first loaded.
struct PythonInitialiser
{
	PythonInitialiser()
	{
		// start python
		Py_Initialize();
		PyEval_InitThreads();

			mainModule = object( handle<>( borrowed( PyImport_AddModule( "__main__" ) ) ) );
			mainModuleNamespace = mainModule.attr( "__dict__" );

			// load the IECoreRI and IECore modules so people don't have to do that in the string
			// they pass to be executed. this also means people don't have to worry about which
			// version to load. also set the dlopen flags to include RTLD_GLOBAL to avoid the dreaded
			// cross module rtti errors on linux.
			string toExecute =	"import sys\n"
								"import ctypes\n"
								"sys.setdlopenflags( sys.getdlopenflags() | ctypes.RTLD_GLOBAL )\n"
								"import IECore\n"
								"import IECoreRI\n";

			handle<> ignored( PyRun_String(
				toExecute.c_str(),
				Py_file_input, mainModuleNamespace.ptr(),
				mainModuleNamespace.ptr() ) );

		PyEval_ReleaseThread( PyThreadState_Get() );
	}

	object mainModule;
	object mainModuleNamespace;
};

static PythonInitialiser g_pythonInitialiser;

extern "C"
{

RtPointer DLLEXPORT ConvertParameters( RtString paramstr )
{
	return new string( paramstr );
}

RtVoid DLLEXPORT Subdivide( RtPointer data, float detail )
{
	PyGILState_STATE gilState = PyGILState_Ensure();

		try
		{

			string *i = (string *)data;

			handle<> ignored( PyRun_String( i->c_str(), Py_file_input, g_pythonInitialiser.mainModuleNamespace.ptr(),
				g_pythonInitialiser.mainModuleNamespace.ptr() ) );

		}
		catch( const error_already_set &e )
		{
			PyErr_Print();
		}
		catch( const std::exception &e )
		{
			cerr << "ERROR : Python procedural : " << e.what() << endl;
		}
		catch( ... )
		{
			cerr << "ERROR : Python procedural : caught unknown exception" << endl;
		}

	PyGILState_Release( gilState );
}

RtVoid DLLEXPORT Free( RtPointer data )
{
	string * i = (string *)data;
	delete i;
}

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

#include "boost/python.hpp"

#include <iostream>

#include "ri.h"

#if defined(_WIN32)
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif

using namespace std;
using namespace boost::python;

/// We use a static instance of this struct to initialise python when the dso is first loaded.
struct PythonInitialiser
{
	PythonInitialiser()
	{
		// start python
		Py_Initialize();
		PyEval_InitThreads();

			try
			{

				mainModule = object( handle<>( borrowed( PyImport_AddModule( "__main__" ) ) ) );
				mainModuleNamespace = mainModule.attr( "__dict__" );

				// load the IECoreRI and IECore modules so people don't have to do that in the string
				// they pass to be executed. this also means people don't have to worry about which
				// version to load. also set the dlopen flags to include RTLD_GLOBAL to avoid the dreaded
				// cross module rtti errors on linux.
				string toExecute =	"import sys\n"
									"import ctypes\n"
									"sys.setdlopenflags( sys.getdlopenflags() | ctypes.RTLD_GLOBAL )\n"
									"import IECore\n"
									"import IECoreRI\n";

				handle<> ignored( PyRun_String(
					toExecute.c_str(),
					Py_file_input, mainModuleNamespace.ptr(),
					mainModuleNamespace.ptr() ) );

			}
			catch( const error_already_set &e )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				cerr << "ERROR : Python procedural initialiser : " << e.what() << endl;
			}
			catch( ... )
			{
				cerr << "ERROR : Python procedural initialiser : caught unknown exception" << endl;
			}

		PyEval_ReleaseThread( PyThreadState_Get() );
	}

	object mainModule;
	object mainModuleNamespace;
};

static PythonInitialiser g_pythonInitialiser;

extern "C"
{

RtPointer DLLEXPORT ConvertParameters( RtString paramstr )
{
	return new string( paramstr );
}

RtVoid DLLEXPORT Subdivide( RtPointer data, float detail )
{
	PyGILState_STATE gilState = PyGILState_Ensure();

		try
		{

			string *i = (string *)data;

			handle<> ignored( PyRun_String( i->c_str(), Py_file_input, g_pythonInitialiser.mainModuleNamespace.ptr(),
				g_pythonInitialiser.mainModuleNamespace.ptr() ) );

		}
		catch( const error_already_set &e )
		{
			PyErr_Print();
		}
		catch( const std::exception &e )
		{
			cerr << "ERROR : Python procedural : " << e.what() << endl;
		}
		catch( ... )
		{
			cerr << "ERROR : Python procedural : caught unknown exception" << endl;
		}

	PyGILState_Release( gilState );
}

RtVoid DLLEXPORT Free( RtPointer data )
{
	string * i = (string *)data;
	delete i;
}

}
<|endoftext|>


<commit_before>#include <functional>
#include <future>
#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "basetable.h"
#include "flattable.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "identifieritem.h"
#include "identifierrange.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "operationhelpergrid.h"
#include "geometryhelper.h"
#include "mirrorrotateraster.h"

using namespace Ilwis;
using namespace RasterOperations;

REGISTER_OPERATION(MirrorRotateRaster)

MirrorRotateRaster::MirrorRotateRaster()
{
}

MirrorRotateRaster::MirrorRotateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool MirrorRotateRaster::dimChanged(const PixelIterator& iter) const{
    switch(_method)    {
    case tmMirrorVertical:
        return iter.ychanged();
    case tmMirrorHorizontal:
        return iter.xchanged();
    case tmRotate90:
        return iter.xchanged();
    case tmRotate270:
        return iter.xchanged();
    default:
        break;
    }
    return false;
}
void MirrorRotateRaster::translatepixels(PixelIterator iterIn,PixelIterator iterOut, const BoundingBox& box, quint32 linelength ){
    std::vector<double> line(linelength);
    auto iterLine = line.begin();
    auto end = iterIn.end();
    for(; iterIn != end; ++iterIn, ++iterLine){
        if ( dimChanged(iterIn)){
            std::reverse(line.begin(), line.end());
            std::copy(line.begin(), line.end(),iterOut);
            iterLine = line.begin();
            iterOut += iterIn.box().xlength();
        }
        (*iterLine) = *iterIn;
    }
    // lastline
    std::reverse(line.begin(), line.end());
    std::copy(line.begin(), line.end(),iterOut);
}

bool MirrorRotateRaster::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx,symTable)) != sPREPARED)
            return false;

    std::function<bool(const BoundingBox)> Transform = [&](const BoundingBox box ) -> bool {
        if ( _method == tmMirrorVertical){
             translatepixels(PixelIterator(_inputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());
        }
        if ( _method == tmMirrorHorizontal){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());
        }
        if ( _method == tmRotate90){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fXYZ), box, _outputRaster->size().ysize());
        }
        if ( _method == tmRotate180){
            _method = tmMirrorHorizontal;
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());
             _method = tmMirrorVertical;
             translatepixels(PixelIterator(_outputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());
             _method = tmRotate180;
        }
        if ( _method == tmRotate270){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fXYZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().xsize());
        }

        return true;

    };

    return  OperationHelperRaster::execute(ctx, Transform, _outputRaster);
}

Ilwis::OperationImplementation *MirrorRotateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new MirrorRotateRaster(metaid, expr);
}

Ilwis::OperationImplementation::State MirrorRotateRaster::prepare(ExecutionContext *ctx, const SymbolTable &)
{
    QString raster = _expression.parm(0).value();
    QString outputName = _expression.parm(0,false).value();
    QString method = _expression.parm(1).value().toLower();

    if (!_inputRaster.prepare(raster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    std::map<QString, TransPoseMethod> methods={{"mirrhor",tmMirrorHorizontal},{"mirrvert",tmMirrorVertical},
                                                {"mirrdiag",tmMirrorDiagonal},{"transpose",tmTranspose},{"rotate90",tmRotate90},
                                                {"rotate180",tmRotate180},{"rotate270",tmRotate270}};
    auto iter = methods.find(method);
    if ( iter == methods.end()){
        ERROR2(ERR_NOT_FOUND2,method, TR("in method for mirrorrotate"));
        return sPREPAREFAILED;
    }
    _method = iter->second;
    Size<> sz = _inputRaster->size();
    Envelope outputenv = _inputRaster->envelope();
    if ( _method == tmTranspose || _method == tmRotate90 || _method == tmRotate270){
        sz = Size<>(sz.ysize(), sz.xsize(), sz.zsize());
        Coordinate center = (outputenv.max_corner() + outputenv.min_corner()) / 2.0;
        auto rotated = GeometryHelper::rotate2d(center,90,(std::vector<Coordinate>)outputenv);
        outputenv = {rotated};
    }

    _outputRaster = OperationHelperRaster::initialize(_inputRaster,itRASTER,itCOORDSYSTEM | itDOMAIN);

    QString grfs = QString("code=georef:type=corners,csy=%1,envelope=%2,gridsize=%3")
            .arg(_outputRaster->coordinateSystem()->id())
            .arg(outputenv.toString())
            .arg(sz.toString());
    _outputRaster->georeference(grfs);
    if (outputName != sUNDEF)
        _outputRaster->name(outputName);

    return sPREPARED;
}

quint64 MirrorRotateRaster::createMetadata()
{
    OperationResource operation({"ilwis://operations/mirrorrotateraster"});
    operation.setSyntax("mirrorrotateraster(inputraster,mirrhor | mirrvert | mirrdiag | transpose | rotate90 | rotate180 | rotate270)");
    operation.setDescription(TR("transpose the raster according to the method indicated by the second parameter"));
    operation.setInParameterCount({2});
    operation.addInParameter(0,itRASTER,  TR("input raster"),TR("ratser to be transposed"));
    operation.addInParameter(1,itSTRING, TR("transpose method"),TR("rotation or mirror of the input map"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(0,itRASTER, TR("output raster"), TR("output raster with a new georef"));
    operation.setKeywords("raster, geometry");

    mastercatalog()->addItems({operation});
    return operation.id();
}
<commit_msg>added output strage in operation<commit_after>#include <functional>
#include <future>
#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "basetable.h"
#include "flattable.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "identifieritem.h"
#include "identifierrange.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "operationhelpergrid.h"
#include "geometryhelper.h"
#include "mirrorrotateraster.h"

using namespace Ilwis;
using namespace RasterOperations;

REGISTER_OPERATION(MirrorRotateRaster)

MirrorRotateRaster::MirrorRotateRaster()
{
}

MirrorRotateRaster::MirrorRotateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{

}

bool MirrorRotateRaster::dimChanged(const PixelIterator& iter) const{
    switch(_method)    {
    case tmMirrorVertical:
        return iter.ychanged();
    case tmMirrorHorizontal:
        return iter.xchanged();
    case tmRotate90:
        return iter.xchanged();
    case tmRotate270:
        return iter.xchanged();
    default:
        break;
    }
    return false;
}
void MirrorRotateRaster::translatepixels(PixelIterator iterIn,PixelIterator iterOut, const BoundingBox& box, quint32 linelength ){
    std::vector<double> line(linelength);
    auto iterLine = line.begin();
    auto end = iterIn.end();
    for(; iterIn != end; ++iterIn, ++iterLine){
        if ( dimChanged(iterIn)){
            std::reverse(line.begin(), line.end());
            std::copy(line.begin(), line.end(),iterOut);
            iterLine = line.begin();
            iterOut += iterIn.box().xlength();
        }
        (*iterLine) = *iterIn;
    }
    // lastline
    std::reverse(line.begin(), line.end());
    std::copy(line.begin(), line.end(),iterOut);
}

bool MirrorRotateRaster::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx,symTable)) != sPREPARED)
            return false;

    std::function<bool(const BoundingBox)> Transform = [&](const BoundingBox box ) -> bool {
        if ( _method == tmMirrorVertical){
             translatepixels(PixelIterator(_inputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());
        }
        if ( _method == tmMirrorHorizontal){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());
        }
        if ( _method == tmRotate90){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fXYZ), box, _outputRaster->size().ysize());
        }
        if ( _method == tmRotate180){
            _method = tmMirrorHorizontal;
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());
             _method = tmMirrorVertical;
             translatepixels(PixelIterator(_outputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());
             _method = tmRotate180;
        }
        if ( _method == tmRotate270){
             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fXYZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().xsize());
        }
        return true;

    };

    bool ok = OperationHelperRaster::execute(ctx, Transform, _outputRaster);

    if ( ok && ctx != 0) {
        QVariant value;
        value.setValue<IRasterCoverage>(_outputRaster);
        ctx->setOutput(symTable,value,_outputRaster->name(), itRASTER, _outputRaster->source() );
    }
    return ok;
}

Ilwis::OperationImplementation *MirrorRotateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new MirrorRotateRaster(metaid, expr);
}

Ilwis::OperationImplementation::State MirrorRotateRaster::prepare(ExecutionContext *ctx, const SymbolTable &)
{
    QString raster = _expression.parm(0).value();
    QString outputName = _expression.parm(0,false).value();
    QString method = _expression.parm(1).value().toLower();

    if (!_inputRaster.prepare(raster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    std::map<QString, TransPoseMethod> methods={{"mirrhor",tmMirrorHorizontal},{"mirrvert",tmMirrorVertical},
                                                {"mirrdiag",tmMirrorDiagonal},{"transpose",tmTranspose},{"rotate90",tmRotate90},
                                                {"rotate180",tmRotate180},{"rotate270",tmRotate270}};
    auto iter = methods.find(method);
    if ( iter == methods.end()){
        ERROR2(ERR_NOT_FOUND2,method, TR("in method for mirrorrotate"));
        return sPREPAREFAILED;
    }
    _method = iter->second;
    Size<> sz = _inputRaster->size();
    Envelope outputenv = _inputRaster->envelope();
    if ( _method == tmTranspose || _method == tmRotate90 || _method == tmRotate270){
        sz = Size<>(sz.ysize(), sz.xsize(), sz.zsize());
        Coordinate center = (outputenv.max_corner() + outputenv.min_corner()) / 2.0;
        auto rotated = GeometryHelper::rotate2d(center,90,(std::vector<Coordinate>)outputenv);
        outputenv = {rotated};
    }

    _outputRaster = OperationHelperRaster::initialize(_inputRaster,itRASTER,itCOORDSYSTEM | itDOMAIN);

    QString grfs = QString("code=georef:type=corners,csy=%1,envelope=%2,gridsize=%3")
            .arg(_outputRaster->coordinateSystem()->id())
            .arg(outputenv.toString())
            .arg(sz.toString());
    _outputRaster->georeference(grfs);
    if (outputName != sUNDEF)
        _outputRaster->name(outputName);

    return sPREPARED;
}

quint64 MirrorRotateRaster::createMetadata()
{
    OperationResource operation({"ilwis://operations/mirrorrotateraster"});
    operation.setSyntax("mirrorrotateraster(inputraster,mirrhor | mirrvert | mirrdiag | transpose | rotate90 | rotate180 | rotate270)");
    operation.setDescription(TR("transpose the raster according to the method indicated by the second parameter"));
    operation.setInParameterCount({2});
    operation.addInParameter(0,itRASTER,  TR("input raster"),TR("ratser to be transposed"));
    operation.addInParameter(1,itSTRING, TR("transpose method"),TR("rotation or mirror of the input map"));
    operation.setOutParameterCount({1});
    operation.addOutParameter(0,itRASTER, TR("output raster"), TR("output raster with a new georef"));
    operation.setKeywords("raster, geometry");

    mastercatalog()->addItems({operation});
    return operation.id();
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2017 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/steering-method/constant-curvature.hh>

#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
#include <pinocchio/spatial/se3.hpp>

namespace hpp {
  namespace core {
    namespace steeringMethod {

      ConstantCurvaturePtr_t ConstantCurvature::create
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels)
      {
        ConstantCurvature* ptr (new ConstantCurvature
                                (robot, init, end, length, curvature, xyId,
                                 rzId, rz, wheels));
        ConstantCurvaturePtr_t shPtr (ptr);
        ptr->init (shPtr);
        return shPtr;
      }

      ConstantCurvaturePtr_t ConstantCurvature::createCopy
      (const ConstantCurvaturePtr_t& other)
      {
        ConstantCurvature* ptr (new ConstantCurvature (*other));
        ConstantCurvaturePtr_t shPtr (ptr);
        ptr->init (shPtr);
        return shPtr;
      }

      ConstantCurvaturePtr_t ConstantCurvature::createCopy
      (const ConstantCurvaturePtr_t& other,
       const ConstraintSetPtr_t& constraints)
      {
	ConstantCurvature* ptr = new ConstantCurvature (*other, constraints);
	ConstantCurvaturePtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// Return a shared pointer to a copy of this
      PathPtr_t ConstantCurvature::copy () const
      {
	return createCopy (weak_.lock ());
      }

      std::ostream& ConstantCurvature::print (std::ostream &os) const
      {
        os << "-- ConstantCurvature" << std::endl;
        os << "from " << initial_.transpose () << std::endl;
        os << "  length: " << forward_ * timeRange ().second << std::endl;
        os << "  curvature: " << curvature_ << std::endl;
        return os;
      }

      ConstantCurvature::ConstantCurvature
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels,
       ConstraintSetPtr_t constraints) :
        Path (std::make_pair (0., fabs (length)), robot->configSize (),
              robot->numberDof (), constraints), robot_ (robot),
        initial_ (init), end_ (end), curvature_ (curvature),
        xyId_ (xyId), rzId_ (rzId), forward_ (length > 0 ? 1 : -1)
      {
        // Find rank of translation and rotation in velocity vectors
        // Hypothesis: degrees of freedom all belong to a planar joint or
        // xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.
        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));
        size_type offset (xyId_ - joint->rankInConfiguration ());
        dxyId_ = joint->rankInVelocity () + offset;
        joint = robot_->getJointAtConfigRank (rzId_);
        offset = rzId_ - joint->rankInConfiguration ();
        drzId_ = joint->rankInVelocity () + offset;
        setWheelJoints (rz, wheels);
        impl_compute (end_, timeRange ().second);
      }

      ConstantCurvature::ConstantCurvature
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels) :
        Path (std::make_pair (0., fabs (length)), robot->configSize (),
              robot->numberDof ()), robot_ (robot),
        initial_ (init), end_ (end), curvature_ (curvature), xyId_ (xyId),
        rzId_ (rzId), forward_ (length > 0 ? 1 : -1)
      {
        // Find rank of translation and rotation in velocity vectors
        // Hypothesis: degrees of freedom all belong to a planar joint or
        // xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.
        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));
        size_type offset (xyId_ - joint->rankInConfiguration ());
        dxyId_ = joint->rankInVelocity () + offset;
        joint = robot_->getJointAtConfigRank (rzId_);
        offset = rzId_ - joint->rankInConfiguration ();
        drzId_ = joint->rankInVelocity () + offset;
        setWheelJoints (rz, wheels);
        impl_compute (end_, timeRange ().second);
      }

      ConstantCurvature::ConstantCurvature (const ConstantCurvature& other) :
        Path (other), robot_ (other.robot_), initial_ (other.initial_),
        end_ (other.end_), curvature_ (other.curvature_),  xyId_ (other.xyId_),
        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)
      {
      }

      ConstantCurvature::ConstantCurvature
      (const ConstantCurvature& other, const ConstraintSetPtr_t& constraints) :
        parent_t (other, constraints), robot_ (other.robot_),
        initial_ (other.initial_), end_ (other.end_),
        curvature_ (other.curvature_),  xyId_ (other.xyId_),
        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)
      {
      }

      bool ConstantCurvature::impl_compute (ConfigurationOut_t result,
                                            value_type param) const
      {
        // Does a linear interpolation on all the joints.
        const value_type u = (timeRange ().second == 0) ? 0 :
          param/timeRange ().second;
        pinocchio::interpolate (robot_, initial_, end_, u, result);

        value_type t (forward_ * param);
        value_type x0 (initial_ [xyId_ + 0]), y0 (initial_ [xyId_ + 1]);
        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);
        value_type x, y;
        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));

        if (curvature_ == 0) {
          x  = x0 + t * c0;
          y  = y0 + t * s0;
        } else {
          value_type r (1./curvature_);
          x = x0 + r * (s0 * (c - 1) + c0 * s);
          y = y0 + r * (c0 * (1 - c) + s0 * s);
        }
        result [xyId_ + 0] = x;
        result [xyId_ + 1] = y;
        result [rzId_ + 0] = c0 * c - s0 * s;
        result [rzId_ + 1] = c0 * s + s0 * c;

        // Set wheel joint positions
        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();
             w < wheels_.end (); ++w) {
          result [w->j->rankInConfiguration ()] = w->value;
        }
        return true;
      }

      void ConstantCurvature::impl_derivative
      (vectorOut_t result, const value_type& param, size_type order) const
      {
        value_type t (forward_ * param);
        value_type alpha (1);
        if (forward_ == -1 && order%2 == 1) alpha = -1;
        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);
        value_type dx, dy, dtheta = 0;
        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));

        if (order <= 0) {
          std::ostringstream oss;
          oss << "order of derivative (" << order << ") should be positive.";
          throw std::runtime_error (oss.str ().c_str ());
        }
        if (order == 1) {
          dx = alpha * (c0 * c - s0 * s);
          dy = alpha * (c0 * s + s0 * c);
          dtheta = alpha * curvature_;
        } else if (order % 4 == 2) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
        } else if (order % 4 == 3) {
          dx = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
        } else if (order % 4 == 0) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
        } else if (order % 4 == 1) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
          dy =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
        }

        result [dxyId_ + 0] = dx;
        result [dxyId_ + 1] = dy;
        result [rzId_] = dtheta;

        // Set wheel joint velocities
        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();
             w < wheels_.end (); ++w) {
          result [w->j->rankInConfiguration ()] = 0;
        }
      }

      inline value_type meanBounds(const JointPtr_t& j, const size_type& i)
      {
        return (j->upperBound(i) + j->lowerBound(i))/2;
      }

      inline value_type saturate (const value_type& v, const JointPtr_t& j,
                                  const size_type& i)
      {
        return std::min(j->upperBound(i), std::max(j->lowerBound(i), v));
      }

      void ConstantCurvature::setWheelJoints
      (const JointPtr_t rz, const std::vector<JointPtr_t> wheels)
      {
        Transform3f zt (rz->currentTransformation ().inverse ());
        wheels_.resize(wheels.size());
        std::size_t rk = 0;
        if (curvature_ == 0) {
          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();
               _wheels != wheels.end(); ++_wheels) {
            wheels_[rk].j = *_wheels;
            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);
            ++rk;
          }
        } else {
          value_type rho (1./curvature_);
          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();
               _wheels != wheels.end(); ++_wheels) {
            wheels_[rk].j = *_wheels;
            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);
            const vector3_t wheelPos = zt.act
              (wheels_[rk].j->currentTransformation().translation());
            const value_type value (std::atan(wheelPos[0] /
                                              (rho - wheelPos[1])));
            wheels_[rk].value = saturate(meanBounds(wheels_[rk].j, 0) + value,
                                         *_wheels, 0);
            ++rk;
          }
        }
      }

    } // namespace steeringMethod
  } // namespace core
} // namespace hpp
<commit_msg>Fix steeringMethod::ConstantCurvature<commit_after>//
// Copyright (c) 2017 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/steering-method/constant-curvature.hh>

#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
#include <pinocchio/spatial/se3.hpp>

namespace hpp {
  namespace core {
    namespace steeringMethod {

      ConstantCurvaturePtr_t ConstantCurvature::create
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels)
      {
        ConstantCurvature* ptr (new ConstantCurvature
                                (robot, init, end, length, curvature, xyId,
                                 rzId, rz, wheels));
        ConstantCurvaturePtr_t shPtr (ptr);
        ptr->init (shPtr);
        return shPtr;
      }

      ConstantCurvaturePtr_t ConstantCurvature::createCopy
      (const ConstantCurvaturePtr_t& other)
      {
        ConstantCurvature* ptr (new ConstantCurvature (*other));
        ConstantCurvaturePtr_t shPtr (ptr);
        ptr->init (shPtr);
        return shPtr;
      }

      ConstantCurvaturePtr_t ConstantCurvature::createCopy
      (const ConstantCurvaturePtr_t& other,
       const ConstraintSetPtr_t& constraints)
      {
	ConstantCurvature* ptr = new ConstantCurvature (*other, constraints);
	ConstantCurvaturePtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// Return a shared pointer to a copy of this
      PathPtr_t ConstantCurvature::copy () const
      {
	return createCopy (weak_.lock ());
      }

      std::ostream& ConstantCurvature::print (std::ostream &os) const
      {
        os << "-- ConstantCurvature" << std::endl;
        os << "from " << initial_.transpose () << std::endl;
        os << "  length: " << forward_ * paramLength() << std::endl;
        os << "  curvature: " << curvature_ << std::endl;
        return os;
      }

      ConstantCurvature::ConstantCurvature
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels,
       ConstraintSetPtr_t constraints) :
        Path (std::make_pair (0., fabs (length)), robot->configSize (),
              robot->numberDof (), constraints), robot_ (robot),
        initial_ (init), end_ (end), curvature_ (curvature),
        xyId_ (xyId), rzId_ (rzId), forward_ (length > 0 ? 1 : -1)
      {
        // Find rank of translation and rotation in velocity vectors
        // Hypothesis: degrees of freedom all belong to a planar joint or
        // xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.
        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));
        size_type offset (xyId_ - joint->rankInConfiguration ());
        dxyId_ = joint->rankInVelocity () + offset;
        joint = robot_->getJointAtConfigRank (rzId_);
        offset = rzId_ - joint->rankInConfiguration ();
        drzId_ = joint->rankInVelocity () + offset;
        setWheelJoints (rz, wheels);
        impl_compute (end_, paramRange ().second);
      }

      ConstantCurvature::ConstantCurvature
      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,
       value_type length, value_type curvature, size_type xyId, size_type rzId,
       const JointPtr_t rz, const std::vector<JointPtr_t> wheels) :
        Path (std::make_pair (0., fabs (length)), robot->configSize (),
              robot->numberDof ()), robot_ (robot),
        initial_ (init), end_ (end), curvature_ (curvature), xyId_ (xyId),
        rzId_ (rzId), forward_ (length > 0 ? 1 : -1)
      {
        // Find rank of translation and rotation in velocity vectors
        // Hypothesis: degrees of freedom all belong to a planar joint or
        // xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.
        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));
        size_type offset (xyId_ - joint->rankInConfiguration ());
        dxyId_ = joint->rankInVelocity () + offset;
        joint = robot_->getJointAtConfigRank (rzId_);
        offset = rzId_ - joint->rankInConfiguration ();
        drzId_ = joint->rankInVelocity () + offset;
        setWheelJoints (rz, wheels);
        impl_compute (end_, paramRange ().second);
      }

      ConstantCurvature::ConstantCurvature (const ConstantCurvature& other) :
        Path (other), robot_ (other.robot_), initial_ (other.initial_),
        end_ (other.end_), curvature_ (other.curvature_),  xyId_ (other.xyId_),
        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)
      {
      }

      ConstantCurvature::ConstantCurvature
      (const ConstantCurvature& other, const ConstraintSetPtr_t& constraints) :
        parent_t (other, constraints), robot_ (other.robot_),
        initial_ (other.initial_), end_ (other.end_),
        curvature_ (other.curvature_),  xyId_ (other.xyId_),
        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)
      {
      }

      bool ConstantCurvature::impl_compute (ConfigurationOut_t result,
                                            value_type param) const
      {
        const value_type L = paramLength();
        // Does a linear interpolation on all the joints.
        const value_type u = (L == 0) ? 0 : ((param - paramRange ().first) / L );
        pinocchio::interpolate (robot_, initial_, end_, u, result);

        value_type t (forward_ * param);
        value_type x0 (initial_ [xyId_ + 0]), y0 (initial_ [xyId_ + 1]);
        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);
        value_type x, y;
        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));

        if (curvature_ == 0) {
          x  = x0 + t * c0;
          y  = y0 + t * s0;
        } else {
          value_type r (1./curvature_);
          x = x0 + r * (s0 * (c - 1) + c0 * s);
          y = y0 + r * (c0 * (1 - c) + s0 * s);
        }
        result [xyId_ + 0] = x;
        result [xyId_ + 1] = y;
        result [rzId_ + 0] = c0 * c - s0 * s;
        result [rzId_ + 1] = c0 * s + s0 * c;

        // Set wheel joint positions
        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();
             w < wheels_.end (); ++w) {
          result [w->j->rankInConfiguration ()] = w->value;
        }
        return true;
      }

      void ConstantCurvature::impl_derivative
      (vectorOut_t result, const value_type& param, size_type order) const
      {
        value_type t (forward_ * param);
        value_type alpha (1);
        if (forward_ == -1 && order%2 == 1) alpha = -1;
        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);
        value_type dx, dy, dtheta = 0;
        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));

        if (order <= 0) {
          std::ostringstream oss;
          oss << "order of derivative (" << order << ") should be positive.";
          throw std::runtime_error (oss.str ().c_str ());
        }
        if (order == 1) {
          dx = alpha * (c0 * c - s0 * s);
          dy = alpha * (c0 * s + s0 * c);
          dtheta = alpha * curvature_;
        } else if (order % 4 == 2) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
        } else if (order % 4 == 3) {
          dx = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
        } else if (order % 4 == 0) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
        } else if (order % 4 == 1) {
          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * c - s0 * s);
          dy =  alpha * pow (curvature_, (value_type) (order - 1)) *
            (c0 * s + s0 * c);
        }

        result [dxyId_ + 0] = dx;
        result [dxyId_ + 1] = dy;
        result [rzId_] = dtheta;

        // Set wheel joint velocities
        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();
             w < wheels_.end (); ++w) {
          result [w->j->rankInConfiguration ()] = 0;
        }
      }

      inline value_type meanBounds(const JointPtr_t& j, const size_type& i)
      {
        return (j->upperBound(i) + j->lowerBound(i))/2;
      }

      inline value_type saturate (const value_type& v, const JointPtr_t& j,
                                  const size_type& i)
      {
        return std::min(j->upperBound(i), std::max(j->lowerBound(i), v));
      }

      void ConstantCurvature::setWheelJoints
      (const JointPtr_t rz, const std::vector<JointPtr_t> wheels)
      {
        Transform3f zt (rz->currentTransformation ().inverse ());
        wheels_.resize(wheels.size());
        std::size_t rk = 0;
        if (curvature_ == 0) {
          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();
               _wheels != wheels.end(); ++_wheels) {
            wheels_[rk].j = *_wheels;
            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);
            ++rk;
          }
        } else {
          value_type rho (1./curvature_);
          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();
               _wheels != wheels.end(); ++_wheels) {
            wheels_[rk].j = *_wheels;
            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);
            const vector3_t wheelPos = zt.act
              (wheels_[rk].j->currentTransformation().translation());
            const value_type value (std::atan(wheelPos[0] /
                                              (rho - wheelPos[1])));
            wheels_[rk].value = saturate(meanBounds(wheels_[rk].j, 0) + value,
                                         *_wheels, 0);
            ++rk;
          }
        }
      }

    } // namespace steeringMethod
  } // namespace core
} // namespace hpp
<|endoftext|>