<commit_before>/******************************************************************************

  This source file is part of the MongoModel project.

  Copyright 2011 Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

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

******************************************************************************/

#include "MongoModel.h"

#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QSize>
#include <QtCore/QDebug>
#include <QtGui/QColor>
#include <QtGui/QPixmap>

#include <vtkNew.h>
#include <vtkTable.h>
#include <vtkFloatArray.h>
#include <vtkStringArray.h>

using namespace mongo;

namespace ChemData {

class MongoModel::Private
{
public:
  Private(const QString &host) : m_namespace("chem.import"), m_rows(0)
  {
  this->connect(host);
  }

  ~Private()
  {
  }

  bool connect(const QString &host)
  {
    try {
      m_db.connect(host.toStdString());
      cout << "connected OK" << endl;
      return query();
    }
    catch (DBException &e) {
      cout << "caught " << e.what() << endl;
      return false;
    }
  }

  bool query()
  {
    if (m_db.isFailed())
      return false;
    m_rowObjects.resize(0);
    m_rows = m_db.count(m_namespace.toStdString());
    m_rowObjects.reserve(m_rows);
    BSONObj empty;
    m_cursor = m_db.query(m_namespace.toStdString(), Query().sort("Observed"));
    //, QUERY("ago" << 33));
    return true;
  }

  BSONObj * getRecord(unsigned int index)
  {
    if (index < m_rowObjects.size()) {
      return &m_rowObjects[index];
    }
    else {
      while (index >= m_rowObjects.size() && m_cursor->more())
        m_rowObjects.push_back(m_cursor->next().getOwned());
      // If there are enough objects, return the one requested
      if (index < m_rowObjects.size())
        return &m_rowObjects[index];
      else
        return 0;
    }
  }

  DBClientConnection m_db;
  auto_ptr<DBClientCursor> m_cursor;
  QString m_namespace;
  std::vector<BSONObj> m_rowObjects;
  int m_rows;

  QStringList m_fields;
  QMap<QString, QString> m_titles;
};

MongoModel::MongoModel(QObject *parent)
  : QAbstractItemModel(parent)
{
  d = new MongoModel::Private("localhost");
//  d = new MongoModel::Private("londinium.kitwarein.com");

  d->m_fields << "CAS" << "Set"
              << "Molecular Weight"
              << "Observed"
              << "Predicted log Sw (MLR)"
              << "Predicted log Sw (RF)";
  d->m_titles["Observed"] = "Observed log(Sw)";
  d->m_titles["Predicted log Sw (MLR)"] = "log(Sw) (MLR)";
  d->m_titles["Predicted log Sw (RF)"] = "log(Sw) (RF)";
}

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

QModelIndex MongoModel::parent(const QModelIndex &) const
{
  return QModelIndex();
}

int MongoModel::rowCount(const QModelIndex &parent) const
{
  return d->m_rows;
}

int MongoModel::columnCount(const QModelIndex &parent) const
{
  return d->m_fields.size();
}

QVariant MongoModel::headerData(int section, Qt::Orientation orientation,
                                int role) const
{
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
    if (d->m_titles.contains(d->m_fields[section]))
      return d->m_titles[d->m_fields[section]];
    else
      return d->m_fields[section];
  }
  else if (orientation == Qt::Vertical && role == Qt::DisplayRole) {
    return QVariant(section);
  }
  return QVariant();
}

QVariant MongoModel::data(const QModelIndex &index, int role) const
{
  if (index.internalPointer()) {
    BSONObj *obj = static_cast<BSONObj *>(index.internalPointer());
    if (obj) {
      if (role == Qt::DisplayRole) {
        BSONElement e = obj->getField(d->m_fields[index.column()].toStdString());
        if (e.isNumber())
          return QVariant(e.number());
        else if (e.isNull())
          return QVariant();
        else
          return e.str().c_str();
      }
      else if (role == Qt::SizeHintRole) {
        if (d->m_fields[index.column()] == "Molecular Weight" &&
            !obj->getField("2D PNG").eoo()) {
          return QVariant(QSize(250, 250));
        }
        else {
          return QVariant(QSize(120, 20));
        }
      }
      else if (role == Qt::DecorationRole) {
        if (d->m_fields[index.column()] == "CAS") {
          if (obj->getField("InChIKey").eoo())
            return Qt::red;
          else
            return Qt::green;
        }
        else if (d->m_fields[index.column()] == "Molecular Weight") {
          BSONElement image = obj->getField("2D PNG");
          if (!image.eoo()) {
            int length;
            const char *data = image.binData(length);
            QByteArray inData(data, length);
            QImage in = QImage::fromData(inData, "PNG");
            QPixmap pix = QPixmap::fromImage(in);
            return QVariant(pix);
          }
        }
      }
      else if (role == Qt::ToolTipRole) {
        if (d->m_fields[index.column()] == "CAS") {
          BSONElement iupac = obj->getField("IUPAC");
          if (iupac.eoo())
            return "Unknown";
          else
            return iupac.str().c_str();
        }
        else if (d->m_fields[index.column()] == "Molecular Weight") {
          BSONElement e = obj->getField("Formula");
          if (!e.eoo()) {
            QStringList parts = QString(e.str().c_str()).split(" ",
                                                               QString::SkipEmptyParts);
            QString formula;
            for (int i = 0; i < parts.size(); i += 2) {
              formula += parts[i];
              if (parts[i+1].toInt() > 1)
                formula += "" + parts[i+1] + "";
            }
            return formula;
          }
        }
      }
    }

  }
  return QVariant();
}

bool MongoModel::setData(const QModelIndex &index, const QVariant &value,
                         int role)
{
  return false;
}

Qt::ItemFlags MongoModel::flags(const QModelIndex &index) const
{
  if (index.column() == 0)
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
  else
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

QModelIndex MongoModel::index(int row, int column,
                              const QModelIndex &parent) const
{
  if (row >= 0 && row < d->m_rows) {
    BSONObj *obj = d->getRecord(row);
    return createIndex(row, column, obj);
  }
  return QModelIndex();
}

void MongoModel::clear()
{
}

bool MongoModel::addIdentifiers(int row, const QString &identifiers)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  QStringList lines = identifiers.split("\n", QString::SkipEmptyParts);
  for (int i = 0; i < lines.size(); ++i) {
    if (lines[i].trimmed() == "[Formula]")
      b << "Formula" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[Molecular weight]")
      b << "Molecular Weight" << lines[++i].trimmed().toDouble();
    else if (lines[i].trimmed() == "[smiles]")
      b << "SMILES" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[canonical smiles]")
      b << "Canonical SMILES" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[inchi]")
      b << "InChI" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[inchikey]")
      b << "InChIKey" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[XYZ]") {
      // Read in all of the XYZ file
      QString file = lines[++i] + "\n";
      while (lines[++i].trimmed() != "[end]")
        file += lines[i] + "\n";
      b << "XYZ File" << file.toStdString();
    }
    else if (lines[i].trimmed() == "[CML]") {
      // Read in all of the CML file
      QString file = lines[++i] + "\n";
      while (lines[++i].trimmed() != "[end]")
        file += lines[i] + "\n";
      b << "CML File" << file.toStdString();
    }
  }
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::setIUPACName(int row, const QString &name)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  b << "IUPAC" << name.toStdString();
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::setImage2D(int row, const QByteArray &image)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  qDebug() << "Image data:" << image.length() << image;
  b.appendBinData("2D PNG", image.length(), mongo::BinDataGeneral, image.data());
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::addOutputFile(const QString &outputFile,
                               const QString &inputFile)
{
  qDebug() << "output" << outputFile << "input" << inputFile;
  BSONObjBuilder b;
  b.genOID();
  QFile output(outputFile);
  if (output.open(QIODevice::ReadOnly)) {
    QByteArray out = output.readAll();
    qDebug() << "GAMESS log file" << out;
    b.append("gamout", out.data());
    output.close();
  }
  else {
    qDebug() << "Failed to open output file:" << outputFile;
    return false;
  }
  if (!inputFile.isEmpty()) {
    QFile input(inputFile);
    if (input.open(QIODevice::ReadOnly)) {
      QByteArray in = input.readAll();
      b.append("gaminp", in.data());
      input.close();
    }
  }
  d->m_db.insert("chem.gamess", b.obj());
  return true;
}

bool MongoModel::results(vtkTable *table)
{
  vtkNew<vtkStringArray> CAS;
  CAS->SetName("CAS");
  CAS->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkStringArray> set;
  set->SetName("Set");
  set->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> observed;
  observed->SetName("Observed");
  observed->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> mlr;
  mlr->SetName("log(Sw) (MLR)");
  mlr->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> rf;
  rf->SetName("log(Sw) (RF)");
  rf->SetNumberOfTuples(d->m_rows);
  for (int i = 0; i < d->m_rows; ++i) {
    BSONObj *obj = d->getRecord(i);
    CAS->SetValue(i, obj->getField("CAS").str().c_str());
    set->SetValue(i, obj->getField("Set").str().c_str());
    observed->SetValue(i, obj->getField("Observed").number());
    mlr->SetValue(i, obj->getField("Predicted log Sw (MLR)").number());
    rf->SetValue(i, obj->getField("Predicted log Sw (RF)").number());
  }
  table->AddColumn(CAS.GetPointer());
  table->AddColumn(set.GetPointer());
  table->AddColumn(observed.GetPointer());
  table->AddColumn(mlr.GetPointer());
  table->AddColumn(rf.GetPointer());
  return true;
}

} // End of namespace
<commit_msg>Place molecule diagram in its own column<commit_after>/******************************************************************************

  This source file is part of the MongoModel project.

  Copyright 2011 Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

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

******************************************************************************/

#include "MongoModel.h"

#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QSize>
#include <QtCore/QDebug>
#include <QtGui/QColor>
#include <QtGui/QPixmap>

#include <vtkNew.h>
#include <vtkTable.h>
#include <vtkFloatArray.h>
#include <vtkStringArray.h>

using namespace mongo;

namespace ChemData {

class MongoModel::Private
{
public:
  Private(const QString &host) : m_namespace("chem.import"), m_rows(0)
  {
  this->connect(host);
  }

  ~Private()
  {
  }

  bool connect(const QString &host)
  {
    try {
      m_db.connect(host.toStdString());
      cout << "connected OK" << endl;
      return query();
    }
    catch (DBException &e) {
      cout << "caught " << e.what() << endl;
      return false;
    }
  }

  bool query()
  {
    if (m_db.isFailed())
      return false;
    m_rowObjects.resize(0);
    m_rows = m_db.count(m_namespace.toStdString());
    m_rowObjects.reserve(m_rows);
    BSONObj empty;
    m_cursor = m_db.query(m_namespace.toStdString(), Query().sort("Observed"));
    //, QUERY("ago" << 33));
    return true;
  }

  BSONObj * getRecord(unsigned int index)
  {
    if (index < m_rowObjects.size()) {
      return &m_rowObjects[index];
    }
    else {
      while (index >= m_rowObjects.size() && m_cursor->more())
        m_rowObjects.push_back(m_cursor->next().getOwned());
      // If there are enough objects, return the one requested
      if (index < m_rowObjects.size())
        return &m_rowObjects[index];
      else
        return 0;
    }
  }

  DBClientConnection m_db;
  auto_ptr<DBClientCursor> m_cursor;
  QString m_namespace;
  std::vector<BSONObj> m_rowObjects;
  int m_rows;

  QStringList m_fields;
  QMap<QString, QString> m_titles;
};

MongoModel::MongoModel(QObject *parent)
  : QAbstractItemModel(parent)
{
  d = new MongoModel::Private("localhost");
//  d = new MongoModel::Private("londinium.kitwarein.com");

  d->m_fields << "CAS"
              << "Set"
              << "2D PNG"
              << "Molecular Weight"
              << "Observed"
              << "Predicted log Sw (MLR)"
              << "Predicted log Sw (RF)";
  d->m_titles["2D PNG"] = "Diagram";
  d->m_titles["Observed"] = "Observed log(Sw)";
  d->m_titles["Predicted log Sw (MLR)"] = "log(Sw) (MLR)";
  d->m_titles["Predicted log Sw (RF)"] = "log(Sw) (RF)";
}

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

QModelIndex MongoModel::parent(const QModelIndex &) const
{
  return QModelIndex();
}

int MongoModel::rowCount(const QModelIndex &parent) const
{
  return d->m_rows;
}

int MongoModel::columnCount(const QModelIndex &parent) const
{
  return d->m_fields.size();
}

QVariant MongoModel::headerData(int section, Qt::Orientation orientation,
                                int role) const
{
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
    if (d->m_titles.contains(d->m_fields[section]))
      return d->m_titles[d->m_fields[section]];
    else
      return d->m_fields[section];
  }
  else if (orientation == Qt::Vertical && role == Qt::DisplayRole) {
    return QVariant(section);
  }
  return QVariant();
}

QVariant MongoModel::data(const QModelIndex &index, int role) const
{
  if (index.internalPointer()) {
    BSONObj *obj = static_cast<BSONObj *>(index.internalPointer());
    if (obj) {
      if (role == Qt::DisplayRole) {
        BSONElement e = obj->getField(d->m_fields[index.column()].toStdString());
        if (e.isNumber())
          return QVariant(e.number());
        else if (e.isNull())
          return QVariant();
        else
          return e.str().c_str();
      }
      else if (role == Qt::SizeHintRole) {
        if (d->m_fields[index.column()] == "Molecular Weight" &&
            !obj->getField("2D PNG").eoo()) {
          return QVariant(QSize(250, 250));
        }
        else {
          return QVariant(QSize(120, 20));
        }
      }
      else if (role == Qt::DecorationRole) {
        if (d->m_fields[index.column()] == "CAS") {
          if (obj->getField("InChIKey").eoo())
            return Qt::red;
          else
            return Qt::green;
        }
        else if (d->m_fields[index.column()] == "2D PNG") {
          BSONElement image = obj->getField("2D PNG");
          if (!image.eoo()) {
            int length;
            const char *data = image.binData(length);
            QByteArray inData(data, length);
            QImage in = QImage::fromData(inData, "PNG");
            QPixmap pix = QPixmap::fromImage(in);
            return QVariant(pix);
          }
        }
      }
      else if (role == Qt::ToolTipRole) {
        if (d->m_fields[index.column()] == "CAS") {
          BSONElement iupac = obj->getField("IUPAC");
          if (iupac.eoo())
            return "Unknown";
          else
            return iupac.str().c_str();
        }
        else if (d->m_fields[index.column()] == "Molecular Weight") {
          BSONElement e = obj->getField("Formula");
          if (!e.eoo()) {
            QStringList parts = QString(e.str().c_str()).split(" ",
                                                               QString::SkipEmptyParts);
            QString formula;
            for (int i = 0; i < parts.size(); i += 2) {
              formula += parts[i];
              if (parts[i+1].toInt() > 1)
                formula += "" + parts[i+1] + "";
            }
            return formula;
          }
        }
      }
    }

  }
  return QVariant();
}

bool MongoModel::setData(const QModelIndex &index, const QVariant &value,
                         int role)
{
  return false;
}

Qt::ItemFlags MongoModel::flags(const QModelIndex &index) const
{
  if (index.column() == 0)
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
  else
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

QModelIndex MongoModel::index(int row, int column,
                              const QModelIndex &parent) const
{
  if (row >= 0 && row < d->m_rows) {
    BSONObj *obj = d->getRecord(row);
    return createIndex(row, column, obj);
  }
  return QModelIndex();
}

void MongoModel::clear()
{
}

bool MongoModel::addIdentifiers(int row, const QString &identifiers)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  QStringList lines = identifiers.split("\n", QString::SkipEmptyParts);
  for (int i = 0; i < lines.size(); ++i) {
    if (lines[i].trimmed() == "[Formula]")
      b << "Formula" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[Molecular weight]")
      b << "Molecular Weight" << lines[++i].trimmed().toDouble();
    else if (lines[i].trimmed() == "[smiles]")
      b << "SMILES" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[canonical smiles]")
      b << "Canonical SMILES" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[inchi]")
      b << "InChI" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[inchikey]")
      b << "InChIKey" << lines[++i].trimmed().toStdString();
    else if (lines[i].trimmed() == "[XYZ]") {
      // Read in all of the XYZ file
      QString file = lines[++i] + "\n";
      while (lines[++i].trimmed() != "[end]")
        file += lines[i] + "\n";
      b << "XYZ File" << file.toStdString();
    }
    else if (lines[i].trimmed() == "[CML]") {
      // Read in all of the CML file
      QString file = lines[++i] + "\n";
      while (lines[++i].trimmed() != "[end]")
        file += lines[i] + "\n";
      b << "CML File" << file.toStdString();
    }
  }
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::setIUPACName(int row, const QString &name)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  b << "IUPAC" << name.toStdString();
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::setImage2D(int row, const QByteArray &image)
{
  BSONObj *obj = d->getRecord(row);
  BSONObjBuilder b;
  qDebug() << "Image data:" << image.length() << image;
  b.appendBinData("2D PNG", image.length(), mongo::BinDataGeneral, image.data());
  BSONObjBuilder updateSet;
  updateSet << "$set" <m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());
  d->query();
}

bool MongoModel::addOutputFile(const QString &outputFile,
                               const QString &inputFile)
{
  qDebug() << "output" << outputFile << "input" << inputFile;
  BSONObjBuilder b;
  b.genOID();
  QFile output(outputFile);
  if (output.open(QIODevice::ReadOnly)) {
    QByteArray out = output.readAll();
    qDebug() << "GAMESS log file" << out;
    b.append("gamout", out.data());
    output.close();
  }
  else {
    qDebug() << "Failed to open output file:" << outputFile;
    return false;
  }
  if (!inputFile.isEmpty()) {
    QFile input(inputFile);
    if (input.open(QIODevice::ReadOnly)) {
      QByteArray in = input.readAll();
      b.append("gaminp", in.data());
      input.close();
    }
  }
  d->m_db.insert("chem.gamess", b.obj());
  return true;
}

bool MongoModel::results(vtkTable *table)
{
  vtkNew<vtkStringArray> CAS;
  CAS->SetName("CAS");
  CAS->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkStringArray> set;
  set->SetName("Set");
  set->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> observed;
  observed->SetName("Observed");
  observed->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> mlr;
  mlr->SetName("log(Sw) (MLR)");
  mlr->SetNumberOfTuples(d->m_rows);
  vtkNew<vtkFloatArray> rf;
  rf->SetName("log(Sw) (RF)");
  rf->SetNumberOfTuples(d->m_rows);
  for (int i = 0; i < d->m_rows; ++i) {
    BSONObj *obj = d->getRecord(i);
    CAS->SetValue(i, obj->getField("CAS").str().c_str());
    set->SetValue(i, obj->getField("Set").str().c_str());
    observed->SetValue(i, obj->getField("Observed").number());
    mlr->SetValue(i, obj->getField("Predicted log Sw (MLR)").number());
    rf->SetValue(i, obj->getField("Predicted log Sw (RF)").number());
  }
  table->AddColumn(CAS.GetPointer());
  table->AddColumn(set.GetPointer());
  table->AddColumn(observed.GetPointer());
  table->AddColumn(mlr.GetPointer());
  table->AddColumn(rf.GetPointer());
  return true;
}

} // End of namespace
<|endoftext|>


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

#include <string>

namespace ghost
{
namespace core
{
namespace carryingSystem
{

/** Factory of At Command used to communicate with the Arduino */
class CarryingSystemAtCommandFactory
{

public:

    /** Ackable Commands */
    enum AtCommandReceivable {
        LIFTED = 666,
        DROPED,
        ACK
    };

    /** Generate the AT Command allowing the carrying system to lift the packet */
    static const std::string liftCommand();

    /** Generate the AT Command allowing the carrying system to drop the packet */
    static const std::string dropCommand();

    /** Test if a received AT Commands try to ack an other one */
    static bool isAckCommandOf(const std::string& atCmd, const std::string& commandType);

private:

    /** At Command parts */
    static const std::string mAtCommandPrefix;
    static const std::string mAtCommandAssignement;
    static const std::string mAtCommandSuffix;

    /** Available At Commands */
    static const std::string mAtCommandDropHeader;
    static const std::string mAtCommandLiftHeader;
    static const std::string mAtCommandAckHeader;

    /** General method which allows to create an AT Command without arguments. */
    static const std::string commandFactory(const std::string& atCmdHeader);

    /** General method which allows to create an AT Command with one argument. */
    // const std::string commandFactory(const std::string& atCmdHeader, const std::string& atCmdParameter);

    static const std::string determineParameter(const std::string& atCmd);
    static const std::string determineHeader(const std::string& atCmd);

};

} /* carryingSystem namespace */
} /* core namespace  */
} /* ghost namespace */
<commit_msg>[Core] Add missing comments in CarryingSystemAtCommandFactory header<commit_after>/*
 * Copyright 2014 Jules Cléro
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#pragma once

#include <string>

namespace ghost
{
namespace core
{
namespace carryingSystem
{

/** Factory of At Command used to communicate with the Arduino */
class CarryingSystemAtCommandFactory
{

public:

    /** Generate the AT Command allowing the carrying system to lift the packet */
    static const std::string liftCommand();

    /** Generate the AT Command allowing the carrying system to drop the packet */
    static const std::string dropCommand();

    /** Test if a received AT Commands try to ack an other one */
    static bool isAckCommandOf(const std::string& atCmd, const std::string& commandType);

private:

    /** At Command parts */
    static const std::string mAtCommandPrefix;
    static const std::string mAtCommandAssignement;
    static const std::string mAtCommandSuffix;

    /** Available At Commands */
    static const std::string mAtCommandDropHeader;
    static const std::string mAtCommandLiftHeader;
    static const std::string mAtCommandAckHeader;

    /** General method which allows to create an AT Command without arguments. */
    static const std::string commandFactory(const std::string& atCmdHeader);

    static const std::string determineParameter(const std::string& atCmd);
    static const std::string determineHeader(const std::string& atCmd);

};

} /* carryingSystem namespace */
} /* core namespace  */
} /* ghost namespace */
<|endoftext|>


<commit_before>/***************************************************************************//**
 * rendergl.hpp
 * OpenGL rendering calls
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Shane Blackett <shane@blackett.co.nz>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#if !defined (RENDERGL_HPP)
#define RENDERGL_HPP

#include "graphics/graphics_object.h"
#include "graphics/render.hpp"

/***************************************************************************//**
 * Common code for all OpenGL based implementations.
 */
class Render_graphics_opengl : public Render_graphics_compile_members
{
public:
	/** Specifies that we should be rendering only objects marked as fast
	 * changing.
	 */
	int fast_changing;
	/** Indicates that we are rendering specifically to pick objects.
	 * Requires the ndc transformation to be different as the viewport is the picking window.
	 */
	int picking;
	Graphics_buffer *graphics_buffer;

	int allow_texture_tiling; /** Flag controls whether when compiling a large texture
	                              it can be split into multiple texture tiles */
	Texture_tiling *texture_tiling;  /** If a given texture is compiled into tiles
													 then this field is filled in and expected to
													 be used when compiling graphics that use that material. */

public:
	Render_graphics_opengl(Graphics_buffer *graphics_buffer) :
		graphics_buffer(graphics_buffer)
	{
		fast_changing = 0;
		picking = 0;
		texture_tiling = NULL;
	}

	/***************************************************************************//**
	 * @see Render_graphics::Scene_compile
	 */
	virtual int Scene_compile(Scene *scene);

	/***************************************************************************//**
	 * @see Render_graphics::Graphics_object_compile
	 */
	virtual int Graphics_object_compile(GT_object *graphics_object);

	/***************************************************************************//**
	 * @see Render_graphics::Material_compile
	 */
	virtual int Material_compile(Graphical_material *material);

	/**************************************************************************//**
	 * Temporarily override the viewing coordinates so that the current opengl
	 * display is in normalised device coordinates (aligned with the viewport).
	 */
	virtual int Start_ndc_coordinates() = 0;

	/**************************************************************************//**
	 * Reverse the changes made by Start_ndc_coordinates and resume normal
	 * 3D rendering.
	 */
	virtual int End_ndc_coordinates() = 0;

}; /* class Render_graphics_opengl */

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * glBegin/glEnd calls to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_glbeginend_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses glBegin/glEnd calls when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_glbeginend_display_list_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * client vertex arrays to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses client vertex arrays when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_display_list_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * vertex buffer objects to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses vertex buffer objects when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_display_list_renderer(
	Graphics_buffer *graphics_buffer);

#endif /* !defined (RENDERGL_HPP) */
<commit_msg>allow_texture_tiling field should be initialised. ASSIGNED - bug 1401: Use vertex arrays with OpenGL  https://tracker.physiomeproject.org/show_bug.cgi?id=1401<commit_after>/***************************************************************************//**
 * rendergl.hpp
 * OpenGL rendering calls
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Shane Blackett <shane@blackett.co.nz>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#if !defined (RENDERGL_HPP)
#define RENDERGL_HPP

#include "graphics/graphics_object.h"
#include "graphics/render.hpp"

/***************************************************************************//**
 * Common code for all OpenGL based implementations.
 */
class Render_graphics_opengl : public Render_graphics_compile_members
{
public:
	/** Specifies that we should be rendering only objects marked as fast
	 * changing.
	 */
	int fast_changing;
	/** Indicates that we are rendering specifically to pick objects.
	 * Requires the ndc transformation to be different as the viewport is the picking window.
	 */
	int picking;
	Graphics_buffer *graphics_buffer;

	int allow_texture_tiling; /** Flag controls whether when compiling a large texture
	                              it can be split into multiple texture tiles */
	Texture_tiling *texture_tiling;  /** If a given texture is compiled into tiles
													 then this field is filled in and expected to
													 be used when compiling graphics that use that material. */

public:
	Render_graphics_opengl(Graphics_buffer *graphics_buffer) :
		graphics_buffer(graphics_buffer)
	{
		fast_changing = 0;
		picking = 0;
		allow_texture_tiling = 0;
		texture_tiling = NULL;
	}

	/***************************************************************************//**
	 * @see Render_graphics::Scene_compile
	 */
	virtual int Scene_compile(Scene *scene);

	/***************************************************************************//**
	 * @see Render_graphics::Graphics_object_compile
	 */
	virtual int Graphics_object_compile(GT_object *graphics_object);

	/***************************************************************************//**
	 * @see Render_graphics::Material_compile
	 */
	virtual int Material_compile(Graphical_material *material);

	/**************************************************************************//**
	 * Temporarily override the viewing coordinates so that the current opengl
	 * display is in normalised device coordinates (aligned with the viewport).
	 */
	virtual int Start_ndc_coordinates() = 0;

	/**************************************************************************//**
	 * Reverse the changes made by Start_ndc_coordinates and resume normal
	 * 3D rendering.
	 */
	virtual int End_ndc_coordinates() = 0;

}; /* class Render_graphics_opengl */

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * glBegin/glEnd calls to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_glbeginend_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses glBegin/glEnd calls when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_glbeginend_display_list_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * client vertex arrays to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses client vertex arrays when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_display_list_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that uses immediate mode
 * vertex buffer objects to render primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_renderer(
	Graphics_buffer *graphics_buffer);

/***************************************************************************//**
 * Factory function to create a renderer that compiles objects into display lists
 * for rendering and uses vertex buffer objects when compiling primitives.
 */
Render_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_display_list_renderer(
	Graphics_buffer *graphics_buffer);

#endif /* !defined (RENDERGL_HPP) */
<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "host/host_settings.h"

#include "base/logging.h"
#include "base/xml_settings.h"
#include "build/build_config.h"
#include "crypto/random.h"
#include "network/srp_user.h"

namespace aspia {

HostSettings::HostSettings()
    : settings_(XmlSettings::registerFormat(),
                QSettings::SystemScope,
                QLatin1String("aspia"),
                QLatin1String("host"))
{
    // Nothing
}

HostSettings::~HostSettings() = default;

QString HostSettings::filePath() const
{
    return settings_.fileName();
}

bool HostSettings::isWritable() const
{
    return settings_.isWritable();
}

QString HostSettings::locale() const
{
    return settings_.value(QLatin1String("Locale"), DEFAULT_LOCALE).toString();
}

void HostSettings::setLocale(const QString& locale)
{
    settings_.setValue(QLatin1String("Locale"), locale);
}

uint16_t HostSettings::tcpPort() const
{
    return settings_.value(QLatin1String("TcpPort"), DEFAULT_HOST_TCP_PORT).toUInt();
}

void HostSettings::setTcpPort(uint16_t port)
{
    settings_.setValue(QLatin1String("TcpPort"), port);
}

bool HostSettings::addFirewallRule() const
{
    return settings_.value(QLatin1String("AddFirewallRule"), true).toBool();
}

void HostSettings::setAddFirewallRule(bool value)
{
    settings_.setValue(QLatin1String("AddFirewallRule"), value);
}

SrpUserList HostSettings::userList() const
{
    SrpUserList users;

    users.seed_key = settings_.value(QLatin1String("SeedKey")).toByteArray();
    if (users.seed_key.isEmpty())
        users.seed_key = Random::generateBuffer(64);

    int size = settings_.beginReadArray(QLatin1String("Users"));
    for (int i = 0; i < size; ++i)
    {
        settings_.setArrayIndex(i);

        SrpUser user;
        user.name      = settings_.value(QLatin1String("Name")).toString();
        user.salt      = QByteArray::fromBase64(settings_.value(QLatin1String("Salt")).toByteArray());
        user.verifier  = QByteArray::fromBase64(settings_.value(QLatin1String("Verifier")).toByteArray());
        user.number    = QByteArray::fromBase64(settings_.value(QLatin1String("Number")).toByteArray());
        user.generator = QByteArray::fromBase64(settings_.value(QLatin1String("Generator")).toByteArray());
        user.sessions  = settings_.value(QLatin1String("Sessions")).toUInt();
        user.flags     = settings_.value(QLatin1String("Flags")).toUInt();

        CHECK(!user.name.isEmpty());
        CHECK(!user.salt.isEmpty());
        CHECK(!user.verifier.isEmpty());
        CHECK(!user.number.isEmpty());
        CHECK(!user.generator.isEmpty());

        users.list.append(user);
    }
    settings_.endArray();

    return users;
}

void HostSettings::setUserList(const SrpUserList& users)
{
    // Clear the old list of users.
    settings_.remove(QLatin1String("Users"));

    settings_.setValue(QLatin1String("SeedKey"), users.seed_key.toBase64());

    settings_.beginWriteArray(QLatin1String("Users"));
    for (int i = 0; i < users.list.size(); ++i)
    {
        settings_.setArrayIndex(i);

        const SrpUser& user = users.list.at(i);

        settings_.setValue(QLatin1String("Name"), user.name);
        settings_.setValue(QLatin1String("Salt"), user.salt.toBase64());
        settings_.setValue(QLatin1String("Verifier"), user.verifier.toBase64());
        settings_.setValue(QLatin1String("Number"), user.number.toBase64());
        settings_.setValue(QLatin1String("Generator"), user.generator.toBase64());
        settings_.setValue(QLatin1String("Sessions"), user.sessions);
        settings_.setValue(QLatin1String("Flags"), user.flags);
    }
    settings_.endArray();
}

QString HostSettings::updateServer() const
{
    return settings_.value(QLatin1String("UpdateServer"), DEFAULT_UPDATE_SERVER).toString();
}

void HostSettings::setUpdateServer(const QString& server)
{
    settings_.setValue(QLatin1String("UpdateServer"), server);
}

bool HostSettings::remoteUpdate() const
{
    return settings_.value(QLatin1String("RemoteUpdate"), true).toBool();
}

void HostSettings::setRemoteUpdate(bool allow)
{
    settings_.setValue(QLatin1String("RemoteUpdate"), allow);
}

} // namespace aspia
<commit_msg>- Converting to base64 is no longer necessary.<commit_after>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "host/host_settings.h"

#include "base/logging.h"
#include "base/xml_settings.h"
#include "build/build_config.h"
#include "crypto/random.h"
#include "network/srp_user.h"

namespace aspia {

HostSettings::HostSettings()
    : settings_(XmlSettings::registerFormat(),
                QSettings::SystemScope,
                QLatin1String("aspia"),
                QLatin1String("host"))
{
    // Nothing
}

HostSettings::~HostSettings() = default;

QString HostSettings::filePath() const
{
    return settings_.fileName();
}

bool HostSettings::isWritable() const
{
    return settings_.isWritable();
}

QString HostSettings::locale() const
{
    return settings_.value(QLatin1String("Locale"), DEFAULT_LOCALE).toString();
}

void HostSettings::setLocale(const QString& locale)
{
    settings_.setValue(QLatin1String("Locale"), locale);
}

uint16_t HostSettings::tcpPort() const
{
    return settings_.value(QLatin1String("TcpPort"), DEFAULT_HOST_TCP_PORT).toUInt();
}

void HostSettings::setTcpPort(uint16_t port)
{
    settings_.setValue(QLatin1String("TcpPort"), port);
}

bool HostSettings::addFirewallRule() const
{
    return settings_.value(QLatin1String("AddFirewallRule"), true).toBool();
}

void HostSettings::setAddFirewallRule(bool value)
{
    settings_.setValue(QLatin1String("AddFirewallRule"), value);
}

SrpUserList HostSettings::userList() const
{
    SrpUserList users;

    users.seed_key = settings_.value(QLatin1String("SeedKey")).toByteArray();
    if (users.seed_key.isEmpty())
        users.seed_key = Random::generateBuffer(64);

    int size = settings_.beginReadArray(QLatin1String("Users"));
    for (int i = 0; i < size; ++i)
    {
        settings_.setArrayIndex(i);

        SrpUser user;
        user.name      = settings_.value(QLatin1String("Name")).toString();
        user.salt      = settings_.value(QLatin1String("Salt")).toByteArray();
        user.verifier  = settings_.value(QLatin1String("Verifier")).toByteArray();
        user.number    = settings_.value(QLatin1String("Number")).toByteArray();
        user.generator = settings_.value(QLatin1String("Generator")).toByteArray();
        user.sessions  = settings_.value(QLatin1String("Sessions")).toUInt();
        user.flags     = settings_.value(QLatin1String("Flags")).toUInt();

        CHECK(!user.name.isEmpty());
        CHECK(!user.salt.isEmpty());
        CHECK(!user.verifier.isEmpty());
        CHECK(!user.number.isEmpty());
        CHECK(!user.generator.isEmpty());

        users.list.append(user);
    }
    settings_.endArray();

    return users;
}

void HostSettings::setUserList(const SrpUserList& users)
{
    // Clear the old list of users.
    settings_.remove(QLatin1String("Users"));

    settings_.setValue(QLatin1String("SeedKey"), users.seed_key);

    settings_.beginWriteArray(QLatin1String("Users"));
    for (int i = 0; i < users.list.size(); ++i)
    {
        settings_.setArrayIndex(i);

        const SrpUser& user = users.list.at(i);

        settings_.setValue(QLatin1String("Name"), user.name);
        settings_.setValue(QLatin1String("Salt"), user.salt);
        settings_.setValue(QLatin1String("Verifier"), user.verifier);
        settings_.setValue(QLatin1String("Number"), user.number);
        settings_.setValue(QLatin1String("Generator"), user.generator);
        settings_.setValue(QLatin1String("Sessions"), user.sessions);
        settings_.setValue(QLatin1String("Flags"), user.flags);
    }
    settings_.endArray();
}

QString HostSettings::updateServer() const
{
    return settings_.value(QLatin1String("UpdateServer"), DEFAULT_UPDATE_SERVER).toString();
}

void HostSettings::setUpdateServer(const QString& server)
{
    settings_.setValue(QLatin1String("UpdateServer"), server);
}

bool HostSettings::remoteUpdate() const
{
    return settings_.value(QLatin1String("RemoteUpdate"), true).toBool();
}

void HostSettings::setRemoteUpdate(bool allow)
{
    settings_.setValue(QLatin1String("RemoteUpdate"), allow);
}

} // namespace aspia
<|endoftext|>


<commit_before>// Copyright 2013 Mirus Project

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

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

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

//
// paging.cpp - interface for paging and related structures
//

#include <mem/paging.hpp>
#include <mem/kheap.hpp>

namespace mirus
{
    namespace mem
    {
        page_directory_t* kernel_directory = 0;
        page_directory_t* current_directory = 0;

        uint32_t* frames;
        uint32_t nframes;

        extern uint32_t placement_address;

        #define INDEX_FROM_BIT(a) (a / 0x20)
        #define OFFSET_FROM_BIT(a) (a % 0x20)

        static void set_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            frames[index] |= (0x1 << offset);
        }

        static void clear_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            frames[index] &= ~(0x1 << offset);
        }

        static uint32_t test_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            return (frames[index] & (0x1 << offset));
        }

        static uint32_t first_frame()
        {
            for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)
            {
                if (frames[i] != 0xFFFFFFFF)
                {
                    for (uint32_t j = 0; j < 32; j++)
                    {
                        uint32_t test = 0x1 << j;

                        if (!(frames[i]&test))
                            return i * 0x20 +j;
                    }
                }
            }
        }

        void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)
        {
            if (page->frame != 0)
            {
                page->present = 1;
                page->rw = (is_writeable == 1) ? 1:0;
                page->user = (is_kernel == 1) ? 0:1;
                return;
            }
            else
            {
                uint32_t index = first_frame();
                set_frame(index * 0x1000);
                page->present = 1;
                page->rw = (is_writeable == 1) ? 1 : 0;
                page->user = (is_kernel == 1)  ? 0 : 1;
                page->frame = index;
            }
        }

        void free_frame(page_t* page)
        {
            uint32_t frame;

            if (!(frame = page->frame))
                return;
            else
            {
                clear_frame(frame * 0x1000);
                page->frame = 0x0;
            }
        }

        void paging::init(uint32_t memsize)
        {
            nframes = memsize / 4;
            frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes * 8));
            memset(frames, 0, INDEX_FROM_BIT(nframes));

            kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));
            current_directory = kernel_directory;

            for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000)
                alloc_frame(paging::get_page(i, 1, kernel_directory), 1, 0);

            cpu::irq::install_handler(14, paging::page_fault);
            kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;
            paging::switch_page_directory(kernel_directory);
        }

        void paging::switch_page_directory(page_directory_t* dir)
        {
            current_directory = dir;

            asm volatile("mov %0, %%cr3":: "r"(current_directory->physical_address));
            uint32_t cr0;
            asm volatile("mov %%cr0, %0": "=r"(cr0));
            cr0 |= 0x80000000;
            asm volatile("mov %0, %%cr0":: "r"(cr0));
        }

        page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)
        {
            address /= 0x1000;
            uint32_t table_index = address / 1024;

            if (dir->tables[table_index])
                return &dir->tables[table_index]->pages[address % 1024];
            else if (make)
            {
                uint32_t temp;

                dir->tables[table_index] =
                    (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);
                dir->tables_physical[table_index] = temp | 0x7;
                return &dir->tables[table_index]->pages[address % 1024];
            }
            else
                return 0;
        }

        void paging::page_fault(cpu::regs* regs)
        {
            // A page fault has occurred.
            // The faulting address is stored in the CR2 register.
            uint32_t faulting_address;
            asm volatile("mov %%cr2, %0" : "=r" (faulting_address));

            // The error code gives us details of what happened.
            int present   = !(regs->err_code & 0x1); // Page not present
            int rw = regs->err_code & 0x2;           // Write operation?
            int us = regs->err_code & 0x4;           // Processor was in user-mode?
            int reserved = regs->err_code & 0x8;     // Overwritten CPU-reserved bits of page entry?
            int id = regs->err_code & 0x10;          // Caused by an instruction fetch?

            // Output an error message.
            kprintf("Page fault! ( ");
            if (present) {kprintf("present ");}
            if (rw) {kprintf("read-only ");}
            if (us) {kprintf("user-mode ");}
            if (reserved) {kprintf("reserved ");}
            kprintf(") at %x\n", faulting_address);
        }
    } // !namespace
} // !namespace<commit_msg>It still dies<commit_after>// Copyright 2013 Mirus Project

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

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

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

//
// paging.cpp - interface for paging and related structures
//

#include <mem/paging.hpp>
#include <mem/kheap.hpp>

namespace mirus
{
    namespace mem
    {
        page_directory_t* kernel_directory = 0;
        page_directory_t* current_directory = 0;

        uint32_t* frames;
        uint32_t nframes;

        extern uint32_t placement_address;

        #define INDEX_FROM_BIT(a) (a / 0x20)
        #define OFFSET_FROM_BIT(a) (a % 0x20)

        static void set_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            frames[index] |= (0x1 << offset);
        }

        static void clear_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            frames[index] &= ~(0x1 << offset);
        }

        static uint32_t test_frame(uint32_t frame_addr)
        {
            uint32_t frame = frame_addr / 0x1000;
            uint32_t index = INDEX_FROM_BIT(frame);
            uint32_t offset = OFFSET_FROM_BIT(frame);

            return (frames[index] & (0x1 << offset));
        }

        static uint32_t first_frame()
        {
            for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)
            {
                if (frames[i] != 0xFFFFFFFF)
                {
                    for (uint32_t j = 0; j < 32; j++)
                    {
                        uint32_t test = 0x1 << j;

                        if (!(frames[i]&test))
                            return i * 0x20 +j;
                    }
                }
            }
        }

        void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)
        {
            if (page->frame)
                return;
            else
            {
                uint32_t index = first_frame();
                set_frame(index * 0x1000);
                page->present = 1;
                page->rw = (is_writeable == 1) ? 1 : 0;
                page->user = (is_kernel == 1)  ? 0 : 1;
                page->frame = index;
            }
        }

        void free_frame(page_t* page)
        {
            uint32_t frame;

            if (!(frame = page->frame))
                return;
            else
            {
                clear_frame(frame);
                page->frame = 0x0;
            }
        }

        void paging::init(uint32_t memsize)
        {
            uint32_t mem_end_page = memsize;
            nframes = mem_end_page / 0x1000;
            frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes));
            memset(frames, 0, INDEX_FROM_BIT(nframes));

            kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));
            memset((uint8_t*)kernel_directory, 0, sizeof(page_directory_t));
            kernel_directory->physical_address = (uint32_t)kernel_directory->tables_physical;

            current_directory = kernel_directory;

            for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000)
                alloc_frame(paging::get_page(i, 1, kernel_directory), 0, 0);

            paging::switch_page_directory(kernel_directory);

            cpu::irq::install_handler(14, paging::page_fault);
            kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;
            paging::switch_page_directory(current_directory);
        }

        void paging::switch_page_directory(page_directory_t* dir)
        {
            current_directory = dir;

            asm volatile("mov %0, %%cr3":: "r"(current_directory->physical_address));
            uint32_t cr0;
            asm volatile("mov %%cr0, %0": "=r"(cr0));
            cr0 |= 0x80000000;
            asm volatile("mov %0, %%cr0":: "r"(cr0));
        }

        page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)
        {
            address /= 0x1000;
            uint32_t table_index = address / 1024;

            if (dir->tables[table_index])
                return &dir->tables[table_index]->pages[address % 1024];
            else if (make)
            {
                uint32_t temp;

                dir->tables[table_index] =
                    (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);
                dir->tables_physical[table_index] = temp | 0x7;
                return &dir->tables[table_index]->pages[address % 1024];
            }
            else
                return 0;
        }

        void paging::page_fault(cpu::regs* regs)
        {
            // A page fault has occurred.
            // The faulting address is stored in the CR2 register.
            uint32_t faulting_address;
            asm volatile("mov %%cr2, %0" : "=r" (faulting_address));

            // The error code gives us details of what happened.
            int present   = !(regs->err_code & 0x1); // Page not present
            int rw = regs->err_code & 0x2;           // Write operation?
            int us = regs->err_code & 0x4;           // Processor was in user-mode?
            int reserved = regs->err_code & 0x8;     // Overwritten CPU-reserved bits of page entry?
            int id = regs->err_code & 0x10;          // Caused by an instruction fetch?

            // Output an error message.
            kprintf("Page fault! ( ");
            if (present) {kprintf("present ");}
            if (rw) {kprintf("read-only ");}
            if (us) {kprintf("user-mode ");}
            if (reserved) {kprintf("reserved ");}
            kprintf(") at %x\n", faulting_address);
        }
    } // !namespace
} // !namespace<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "conf.h"
#include "type/type.pb.h"
#include <google/protobuf/descriptor.h>

#include <boost/thread.hpp>
#include <functional>
#include <string>
#include <iostream>
#include "utils/init.h"
#include "kraken_zmq.h"
#include "utils/zmq.h"
#include "utils/functions.h" //navitia::absolute_path function

static void show_usage(const std::string& name)
{
    std::cerr << "Usage:\n"
              << "\t" << name << " --help\t\tShow this message.\n"
              << "\t" << name << " [config_file]\tSpecify the path of the configuration file "
              << "(default: kraken.ini in the current path)"
              << std::endl;
}

int main(int argn, char** argv){
    navitia::init_app();
    navitia::kraken::Configuration conf;

    std::string::size_type posSlash = std::string(argv[0]).find_last_of( "\\/" );
    std::string application = std::string(argv[0]).substr(posSlash+1);
    std::string path = navitia::absolute_path();
    if (path.empty()) {
        return 1;
    }
    std::string conf_file;
    if(argn > 1){
        std::string arg = argv[1];
        if(arg == "-h" || arg == "--help"){
            show_usage(argv[0]);
            return 0;
        }else{
            // The first argument is the path to the configuration file
            conf_file = arg;
        }
    }else{
        conf_file = path + application + ".ini";
    }
    conf.load(conf_file);
    auto log_level = conf.log_level();
    auto log_format = conf.log_format();
    if(log_level && log_format){
        init_logger(*log_level, *log_format);
    }else{
        init_logger(conf_file);
    }

    DataManager<navitia::type::Data> data_manager;

    auto logger = log4cplus::Logger::getInstance("startup");
    LOG4CPLUS_INFO(logger, "starting kraken: " << navitia::config::project_version);
    boost::thread_group threads;
    // Prepare our context and sockets
    zmq::context_t context(1);
    // Catch startup exceptions; without this, startup errors are on stdout
    std::string zmq_socket = conf.zmq_socket_path();
    //TODO: try/catch
    LoadBalancer lb(context);

    const navitia::Metrics metrics(conf.metrics_binding(), conf.instance_name());

    threads.create_thread(navitia::MaintenanceWorker(data_manager, conf));

    int nb_threads = conf.nb_threads();
    // Launch pool of worker threads
    LOG4CPLUS_INFO(logger, "starting workers threads");
    for(int thread_nbr = 0; thread_nbr < nb_threads; ++thread_nbr) {
        threads.create_thread(std::bind(&doWork,
                                        std::ref(context),
                                        std::ref(data_manager),
                                        conf,
                                        std::ref(metrics)));
    }

    //Data have been loaded, we can now accept connections
    try{
        lb.bind(zmq_socket, "inproc://workers");
    }catch(zmq::error_t& e){
        LOG4CPLUS_ERROR(logger, "zmq::socket_t::bind() failure: " << e.what());
        return 1;
    }

    // Connect worker threads to client threads via a queue
    do{
        try{
            lb.run();
        }catch(const zmq::error_t&){}//lors d'un SIGHUP on restore la queue
    }while(true);
}

<commit_msg>Fix crash artemis<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "conf.h"
#include "type/type.pb.h"
#include <google/protobuf/descriptor.h>

#include <boost/thread.hpp>
#include <functional>
#include <string>
#include <iostream>
#include "utils/init.h"
#include "kraken_zmq.h"
#include "utils/zmq.h"
#include "utils/functions.h" //navitia::absolute_path function

static void show_usage(const std::string& name)
{
    std::cerr << "Usage:\n"
              << "\t" << name << " --help\t\tShow this message.\n"
              << "\t" << name << " [config_file]\tSpecify the path of the configuration file "
              << "(default: kraken.ini in the current path)"
              << std::endl;
}

int main(int argn, char** argv){
    navitia::init_app();
    navitia::kraken::Configuration conf;

    std::string::size_type posSlash = std::string(argv[0]).find_last_of( "\\/" );
    std::string application = std::string(argv[0]).substr(posSlash+1);
    std::string path = navitia::absolute_path();
    if (path.empty()) {
        return 1;
    }
    std::string conf_file;
    if(argn > 1){
        std::string arg = argv[1];
        if(arg == "-h" || arg == "--help"){
            show_usage(argv[0]);
            return 0;
        }else{
            // The first argument is the path to the configuration file
            conf_file = arg;
        }
    }else{
        conf_file = path + application + ".ini";
    }
    conf.load(conf_file);
    auto log_level = conf.log_level();
    auto log_format = conf.log_format();
    if(log_level && log_format){
        init_logger(*log_level, *log_format);
    }else{
        init_logger(conf_file);
    }

    DataManager<navitia::type::Data> data_manager;

    auto logger = log4cplus::Logger::getInstance("startup");
    LOG4CPLUS_INFO(logger, "starting kraken: " << navitia::config::project_version);
    boost::thread_group threads;
    // Prepare our context and sockets
    zmq::context_t context(1);
    // Catch startup exceptions; without this, startup errors are on stdout
    std::string zmq_socket = conf.zmq_socket_path();
    //TODO: try/catch
    LoadBalancer lb(context);

    const navitia::Metrics metrics(conf.metrics_binding(), conf.instance_name());

    threads.create_thread(navitia::MaintenanceWorker(data_manager, conf));
    //
    //Data have been loaded, we can now accept connections
    try{
        lb.bind(zmq_socket, "inproc://workers");
    }catch(zmq::error_t& e){
        LOG4CPLUS_ERROR(logger, "zmq::socket_t::bind() failure: " << e.what());
        return 1;
    }

    int nb_threads = conf.nb_threads();
    // Launch pool of worker threads
    LOG4CPLUS_INFO(logger, "starting workers threads");
    for(int thread_nbr = 0; thread_nbr < nb_threads; ++thread_nbr) {
        threads.create_thread(std::bind(&doWork,
                                        std::ref(context),
                                        std::ref(data_manager),
                                        conf,
                                        std::ref(metrics)));
    }

    // Connect worker threads to client threads via a queue
    do{
        try{
            lb.run();
        }catch(const zmq::error_t&){}//lors d'un SIGHUP on restore la queue
    }while(true);
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 1999-2007 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */
#ifdef HAVE_CVS_IDENT
#ident "$Id: PWire.cc,v 1.14 2007/05/24 04:07:11 steve Exp $"
#endif

# include "config.h"
# include  "PWire.h"
# include  "PExpr.h"
# include  <assert.h>

PWire::PWire(const pform_name_t&n,
	     NetNet::Type t,
	     NetNet::PortType pt,
	     ivl_variable_type_t dt)
: hname_(n), type_(t), port_type_(pt), data_type_(dt),
  signed_(false), isint_(false), port_set_(false), net_set_(false),
  port_msb_(0), port_lsb_(0), net_msb_(0), net_lsb_(0), error_cnt_(0),
  lidx_(0), ridx_(0)
{
      if (t == NetNet::INTEGER) {
	    type_ = NetNet::REG;
	    signed_ = true;
	    isint_ = true;
      }
}

NetNet::Type PWire::get_wire_type() const
{
      return type_;
}

const pform_name_t& PWire::path() const
{
      return hname_;
}

bool PWire::set_wire_type(NetNet::Type t)
{
      assert(t != NetNet::IMPLICIT);

      switch (type_) {
	  case NetNet::IMPLICIT:
	    type_ = t;
	    return true;
	  case NetNet::IMPLICIT_REG:
	    if (t == NetNet::REG) { type_ = t; return true; }
	    return false;
	  case NetNet::REG:
	    if (t == NetNet::INTEGER) {
		  isint_ = true;
		  return true;
	    }
	    if (t == NetNet::REG) return true;
	    return false;
	  default:
	    if (type_ != t)
		  return false;
	    else
		  return true;
      }
}

NetNet::PortType PWire::get_port_type() const
{
      return port_type_;
}

bool PWire::set_port_type(NetNet::PortType pt)
{
      assert(pt != NetNet::NOT_A_PORT);
      assert(pt != NetNet::PIMPLICIT);

      switch (port_type_) {
	  case NetNet::PIMPLICIT:
	    port_type_ = pt;
	    return true;

	  case NetNet::NOT_A_PORT:
	    return false;

	  default:
	    if (port_type_ != pt)
		  return false;
	    else
		  return true;
      }
}

bool PWire::set_data_type(ivl_variable_type_t dt)
{
      if (data_type_ != IVL_VT_NO_TYPE)
	    if (data_type_ != dt)
		  return false;
	    else
		  return true;

      assert(data_type_ == IVL_VT_NO_TYPE);
      data_type_ = dt;
      return true;
}

void PWire::set_signed(bool flag)
{
      signed_ = flag;
}

bool PWire::get_signed() const
{
      return signed_;
}

bool PWire::get_isint() const
{
      return isint_;
}

/*
 * Since implicitly defined list of port declarations are no longer
 * considered fully defined we no longer need this routine to force
 * them to be fully defined.
 *
void PWire::set_net_range()
{
      net_msb_ = port_msb_;
      net_lsb_ = port_lsb_;
      net_set_ = true;
}
*/

void PWire::set_range(PExpr*m, PExpr*l, PWSRType type)
{
      switch (type) {
	  case SR_PORT:
	    if (port_set_) {
		  cerr << get_line() << ": error: Port ``" << hname_
		       << "'' has already been declared a port." << endl;
		  error_cnt_ += 1;
	    } else {
		  port_msb_ = m;
		  port_lsb_ = l;
		  port_set_ = true;
	    }
	    return;

	  case SR_NET:
	    if (net_set_) {
		  cerr << get_line() << ": error: Net ``" << hname_
		       << "'' has already been declared." << endl;
		  error_cnt_ += 1;
	    } else {
		  net_msb_ = m;
		  net_lsb_ = l;
		  net_set_ = true;
	    }
	    return;

	  case SR_BOTH:
	    if (port_set_ || net_set_) {
		  if (port_set_) {
		        cerr << get_line() << ": error: Port ``" << hname_
		             << "'' has already been declared a port." << endl;
		        error_cnt_ += 1;
		  }
		  if (net_set_) {
		        cerr << get_line() << ": error: Net ``" << hname_
		             << "'' has already been declared." << endl;
		        error_cnt_ += 1;
		  }
	    } else {
		  port_msb_ = m;
		  port_lsb_ = l;
		  port_set_ = true;
		  net_msb_ = m;
		  net_lsb_ = l;
		  net_set_ = true;
	    }
	    return;
      }
}

void PWire::set_memory_idx(PExpr*ldx, PExpr*rdx)
{
      assert(lidx_ == 0);
      assert(ridx_ == 0);
      lidx_ = ldx;
      ridx_ = rdx;
}

<commit_msg>Error message for duplicate declare of arrays.<commit_after>/*
 * Copyright (c) 1999-2007 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */
#ifdef HAVE_CVS_IDENT
#ident "$Id: PWire.cc,v 1.14 2007/05/24 04:07:11 steve Exp $"
#endif

# include "config.h"
# include  "PWire.h"
# include  "PExpr.h"
# include  <assert.h>

PWire::PWire(const pform_name_t&n,
	     NetNet::Type t,
	     NetNet::PortType pt,
	     ivl_variable_type_t dt)
: hname_(n), type_(t), port_type_(pt), data_type_(dt),
  signed_(false), isint_(false), port_set_(false), net_set_(false),
  port_msb_(0), port_lsb_(0), net_msb_(0), net_lsb_(0), error_cnt_(0),
  lidx_(0), ridx_(0)
{
      if (t == NetNet::INTEGER) {
	    type_ = NetNet::REG;
	    signed_ = true;
	    isint_ = true;
      }
}

NetNet::Type PWire::get_wire_type() const
{
      return type_;
}

const pform_name_t& PWire::path() const
{
      return hname_;
}

bool PWire::set_wire_type(NetNet::Type t)
{
      assert(t != NetNet::IMPLICIT);

      switch (type_) {
	  case NetNet::IMPLICIT:
	    type_ = t;
	    return true;
	  case NetNet::IMPLICIT_REG:
	    if (t == NetNet::REG) { type_ = t; return true; }
	    return false;
	  case NetNet::REG:
	    if (t == NetNet::INTEGER) {
		  isint_ = true;
		  return true;
	    }
	    if (t == NetNet::REG) return true;
	    return false;
	  default:
	    if (type_ != t)
		  return false;
	    else
		  return true;
      }
}

NetNet::PortType PWire::get_port_type() const
{
      return port_type_;
}

bool PWire::set_port_type(NetNet::PortType pt)
{
      assert(pt != NetNet::NOT_A_PORT);
      assert(pt != NetNet::PIMPLICIT);

      switch (port_type_) {
	  case NetNet::PIMPLICIT:
	    port_type_ = pt;
	    return true;

	  case NetNet::NOT_A_PORT:
	    return false;

	  default:
	    if (port_type_ != pt)
		  return false;
	    else
		  return true;
      }
}

bool PWire::set_data_type(ivl_variable_type_t dt)
{
      if (data_type_ != IVL_VT_NO_TYPE)
	    if (data_type_ != dt)
		  return false;
	    else
		  return true;

      assert(data_type_ == IVL_VT_NO_TYPE);
      data_type_ = dt;
      return true;
}

void PWire::set_signed(bool flag)
{
      signed_ = flag;
}

bool PWire::get_signed() const
{
      return signed_;
}

bool PWire::get_isint() const
{
      return isint_;
}

/*
 * Since implicitly defined list of port declarations are no longer
 * considered fully defined we no longer need this routine to force
 * them to be fully defined.
 *
void PWire::set_net_range()
{
      net_msb_ = port_msb_;
      net_lsb_ = port_lsb_;
      net_set_ = true;
}
*/

void PWire::set_range(PExpr*m, PExpr*l, PWSRType type)
{
      switch (type) {
	  case SR_PORT:
	    if (port_set_) {
		  cerr << get_line() << ": error: Port ``" << hname_
		       << "'' has already been declared a port." << endl;
		  error_cnt_ += 1;
	    } else {
		  port_msb_ = m;
		  port_lsb_ = l;
		  port_set_ = true;
	    }
	    return;

	  case SR_NET:
	    if (net_set_) {
		  cerr << get_line() << ": error: Net ``" << hname_
		       << "'' has already been declared." << endl;
		  error_cnt_ += 1;
	    } else {
		  net_msb_ = m;
		  net_lsb_ = l;
		  net_set_ = true;
	    }
	    return;

	  case SR_BOTH:
	    if (port_set_ || net_set_) {
		  if (port_set_) {
		        cerr << get_line() << ": error: Port ``" << hname_
		             << "'' has already been declared a port." << endl;
		        error_cnt_ += 1;
		  }
		  if (net_set_) {
		        cerr << get_line() << ": error: Net ``" << hname_
		             << "'' has already been declared." << endl;
		        error_cnt_ += 1;
		  }
	    } else {
		  port_msb_ = m;
		  port_lsb_ = l;
		  port_set_ = true;
		  net_msb_ = m;
		  net_lsb_ = l;
		  net_set_ = true;
	    }
	    return;
      }
}

void PWire::set_memory_idx(PExpr*ldx, PExpr*rdx)
{
      if (lidx_ != 0 || ridx_ != 0) {
	    cerr << get_line() << ": error: Array ``" << hname_
	         << "'' has already been declared." << endl;
	    error_cnt_ += 1;
      } else {
            lidx_ = ldx;
            ridx_ = rdx;
      }
}

<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "raptor.h"
#include "type/data.h"
#include "utils/timer.h"
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
#include <random>
#include <fstream>
#include "utils/init.h"

using namespace navitia;
using namespace routing;
namespace po = boost::program_options;

struct PathDemand {
    type::idx_t start;
    type::idx_t target;
    unsigned int date;
    unsigned int hour;
};

struct Result {
    int duration;
    int time;
    int arrival;
    int nb_changes;

    Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) {
        if(!path.items.empty())
            arrival = path.items.back().arrival.time_of_day().total_seconds();
    }
};

int main(int argc, char** argv){
    navitia::init_app();
    po::options_description desc("Options de l'outil de benchmark");
    std::string file, output;
    int iterations, start, target, date, hour;

    desc.add_options()
            ("help", "Show this message")
            ("interations,i", po::value<int>(&iterations)->default_value(100),
                     "Number of iterations (10 calcuations par iteration)")
            ("file,f", po::value<std::string>(&file)->default_value("data.nav.lz4"),
                     "Path to data.nav.lz4")
            ("start,s", po::value<int>(&start)->default_value(-1),
                    "Start of a particular journey")
            ("target,t", po::value<int>(&target)->default_value(-1),
                    "Target of a particular journey")
            ("date,d", po::value<int>(&date)->default_value(-1),
                    "Begginning date of a particular journey")
            ("hour,h", po::value<int>(&hour)->default_value(-1),
                    "Begginning hour of a particular journey")
            ("verbose,v", "Verbose debugging output")
            ("output,o", po::value<std::string>(&output)->default_value("benchmark.csv"),
                     "Output file");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    bool verbose = vm.count("verbose");

    if (vm.count("help")) {
        std::cout << "This is used to benchmark journey computation" << std::endl;
        std::cout << desc << std::endl;
        return 1;
    }

    type::Data data;
    {
        Timer t("Chargement des données : " + file);
        data.load(file);
    }
    std::vector<PathDemand> demands;

    if(start != -1 && target != -1 && date != -1 && hour != -1) {
        PathDemand demand;
        demand.start = start;
        demand.target = target;
        demand.hour = hour;
        demand.date = date;
        demands.push_back(demand);
    } else {
        // Génération des instances
        std::random_device rd;
        std::mt19937 rng(31442);
        std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);
        std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000};
        std::vector<unsigned int> days({7});
        if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)
            days.push_back(8);
        else
            days.push_back(13);

        for(int i = 0; i < iterations; ++i) {
            PathDemand demand;
            demand.start = gen(rng);
            demand.target = gen(rng);
            while(demand.start == demand.target) {
                demand.target = gen(rng);
                demand.start = gen(rng);
            }
            for(auto day : days) {
                for(auto hour : hours) {
                    demand.date = day;
                    demand.hour = hour;
                    demands.push_back(demand);
                }
            }
        }
    }

    // Calculs des itinéraires
    std::vector<Result> results;
    data.build_raptor();
    RAPTOR router(data);

    std::cout << "On lance le benchmark de l'algo " << std::endl;
    boost::progress_display show_progress(demands.size());
    Timer t("Calcul avec l'algorithme ");
    //ProfilerStart("bench.prof");
    int nb_reponses = 0;
    for(auto demand : demands){
        ++show_progress;
        Timer t2;
        if (verbose){
            std::cout << data.pt_data->stop_areas[demand.start]->uri
                      << ", " << demand.start
                      << ", " << data.pt_data->stop_areas[demand.target]->uri
                      << ", " << demand.target
                      << ", " << demand.date
                      << ", " << demand.hour
                      << "\n";
        }
        auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, navitia::DateTimeUtils::inf,false, true);

        Path path;
        if(res.size() > 0) {
            path = res[0];
            ++ nb_reponses;
        }

        Result result(path);
        result.time = t2.ms();
        results.push_back(result);
    }
    //ProfilerStop();

    Timer ecriture("Writing results");
    std::fstream out_file(output, std::ios::out);
    out_file << "Start, Start id, Target, Target id, Day, Hour";
        out_file << ", "
                 << "arrival, "
                 << "duration, "
                 << "nb_change, "
                 << "visited, "
                 << "time";
    out_file << "\n";

    for(size_t i = 0; i < demands.size(); ++i){
        PathDemand demand = demands[i];
        out_file << data.pt_data->stop_areas[demand.start]->uri
                 << ", " << demand.start
                 << ", " << data.pt_data->stop_areas[demand.target]->uri
                 << ", " << demand.target
                 << ", " << demand.date
                 << ", " << demand.hour;

        out_file << ", "
                 << results[i].arrival << ", "
                 << results[i].duration << ", "
                 << results[i].nb_changes << ", "
                 << results[i].time;

        out_file << "\n";
    }
    out_file.close();

    std::cout << "Number of requests :" << demands.size() << std::endl;
    std::cout << "Number of results with solution" << nb_reponses << std::endl;
}
<commit_msg>Benchmark: add possibility to run again the same tests<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "raptor.h"
#include "type/data.h"
#include "utils/timer.h"
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
#include <random>
#include <fstream>
#include "utils/init.h"
#include "utils/csv.h"

using namespace navitia;
using namespace routing;
namespace po = boost::program_options;

struct PathDemand {
    type::idx_t start;
    type::idx_t target;
    unsigned int date;
    unsigned int hour;
};

struct Result {
    int duration;
    int time;
    int arrival;
    int nb_changes;

    Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) {
        if(!path.items.empty())
            arrival = path.items.back().arrival.time_of_day().total_seconds();
    }
};

int main(int argc, char** argv){
    navitia::init_app();
    po::options_description desc("Options de l'outil de benchmark");
    std::string file, output, stop_input_file;
    int iterations, start, target, date, hour;

    desc.add_options()
            ("help", "Show this message")
            ("interations,i", po::value<int>(&iterations)->default_value(100),
                     "Number of iterations (10 calcuations par iteration)")
            ("file,f", po::value<std::string>(&file)->default_value("data.nav.lz4"),
                     "Path to data.nav.lz4")
            ("start,s", po::value<int>(&start)->default_value(-1),
                    "Start of a particular journey")
            ("target,t", po::value<int>(&target)->default_value(-1),
                    "Target of a particular journey")
            ("date,d", po::value<int>(&date)->default_value(-1),
                    "Begginning date of a particular journey")
            ("hour,h", po::value<int>(&hour)->default_value(-1),
                    "Begginning hour of a particular journey")
            ("verbose,v", "Verbose debugging output")
            ("stop_files", po::value<std::string>(&stop_input_file), "File with list of start and target")
            ("output,o", po::value<std::string>(&output)->default_value("benchmark.csv"),
                     "Output file");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    bool verbose = vm.count("verbose");

    if (vm.count("help")) {
        std::cout << "This is used to benchmark journey computation" << std::endl;
        std::cout << desc << std::endl;
        return 1;
    }

    type::Data data;
    {
        Timer t("Chargement des données : " + file);
        data.load(file);
    }
    std::vector<PathDemand> demands;

    if (! stop_input_file.empty()) {
        //csv file should be the same as the output one
        CsvReader csv(stop_input_file, ',');
        csv.next();
        size_t cpt_not_found = 0;
        for (auto it = csv.next(); ! csv.eof(); it = csv.next()) {
            const auto it_start = data.pt_data->stop_areas_map.find(it[0]);
            if (it_start == data.pt_data->stop_areas_map.end()) {
                std::cout << "impossible to find " << it[0] << std::endl;
                cpt_not_found++;
                continue;
            }
            const auto start = it_start->second;

            const auto it_end = data.pt_data->stop_areas_map.find(it[2]);
            if (it_end == data.pt_data->stop_areas_map.end()) {
                std::cout << "impossible to find " << it[2] << std::endl;
                cpt_not_found++;
                continue;
            }
            const auto end = it_end->second;

            PathDemand demand;
            demand.start = start->idx;
            demand.target = end->idx;
            demand.hour = boost::lexical_cast<unsigned int>(it[5]);
            demand.date = boost::lexical_cast<unsigned int>(it[4]);
            demands.push_back(demand);
        }
        std::cout << "nb start not found " << cpt_not_found << std::endl;
    }
    else if(start != -1 && target != -1 && date != -1 && hour != -1) {
        PathDemand demand;
        demand.start = start;
        demand.target = target;
        demand.hour = hour;
        demand.date = date;
        demands.push_back(demand);
    } else {
        // Génération des instances
        std::random_device rd;
        std::mt19937 rng(31442);
        std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);
        std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000};
        std::vector<unsigned int> days({7});
        if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)
            days.push_back(8);
        else
            days.push_back(13);

        for(int i = 0; i < iterations; ++i) {
            PathDemand demand;
            demand.start = gen(rng);
            demand.target = gen(rng);
            while(demand.start == demand.target) {
                demand.target = gen(rng);
                demand.start = gen(rng);
            }
            for(auto day : days) {
                for(auto hour : hours) {
                    demand.date = day;
                    demand.hour = hour;
                    demands.push_back(demand);
                }
            }
        }
    }

    // Calculs des itinéraires
    std::vector<Result> results;
    data.build_raptor();
    RAPTOR router(data);

    std::cout << "On lance le benchmark de l'algo " << std::endl;
    boost::progress_display show_progress(demands.size());
    Timer t("Calcul avec l'algorithme ");
    //ProfilerStart("bench.prof");
    int nb_reponses = 0;
    for(auto demand : demands){
        ++show_progress;
        Timer t2;
        if (verbose){
            std::cout << data.pt_data->stop_areas[demand.start]->uri
                      << ", " << demand.start
                      << ", " << data.pt_data->stop_areas[demand.target]->uri
                      << ", " << demand.target
                      << ", " << demand.date
                      << ", " << demand.hour
                      << "\n";
        }
        auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, navitia::DateTimeUtils::inf,false, true);

        Path path;
        if(res.size() > 0) {
            path = res[0];
            ++ nb_reponses;
        }

        Result result(path);
        result.time = t2.ms();
        results.push_back(result);
    }
    //ProfilerStop();

    Timer ecriture("Writing results");
    std::fstream out_file(output, std::ios::out);
    out_file << "Start, Start id, Target, Target id, Day, Hour";
        out_file << ", "
                 << "arrival, "
                 << "duration, "
                 << "nb_change, "
                 << "visited, "
                 << "time";
    out_file << "\n";

    for(size_t i = 0; i < demands.size(); ++i){
        PathDemand demand = demands[i];
        out_file << data.pt_data->stop_areas[demand.start]->uri
                 << ", " << demand.start
                 << ", " << data.pt_data->stop_areas[demand.target]->uri
                 << ", " << demand.target
                 << ", " << demand.date
                 << ", " << demand.hour;

        out_file << ", "
                 << results[i].arrival << ", "
                 << results[i].duration << ", "
                 << results[i].nb_changes << ", "
                 << results[i].time;

        out_file << "\n";
    }
    out_file.close();

    std::cout << "Number of requests :" << demands.size() << std::endl;
    std::cout << "Number of results with solution" << nb_reponses << std::endl;
}
<|endoftext|>


<commit_before>#include <ctime>
#include <iostream>
#include <cmath>

using namespace std;

int main() {

	int side{ 0 };
	int roll{ 0 };
	cout << "Enter ctrl + z in place of a number to exit at any time." << endl << endl;
	while (!cin.fail()) {
		srand(time(0));
		cout << "Enter the amount of sides your dice needs: ";
		cin >> side;
		cout << "Enter how many times you need to roll this die: ";
		cin >> roll;
		while (cin.fail())
		{
			system("pause");
			return 0;
		}
		cout << endl << "Your rolls are below." << endl;
		for (int i = 0; i < roll; i++)
			cout << 1 + rand() % side << endl;
	}

	system("pause");
	return 0;

}<commit_msg>Update Roll.cpp<commit_after>#include <ctime>
#include <iostream>
#include <cmath>

using namespace std;

int main() {

	int side{ 0 };
	int roll{ 0 };
	//User exit method prompt
	cout << "Enter ctrl + z in place of a number to exit at any time." << endl << endl;
	while (!cin.fail()) { //While ctrl+z is not entered
		srand(time(0));//seed random numbers for rolling die
		//prompt for die size (d20, d6, d8, etc) and get user input
		cout << "Enter the amount of sides your dice needs: ";
		cin >> side;
		//prompt for roll amount and get user input
		cout << "Enter how many times you need to roll this die: ";
		cin >> roll;
		while (cin.fail()) //check for user exit method
		{
			system("pause");
			return 0;
		}
		//output roll results
		cout << endl << "Your rolls are below." << endl;
		//repeat as many times as user requested
		for (int i = 0; i < roll; i++)
			//calculate roll range and output each roll on its own line
			cout << 1 + rand() % side << endl;
	}
//end program statements because it's a habit
	system("pause");
	return 0;

}
<|endoftext|>