<commit_before>#include "person.h"

#include <set>

namespace {
  bool canPathThroughDoor(roomDirData* ex)
  {
    if (!ex)
      return false;

    if (IS_SET(ex->condition, EXIT_CAVED_IN))
      return false;

    if (IS_SET(ex->condition, EXIT_CLOSED) && (
          IS_SET(ex->condition, EXIT_SECRET) || IS_SET(ex->condition, EXIT_LOCKED)))
      return false;

    return true;
  }

  // colors in TTerrainInfo
  const char* terrainToColor[16] = {
    "<K>", // black 0
    "<r>", // maroon 1
    "<G>", // green 2
    "<d><g>", // olive 3
    "<B>", // navy 4
    "<P>", // purple 5
    "<c>", // teal 6
    "<d><k>", // silver 7
    "<k>", // gray 8
    "<R>", // red 9
    "<G>", // lime 10
    "<y>", // yellow 11
    "<b>", // blue 12
    "<p>", // magenta 13
    "<C>", // cyan 14
    "<w>", // white 15
  };

  std::vector<std::string> colorize(std::vector<std::string> const& in)
  {
    std::vector<std::string> out;
    out.reserve(in.size());

    for (const auto& row : in) {
      std::string outRow;
      outRow.reserve(in.size() * 3);
      for (char cell : row) {
        if (cell < 0) {
          // cf. TRoom::colorRoom, TerrainInfo
          outRow.append(terrainToColor[TerrainInfo[-cell]->color]);
          outRow.push_back('#'); // current value is terrain type
          outRow.append("<z>");
        } else {
          outRow.push_back(cell);
        }
      }
      out.push_back(outRow);
    }

    return out;
  }

  int x(int old, dirTypeT dir)
  {
    if (dir == DIR_EAST || dir == DIR_NORTHEAST || dir == DIR_SOUTHEAST)
      return old + 1;
    if (dir == DIR_WEST || dir == DIR_NORTHWEST || dir == DIR_SOUTHWEST)
      return old - 1;
    return old;
  }

  int y(int old, dirTypeT dir)
  {
    if (dir == DIR_NORTH || dir == DIR_NORTHEAST || dir == DIR_NORTHWEST)
      return old - 1;
    if (dir == DIR_SOUTH || dir == DIR_SOUTHEAST || dir == DIR_SOUTHWEST)
      return old + 1;
    return old;
  }

  char exitSym(char old, dirTypeT dir)
  {
    switch (dir) {
      case DIR_UP:
        return '^';
      case DIR_DOWN:
        return 'v';
      default:;
    }

    switch (old) {
      case ' ':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '|';
            case DIR_EAST:
            case DIR_WEST:
              return '-';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return '/';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '\\';
            default:
              return '!';
          };
        }
      case '|':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '|';
            case DIR_EAST:
            case DIR_WEST:
              return '+';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '*';
            default:
              return '!';
          };
        }
      case '-':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '+';
            case DIR_EAST:
            case DIR_WEST:
              return '-';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '*';
            default:
              return '!';
          };
        }
      case '/':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
            case DIR_EAST:
            case DIR_WEST:
              return '*';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return '/';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return 'X';
            default:
              return '!';
          };
        }
      case '\\':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
            case DIR_EAST:
            case DIR_WEST:
              return '*';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return 'X';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '\\';
            default:
              return '!';
          };
        }
      case '*':
        return '*';
      default:
        return old;
    }
  }

  void visit(TPerson const* ch, int halfEdge, int radius, std::vector<std::string>& grid, TRoom const& r)
  {
    if (real_roomp(ch->in_room)->getZCoord() != r.getZCoord())
      return;

    int myX = real_roomp(ch->in_room)->getXCoord();
    int myY = real_roomp(ch->in_room)->getYCoord();
    // coords are now relative to the map's center point (ie. player's location)
    int dx = r.getXCoord() - myX;
    int dy = r.getYCoord() - myY;

    if (max(abs(dx), abs(dy)) > radius)
      return;

    ch->sendTo(boost::format("Visiting %d %s @ (%d,%d) rel (%d,%d)\n\r")
        % r.number % r.name % r.getXCoord() % r.getYCoord() % dx % dy);

    // Let's agree that negative values are sector types, positive values are exits.
    char symbol = -r.getSectorType();

    if (dx == 0 && dy == 0)
      symbol = '@';

    // 2 for the doors
    int hereY = -(2 * dy) + halfEdge;
    int hereX = 2 * dx + halfEdge;
    grid.at(hereY).at(hereX) = symbol;

    ///////
    // exits
    for (auto dir = MIN_DIR; dir < MAX_DIR; dir++) {
      roomDirData* ex = r.exitDir(dir);
      if (r.exitDir(dir) && canPathThroughDoor(ex))
      {
        int exitX = x(hereX, dir);
        int exitY = y(hereY, dir);
        char prevSym = grid.at(exitY).at(exitX);
        grid.at(exitY).at(exitX) = exitSym(prevSym, dir);
      }
    }
  };

}

// TODO: replace queue and set with fixed size array with advancing pointer
// (fixed because the size of map is known in advance)
void TPerson::drawMap(const int radius) const
{
  // 2n+1 rows/columns to accommodate radius of n
  // *2 to fit doors, +2 because we also want doors leading out
  size_t edgeLen = (radius * 2 + 1) * 2 + 2;
  size_t halfEdge = edgeLen / 2;

  std::vector<std::string> grid; // There's probably a clever way to initialize it in one line, maybe
  for (int i = edgeLen; i --> 0;)
    grid.emplace_back(edgeLen, ' ');

  struct Candidate
  {
    int vnum;
    int distance;
  };

  std::queue<Candidate> candidates;
  candidates.push({in_room, 0});

  std::set<int> visited;

  while (!candidates.empty()) {
    Candidate c = candidates.front();
    candidates.pop();

    if (c.distance > 5 * radius)
      continue;

    if (visited.count(c.vnum) == 1)
      continue;
    visited.insert(c.vnum);

    TRoom* r = real_roomp(c.vnum);
    if (!r)
    {
      sendTo("Error: null roomp\n\r");
      continue;
    }

    visit(this, halfEdge, radius, grid, *r);

    for (auto exitDir = MIN_DIR; exitDir < MAX_DIR; exitDir++) {
      roomDirData* ex = r->exitDir(exitDir);
      if (canPathThroughDoor(ex)) {
        // hm, doesn't happen anymore
        if (!real_roomp(ex->to_room))
          sendTo(boost::format("Error: room %d has weird exit towards %d\n\r") % c.vnum % exitDir);
        candidates.push({ex->to_room, c.distance + 1});
      }
    }
  }

  for (const auto& row : colorize(grid))
    sendTo(row + "\n\r");
}
<commit_msg>Automap: removed debug prints<commit_after>#include "person.h"

#include <set>

namespace {
  bool canPathThroughDoor(roomDirData* ex)
  {
    if (!ex)
      return false;

    if (IS_SET(ex->condition, EXIT_CAVED_IN))
      return false;

    if (IS_SET(ex->condition, EXIT_CLOSED) && (
          IS_SET(ex->condition, EXIT_SECRET) || IS_SET(ex->condition, EXIT_LOCKED)))
      return false;

    return true;
  }

  // colors in TTerrainInfo
  const char* terrainToColor[16] = {
    "<K>", // black 0
    "<r>", // maroon 1
    "<G>", // green 2
    "<d><g>", // olive 3
    "<B>", // navy 4
    "<P>", // purple 5
    "<c>", // teal 6
    "<d><k>", // silver 7
    "<k>", // gray 8
    "<R>", // red 9
    "<G>", // lime 10
    "<y>", // yellow 11
    "<b>", // blue 12
    "<p>", // magenta 13
    "<C>", // cyan 14
    "<w>", // white 15
  };

  std::vector<std::string> colorize(std::vector<std::string> const& in)
  {
    std::vector<std::string> out;
    out.reserve(in.size());

    for (const auto& row : in) {
      std::string outRow;
      outRow.reserve(in.size() * 3);
      for (char cell : row) {
        if (cell < 0) {
          // cf. TRoom::colorRoom, TerrainInfo
          outRow.append(terrainToColor[TerrainInfo[-cell]->color]);
          outRow.push_back('#'); // current value is terrain type
          outRow.append("<z>");
        } else {
          outRow.push_back(cell);
        }
      }
      out.push_back(outRow);
    }

    return out;
  }

  int x(int old, dirTypeT dir)
  {
    if (dir == DIR_EAST || dir == DIR_NORTHEAST || dir == DIR_SOUTHEAST)
      return old + 1;
    if (dir == DIR_WEST || dir == DIR_NORTHWEST || dir == DIR_SOUTHWEST)
      return old - 1;
    return old;
  }

  int y(int old, dirTypeT dir)
  {
    if (dir == DIR_NORTH || dir == DIR_NORTHEAST || dir == DIR_NORTHWEST)
      return old - 1;
    if (dir == DIR_SOUTH || dir == DIR_SOUTHEAST || dir == DIR_SOUTHWEST)
      return old + 1;
    return old;
  }

  char exitSym(char old, dirTypeT dir)
  {
    switch (dir) {
      case DIR_UP:
        return '^';
      case DIR_DOWN:
        return 'v';
      default:;
    }

    switch (old) {
      case ' ':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '|';
            case DIR_EAST:
            case DIR_WEST:
              return '-';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return '/';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '\\';
            default:
              return '!';
          };
        }
      case '|':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '|';
            case DIR_EAST:
            case DIR_WEST:
              return '+';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '*';
            default:
              return '!';
          };
        }
      case '-':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
              return '+';
            case DIR_EAST:
            case DIR_WEST:
              return '-';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '*';
            default:
              return '!';
          };
        }
      case '/':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
            case DIR_EAST:
            case DIR_WEST:
              return '*';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return '/';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return 'X';
            default:
              return '!';
          };
        }
      case '\\':
        {
          switch (dir) {
            case DIR_NORTH:
            case DIR_SOUTH:
            case DIR_EAST:
            case DIR_WEST:
              return '*';
            case DIR_NORTHEAST:
            case DIR_SOUTHWEST:
              return 'X';
            case DIR_NORTHWEST:
            case DIR_SOUTHEAST:
              return '\\';
            default:
              return '!';
          };
        }
      case '*':
        return '*';
      default:
        return old;
    }
  }

  void visit(TPerson const* ch, int halfEdge, int radius, std::vector<std::string>& grid, TRoom const& r)
  {
    if (real_roomp(ch->in_room)->getZCoord() != r.getZCoord())
      return;

    int myX = real_roomp(ch->in_room)->getXCoord();
    int myY = real_roomp(ch->in_room)->getYCoord();
    // coords are now relative to the map's center point (ie. player's location)
    int dx = r.getXCoord() - myX;
    int dy = r.getYCoord() - myY;

    if (max(abs(dx), abs(dy)) > radius)
      return;

    // Let's agree that negative values are sector types, positive values are exits.
    char symbol = -r.getSectorType();

    if (dx == 0 && dy == 0)
      symbol = '@';

    // 2 for the doors
    int hereY = -(2 * dy) + halfEdge;
    int hereX = 2 * dx + halfEdge;
    grid.at(hereY).at(hereX) = symbol;

    ///////
    // exits
    for (auto dir = MIN_DIR; dir < MAX_DIR; dir++) {
      roomDirData* ex = r.exitDir(dir);
      if (r.exitDir(dir) && canPathThroughDoor(ex))
      {
        int exitX = x(hereX, dir);
        int exitY = y(hereY, dir);
        char prevSym = grid.at(exitY).at(exitX);
        grid.at(exitY).at(exitX) = exitSym(prevSym, dir);
      }
    }
  };

}

// TODO: replace queue and set with fixed size array with advancing pointer
// (fixed because the size of map is known in advance)
void TPerson::drawMap(const int radius) const
{
  // 2n+1 rows/columns to accommodate radius of n
  // *2 to fit doors, +2 because we also want doors leading out
  size_t edgeLen = (radius * 2 + 1) * 2 + 2;
  size_t halfEdge = edgeLen / 2;

  std::vector<std::string> grid; // There's probably a clever way to initialize it in one line, maybe
  for (int i = edgeLen; i --> 0;)
    grid.emplace_back(edgeLen, ' ');

  struct Candidate
  {
    int vnum;
    int distance;
  };

  std::queue<Candidate> candidates;
  candidates.push({in_room, 0});

  std::set<int> visited;

  while (!candidates.empty()) {
    Candidate c = candidates.front();
    candidates.pop();

    if (c.distance > 5 * radius)
      continue;

    if (visited.count(c.vnum) == 1)
      continue;
    visited.insert(c.vnum);

    TRoom* r = real_roomp(c.vnum);
    if (!r)
    {
      sendTo("Error: null roomp\n\r");
      continue;
    }

    visit(this, halfEdge, radius, grid, *r);

    for (auto exitDir = MIN_DIR; exitDir < MAX_DIR; exitDir++) {
      roomDirData* ex = r->exitDir(exitDir);
      if (canPathThroughDoor(ex)) {
        // hm, doesn't happen anymore
        if (!real_roomp(ex->to_room))
          sendTo(boost::format("Error: room %d has weird exit towards %d\n\r") % c.vnum % exitDir);
        candidates.push({ex->to_room, c.distance + 1});
      }
    }
  }

  for (const auto& row : colorize(grid))
    sendTo(row + "\n\r");
}
<|endoftext|>


<commit_before>#include "includes.h"

Class::Class(const string &name) :
  Module(ClassClass),
  _name(name)
{
  this->_superclass = 0;
}

Class::Class(const string &name, Class_p superclass) :
  Module(ClassClass),
  _name(name),
  _superclass(superclass)
{
}

Class::~Class()
{
}

string Class::name() const
{
  return _name;
}

FancyObject_p Class::create_instance() const
{
  Class_p klass = const_cast<Class_p>(this);
  FancyObject_p instance = new FancyObject(klass);
  return instance;
}

FancyObject_p Class::create_instance(NativeObject_p native_value) const
{
  Class_p klass = const_cast<Class_p>(this);
  FancyObject_p instance = new FancyObject(klass, native_value);
  return instance;
}

void Class::def_slot(const string &name)
{
  this->_instance_slotnames.push_back(name);
}

void Class::def_slot(const Identifier_p name)
{
  assert(name);
  this->def_slot(name->name());
}

void Class::def_class_slot(const string &name, const FancyObject_p value)
{
  assert(value);
  this->_class_slots[name] = value;
}

void Class::def_class_slot(const Identifier_p name, const FancyObject_p value)
{
  assert(name);
  this->def_class_slot(name->name(), value);
}

FancyObject_p Class::get_class_slot(const string &identifier) const
{
  map<string, FancyObject_p>::const_iterator it;
  it = this->slots.find(identifier);
  if(it != this->slots.end()) {
    return it->second;
  } else {
    return nil;
  }
}

void Class::include(const Module_p module)
{
  assert(module);
  this->_included_modules.push_back(module);
}

vector<string> Class::instance_slotnames() const
{
  return this->_instance_slotnames;
}

map<string, FancyObject_p> Class::class_slots() const
{
  return this->_class_slots;
}

void Class::def_method(const string &name, const Callable_p method)
{
  assert(method);
  this->_instance_methods[name] = method;
}

void Class::def_method(const Identifier_p name, const Callable_p method)
{
  assert(name);
  this->def_method(name->name(), method);
}

void Class::def_class_method(const string &name, const Callable_p method)
{
  assert(method);
  // class methods are nothing else than singleton methods on class objects :)
  this->def_singleton_method(name, method);
}

void Class::def_class_method(const Identifier_p name, const Callable_p method)
{
  assert(name);
  this->def_singleton_method(name->name(), method);
}

NativeObject_p Class::equal(const NativeObject_p other) const
{
  if(!IS_CLASS(other))
    return nil;

  // TODO: compare slotnames, class_slots, superclass etc.
  return nil;
}

FancyObject_p Class::eval(Scope *scope)
{
  return this;
}

string Class::to_s() const
{
  return "<Class>";
}

Callable_p Class::find_method(const string &name)
{
  // first, try instance methods
  if(this->_instance_methods.find(name) != this->_instance_methods.end()) {
    return this->_instance_methods[name];
  }
  // then, try singleton methods (class methods)
  if(this->_singleton_methods.find(name) != this->_singleton_methods.end()) {
    return this->_singleton_methods[name];
  }
  // then, try getting method from superclass (if there is any)
  if(this->_superclass) {
    return this->_superclass->find_method(name);
  }

  return 0;
}

bool Class::is_class() const
{
  return true;
}
<commit_msg>nicer output for String#to_s()<commit_after>#include "includes.h"

Class::Class(const string &name) :
  Module(ClassClass),
  _name(name)
{
  this->_superclass = 0;
}

Class::Class(const string &name, Class_p superclass) :
  Module(ClassClass),
  _name(name),
  _superclass(superclass)
{
}

Class::~Class()
{
}

string Class::name() const
{
  return _name;
}

FancyObject_p Class::create_instance() const
{
  Class_p klass = const_cast<Class_p>(this);
  FancyObject_p instance = new FancyObject(klass);
  return instance;
}

FancyObject_p Class::create_instance(NativeObject_p native_value) const
{
  Class_p klass = const_cast<Class_p>(this);
  FancyObject_p instance = new FancyObject(klass, native_value);
  return instance;
}

void Class::def_slot(const string &name)
{
  this->_instance_slotnames.push_back(name);
}

void Class::def_slot(const Identifier_p name)
{
  assert(name);
  this->def_slot(name->name());
}

void Class::def_class_slot(const string &name, const FancyObject_p value)
{
  assert(value);
  this->_class_slots[name] = value;
}

void Class::def_class_slot(const Identifier_p name, const FancyObject_p value)
{
  assert(name);
  this->def_class_slot(name->name(), value);
}

FancyObject_p Class::get_class_slot(const string &identifier) const
{
  map<string, FancyObject_p>::const_iterator it;
  it = this->slots.find(identifier);
  if(it != this->slots.end()) {
    return it->second;
  } else {
    return nil;
  }
}

void Class::include(const Module_p module)
{
  assert(module);
  this->_included_modules.push_back(module);
}

vector<string> Class::instance_slotnames() const
{
  return this->_instance_slotnames;
}

map<string, FancyObject_p> Class::class_slots() const
{
  return this->_class_slots;
}

void Class::def_method(const string &name, const Callable_p method)
{
  assert(method);
  this->_instance_methods[name] = method;
}

void Class::def_method(const Identifier_p name, const Callable_p method)
{
  assert(name);
  this->def_method(name->name(), method);
}

void Class::def_class_method(const string &name, const Callable_p method)
{
  assert(method);
  // class methods are nothing else than singleton methods on class objects :)
  this->def_singleton_method(name, method);
}

void Class::def_class_method(const Identifier_p name, const Callable_p method)
{
  assert(name);
  this->def_singleton_method(name->name(), method);
}

NativeObject_p Class::equal(const NativeObject_p other) const
{
  if(!IS_CLASS(other))
    return nil;

  // TODO: compare slotnames, class_slots, superclass etc.
  return nil;
}

FancyObject_p Class::eval(Scope *scope)
{
  return this;
}

string Class::to_s() const
{
  return "<Class:" + this->_name + ">";
}

Callable_p Class::find_method(const string &name)
{
  // first, try instance methods
  if(this->_instance_methods.find(name) != this->_instance_methods.end()) {
    return this->_instance_methods[name];
  }
  // then, try singleton methods (class methods)
  if(this->_singleton_methods.find(name) != this->_singleton_methods.end()) {
    return this->_singleton_methods[name];
  }
  // then, try getting method from superclass (if there is any)
  if(this->_superclass) {
    return this->_superclass->find_method(name);
  }

  return 0;
}

bool Class::is_class() const
{
  return true;
}
<|endoftext|>


<commit_before>/**
 *  @file GibbsExcessVPSSTP.cpp
 *   Definitions for intermediate ThermoPhase object for phases which
 *   employ excess gibbs free energy formulations
 *  (see \ref thermoprops
 * and class \link Cantera::GibbsExcessVPSSTP GibbsExcessVPSSTP\endlink).
 *
 * Header file for a derived class of ThermoPhase that handles
 * variable pressure standard state methods for calculating
 * thermodynamic properties that are further based upon expressions
 * for the excess gibbs free energy expressed as a function of
 * the mole fractions.
 */
/*
 * Copywrite (2009) Sandia Corporation. Under the terms of
 * Contract DE-AC04-94AL85000 with Sandia Corporation, the
 * U.S. Government retains certain rights in this software.
 */
/*
 *  $Date$
 *  $Revision$
 */

#include "GibbsExcessVPSSTP.h"
using namespace std;

namespace Cantera {

  /*
   * Default constructor.
   *
   */
  GibbsExcessVPSSTP::GibbsExcessVPSSTP() :
    VPStandardStateTP()
  {
  }

  /*
   * Copy Constructor:
   *
   *  Note this stuff will not work until the underlying phase
   *  has a working copy constructor
   */
  GibbsExcessVPSSTP::GibbsExcessVPSSTP(const GibbsExcessVPSSTP &b) :
    VPStandardStateTP()
  {
    GibbsExcessVPSSTP::operator=(b);
  }

  /*
   * operator=()
   *
   *  Note this stuff will not work until the underlying phase
   *  has a working assignment operator
   */
  GibbsExcessVPSSTP& GibbsExcessVPSSTP::
  operator=(const GibbsExcessVPSSTP &b) {
    if (&b == this) {
      return *this;
    }

    VPStandardStateTP::operator=(b);

    moleFractions_       = b.moleFractions_;
    lnActCoeff_Scaled_   = b.lnActCoeff_Scaled_;
    dlnActCoeffdT_Scaled_   = b.dlnActCoeffdT_Scaled_;
    dlnActCoeffdlnC_Scaled_ = b.dlnActCoeffdlnC_Scaled_;
    m_pp                 = b.m_pp;

    return *this;
  }

  /**
   *
   * ~GibbsExcessVPSSTP():   (virtual)
   *
   * Destructor: does nothing:
   *
   */
  GibbsExcessVPSSTP::~GibbsExcessVPSSTP() {
  }

  /*
   * This routine duplicates the current object and returns
   * a pointer to ThermoPhase.
   */
  ThermoPhase*
  GibbsExcessVPSSTP::duplMyselfAsThermoPhase() const {
    GibbsExcessVPSSTP* mtp = new GibbsExcessVPSSTP(*this);
    return (ThermoPhase *) mtp;
  }

  /*
   *  -------------- Utilities -------------------------------
   */

  void GibbsExcessVPSSTP::setMassFractions(const doublereal* const y) {
#if DEBUG_MODE
    checkMFSum(y);
#endif
    State::setMassFractions(y);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setMassFractions_NoNorm(const doublereal* const y) {
#if DEBUG_MODE
    checkMFSum(y);
#endif
    State::setMassFractions_NoNorm(y);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

 void GibbsExcessVPSSTP::setMoleFractions(const doublereal* const x) {
#if DEBUG_MODE
    checkMFSum(x);
#endif
    State::setMoleFractions(x);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setMoleFractions_NoNorm(const doublereal* const x) {
#if DEBUG_MODE
    checkMFSum(x);
#endif
    State::setMoleFractions_NoNorm(x);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setConcentrations(const doublereal* const c) {
    State::setConcentrations(c);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  // Equation of state type flag.
  /*
   * The ThermoPhase base class returns
   * zero. Subclasses should define this to return a unique
   * non-zero value. Known constants defined for this purpose are
   * listed in mix_defs.h. The GibbsExcessVPSSTP class also returns
   * zero, as it is a non-complete class.
   */
  int GibbsExcessVPSSTP::eosType() const {
    return 0;
  }

  /*
   * ------------ Molar Thermodynamic Properties ----------------------
   */

  /*
   *
   * ------------ Mechanical Properties ------------------------------
   *
   */

  /*
   * Set the pressure at constant temperature. Units: Pa.
   * This method sets a constant within the object.
   * The mass density is not a function of pressure.
   */
  void GibbsExcessVPSSTP::setPressure(doublereal p) {
    setState_TP(temperature(), p);
  }

  void GibbsExcessVPSSTP::calcDensity() {
    double *vbar = &m_pp[0];
    getPartialMolarVolumes(vbar);

    doublereal vtotal = 0.0;
    for (int i = 0; i < m_kk; i++) {
      vtotal += vbar[i] * moleFractions_[i];
    }
    doublereal dd = meanMolecularWeight() / vtotal;
    State::setDensity(dd);
  }

  void GibbsExcessVPSSTP::setState_TP(doublereal t, doublereal p) {
    State::setTemperature(t);
    /*
     * Store the current pressure
     */
    m_Pcurrent = p;
    /*
     * update the standard state thermo
     * -> This involves calling the water function and setting the pressure
     */
    updateStandardStateThermo();

    /*
     * Calculate the partial molar volumes, and then the density of the fluid
     */
    calcDensity();
  }

  /*
   * - Activities, Standard States, Activity Concentrations -----------
   */

  doublereal GibbsExcessVPSSTP::standardConcentration(int k) const {
    err("standardConcentration");
    return -1.0;
  }

  doublereal GibbsExcessVPSSTP::logStandardConc(int k) const {
    err("logStandardConc");
    return -1.0;
  }

  void GibbsExcessVPSSTP::getActivities(doublereal* ac) const {
    getActivityCoefficients(ac);
    getMoleFractions(DATA_PTR(moleFractions_));
    for (int k = 0; k < m_kk; k++) {
      ac[k] *= moleFractions_[k];
    }
  }

  void GibbsExcessVPSSTP::getElectrochemPotentials(doublereal* mu) const {
    getChemPotentials(mu);
    double ve = Faraday * electricPotential();
    for (int k = 0; k < m_kk; k++) {
      mu[k] += ve*charge(k);
    }
  }

  /*
   * ------------ Partial Molar Properties of the Solution ------------
   */

  // Return an array of partial molar volumes for the
  // species in the mixture. Units: m^3/kmol.
  /*
   *  Frequently, for this class of thermodynamics representations,
   *  the excess Volume due to mixing is zero. Here, we set it as
   *  a default. It may be overriden in derived classes.
   *
   *  @param vbar   Output vector of speciar partial molar volumes.
   *                Length = m_kk. units are m^3/kmol.
   */
  void GibbsExcessVPSSTP::getPartialMolarVolumes(doublereal* vbar) const {
    /*
     * Get the standard state values in m^3 kmol-1
     */
    getStandardVolumes(vbar);
  }

  doublereal GibbsExcessVPSSTP::err(std::string msg) const {
    throw CanteraError("GibbsExcessVPSSTP","Base class method "
		       +msg+" called. Equation of state type: "+int2str(eosType()));
    return 0;
  }

  double GibbsExcessVPSSTP::checkMFSum(const doublereal * const x) const {
    doublereal norm = accumulate(x, x + m_kk, 0.0);
    if (fabs(norm - 1.0) > 1.0E-9) {
      throw CanteraError("GibbsExcessVPSSTP::checkMFSun",
			 "MF sum exceeded tolerance of 1.0E-9:" + fp2str(norm));
    }
    return norm;
  }

  /*
   * Returns the units of the standard and general concentrations
   * Note they have the same units, as their divisor is
   * defined to be equal to the activity of the kth species
   * in the solution, which is unitless.
   *
   * This routine is used in print out applications where the
   * units are needed. Usually, MKS units are assumed throughout
   * the program and in the XML input files.
   *
   * On return uA contains the powers of the units (MKS assumed)
   * of the standard concentrations and generalized concentrations
   * for the kth species.
   *
   *  uA[0] = kmol units - default  = 1
   *  uA[1] = m    units - default  = -nDim(), the number of spatial
   *                                dimensions in the Phase class.
   *  uA[2] = kg   units - default  = 0;
   *  uA[3] = Pa(pressure) units - default = 0;
   *  uA[4] = Temperature units - default = 0;
   *  uA[5] = time units - default = 0
   */
  void GibbsExcessVPSSTP::getUnitsStandardConc(double *uA, int k, int sizeUA) const {
    for (int i = 0; i < sizeUA; i++) {
      if (i == 0) uA[0] = 1.0;
      if (i == 1) uA[1] = -nDim();
      if (i == 2) uA[2] = 0.0;
      if (i == 3) uA[3] = 0.0;
      if (i == 4) uA[4] = 0.0;
      if (i == 5) uA[5] = 0.0;
    }
  }

  /*
   * @internal Initialize. This method is provided to allow
   * subclasses to perform any initialization required after all
   * species have been added. For example, it might be used to
   * resize internal work arrays that must have an entry for
   * each species.  The base class implementation does nothing,
   * and subclasses that do not require initialization do not
   * need to overload this method.  When importing a CTML phase
   * description, this method is called just prior to returning
   * from function importPhase.
   *
   * @see importCTML.cpp
   */
  void GibbsExcessVPSSTP::initThermo() {
    initLengths();
    VPStandardStateTP::initThermo();

  }

  //   Initialize lengths of local variables after all species have
  //   been identified.
  void  GibbsExcessVPSSTP::initLengths() {
    m_kk = nSpecies();
    moleFractions_.resize(m_kk);
    lnActCoeff_Scaled_.resize(m_kk);
    dlnActCoeffdT_Scaled_.resize(m_kk);
    dlnActCoeffdlnC_Scaled_.resize(m_kk);
    m_pp.resize(m_kk);
  }

  /*
   * initThermoXML()                (virtual from ThermoPhase)
   *   Import and initialize a ThermoPhase object
   *
   * @param phaseNode This object must be the phase node of a
   *             complete XML tree
   *             description of the phase, including all of the
   *             species data. In other words while "phase" must
   *             point to an XML phase object, it must have
   *             sibling nodes "speciesData" that describe
   *             the species in the phase.
   * @param id   ID of the phase. If nonnull, a check is done
   *             to see if phaseNode is pointing to the phase
   *             with the correct id.
   */
  void GibbsExcessVPSSTP::initThermoXML(XML_Node& phaseNode, std::string id) {

    VPStandardStateTP::initThermoXML(phaseNode, id);
  }

 /**
   * Format a summary of the mixture state for output.
   */
  std::string GibbsExcessVPSSTP::report(bool show_thermo) const {

    char p[800];
    string s = "";
    try {
      if (name() != "") {
	sprintf(p, " \n  %s:\n", name().c_str());
	s += p;
      }
      sprintf(p, " \n       temperature    %12.6g  K\n", temperature());
      s += p;
      sprintf(p, "          pressure    %12.6g  Pa\n", pressure());
      s += p;
      sprintf(p, "           density    %12.6g  kg/m^3\n", density());
      s += p;
      sprintf(p, "  mean mol. weight    %12.6g  amu\n", meanMolecularWeight());
      s += p;

      doublereal phi = electricPotential();
      sprintf(p, "         potential    %12.6g  V\n", phi);
      s += p;

      int kk = nSpecies();
      array_fp x(kk);
      array_fp molal(kk);
      array_fp mu(kk);
      array_fp muss(kk);
      array_fp acMolal(kk);
      array_fp actMolal(kk);
      getMoleFractions(&x[0]);

      getChemPotentials(&mu[0]);
      getStandardChemPotentials(&muss[0]);
      getActivities(&actMolal[0]);

      if (show_thermo) {
        sprintf(p, " \n");
        s += p;
        sprintf(p, "                          1 kg            1 kmol\n");
        s += p;
        sprintf(p, "                       -----------      ------------\n");
        s += p;
        sprintf(p, "          enthalpy    %12.6g     %12.4g     J\n",
		enthalpy_mass(), enthalpy_mole());
        s += p;
        sprintf(p, "   internal energy    %12.6g     %12.4g     J\n",
		intEnergy_mass(), intEnergy_mole());
        s += p;
        sprintf(p, "           entropy    %12.6g     %12.4g     J/K\n",
		entropy_mass(), entropy_mole());
        s += p;
        sprintf(p, "    Gibbs function    %12.6g     %12.4g     J\n",
		gibbs_mass(), gibbs_mole());
        s += p;
        sprintf(p, " heat capacity c_p    %12.6g     %12.4g     J/K\n",
		cp_mass(), cp_mole());
        s += p;
        try {
	  sprintf(p, " heat capacity c_v    %12.6g     %12.4g     J/K\n",
		  cv_mass(), cv_mole());
	  s += p;
        }
        catch(CanteraError) {
	  sprintf(p, " heat capacity c_v    <not implemented>       \n");
	  s += p;
        }
      }

    } catch (CanteraError) {
      ;
    }
    return s;
  }

}

<commit_msg>took out checkMFSum() which is inappropriate in that context.<commit_after>/**
 *  @file GibbsExcessVPSSTP.cpp
 *   Definitions for intermediate ThermoPhase object for phases which
 *   employ excess gibbs free energy formulations
 *  (see \ref thermoprops
 * and class \link Cantera::GibbsExcessVPSSTP GibbsExcessVPSSTP\endlink).
 *
 * Header file for a derived class of ThermoPhase that handles
 * variable pressure standard state methods for calculating
 * thermodynamic properties that are further based upon expressions
 * for the excess gibbs free energy expressed as a function of
 * the mole fractions.
 */
/*
 * Copywrite (2009) Sandia Corporation. Under the terms of
 * Contract DE-AC04-94AL85000 with Sandia Corporation, the
 * U.S. Government retains certain rights in this software.
 */
/*
 *  $Date$
 *  $Revision$
 */

#include "GibbsExcessVPSSTP.h"
using namespace std;

namespace Cantera {

  /*
   * Default constructor.
   *
   */
  GibbsExcessVPSSTP::GibbsExcessVPSSTP() :
    VPStandardStateTP()
  {
  }

  /*
   * Copy Constructor:
   *
   *  Note this stuff will not work until the underlying phase
   *  has a working copy constructor
   */
  GibbsExcessVPSSTP::GibbsExcessVPSSTP(const GibbsExcessVPSSTP &b) :
    VPStandardStateTP()
  {
    GibbsExcessVPSSTP::operator=(b);
  }

  /*
   * operator=()
   *
   *  Note this stuff will not work until the underlying phase
   *  has a working assignment operator
   */
  GibbsExcessVPSSTP& GibbsExcessVPSSTP::
  operator=(const GibbsExcessVPSSTP &b) {
    if (&b == this) {
      return *this;
    }

    VPStandardStateTP::operator=(b);

    moleFractions_       = b.moleFractions_;
    lnActCoeff_Scaled_   = b.lnActCoeff_Scaled_;
    dlnActCoeffdT_Scaled_   = b.dlnActCoeffdT_Scaled_;
    dlnActCoeffdlnC_Scaled_ = b.dlnActCoeffdlnC_Scaled_;
    m_pp                 = b.m_pp;

    return *this;
  }

  /**
   *
   * ~GibbsExcessVPSSTP():   (virtual)
   *
   * Destructor: does nothing:
   *
   */
  GibbsExcessVPSSTP::~GibbsExcessVPSSTP() {
  }

  /*
   * This routine duplicates the current object and returns
   * a pointer to ThermoPhase.
   */
  ThermoPhase*
  GibbsExcessVPSSTP::duplMyselfAsThermoPhase() const {
    GibbsExcessVPSSTP* mtp = new GibbsExcessVPSSTP(*this);
    return (ThermoPhase *) mtp;
  }

  /*
   *  -------------- Utilities -------------------------------
   */

  void GibbsExcessVPSSTP::setMassFractions(const doublereal* const y) {
    State::setMassFractions(y);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setMassFractions_NoNorm(const doublereal* const y) {
    State::setMassFractions_NoNorm(y);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

 void GibbsExcessVPSSTP::setMoleFractions(const doublereal* const x) {
    State::setMoleFractions(x);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setMoleFractions_NoNorm(const doublereal* const x) {
    State::setMoleFractions_NoNorm(x);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  void GibbsExcessVPSSTP::setConcentrations(const doublereal* const c) {
    State::setConcentrations(c);
    getMoleFractions(DATA_PTR(moleFractions_));
  }

  // Equation of state type flag.
  /*
   * The ThermoPhase base class returns
   * zero. Subclasses should define this to return a unique
   * non-zero value. Known constants defined for this purpose are
   * listed in mix_defs.h. The GibbsExcessVPSSTP class also returns
   * zero, as it is a non-complete class.
   */
  int GibbsExcessVPSSTP::eosType() const {
    return 0;
  }

  /*
   * ------------ Molar Thermodynamic Properties ----------------------
   */

  /*
   *
   * ------------ Mechanical Properties ------------------------------
   *
   */

  /*
   * Set the pressure at constant temperature. Units: Pa.
   * This method sets a constant within the object.
   * The mass density is not a function of pressure.
   */
  void GibbsExcessVPSSTP::setPressure(doublereal p) {
    setState_TP(temperature(), p);
  }

  void GibbsExcessVPSSTP::calcDensity() {
    double *vbar = &m_pp[0];
    getPartialMolarVolumes(vbar);

    doublereal vtotal = 0.0;
    for (int i = 0; i < m_kk; i++) {
      vtotal += vbar[i] * moleFractions_[i];
    }
    doublereal dd = meanMolecularWeight() / vtotal;
    State::setDensity(dd);
  }

  void GibbsExcessVPSSTP::setState_TP(doublereal t, doublereal p) {
    State::setTemperature(t);
    /*
     * Store the current pressure
     */
    m_Pcurrent = p;
    /*
     * update the standard state thermo
     * -> This involves calling the water function and setting the pressure
     */
    updateStandardStateThermo();

    /*
     * Calculate the partial molar volumes, and then the density of the fluid
     */
    calcDensity();
  }

  /*
   * - Activities, Standard States, Activity Concentrations -----------
   */

  doublereal GibbsExcessVPSSTP::standardConcentration(int k) const {
    err("standardConcentration");
    return -1.0;
  }

  doublereal GibbsExcessVPSSTP::logStandardConc(int k) const {
    err("logStandardConc");
    return -1.0;
  }

  void GibbsExcessVPSSTP::getActivities(doublereal* ac) const {
    getActivityCoefficients(ac);
    getMoleFractions(DATA_PTR(moleFractions_));
    for (int k = 0; k < m_kk; k++) {
      ac[k] *= moleFractions_[k];
    }
  }

  void GibbsExcessVPSSTP::getElectrochemPotentials(doublereal* mu) const {
    getChemPotentials(mu);
    double ve = Faraday * electricPotential();
    for (int k = 0; k < m_kk; k++) {
      mu[k] += ve*charge(k);
    }
  }

  /*
   * ------------ Partial Molar Properties of the Solution ------------
   */

  // Return an array of partial molar volumes for the
  // species in the mixture. Units: m^3/kmol.
  /*
   *  Frequently, for this class of thermodynamics representations,
   *  the excess Volume due to mixing is zero. Here, we set it as
   *  a default. It may be overriden in derived classes.
   *
   *  @param vbar   Output vector of speciar partial molar volumes.
   *                Length = m_kk. units are m^3/kmol.
   */
  void GibbsExcessVPSSTP::getPartialMolarVolumes(doublereal* vbar) const {
    /*
     * Get the standard state values in m^3 kmol-1
     */
    getStandardVolumes(vbar);
  }

  doublereal GibbsExcessVPSSTP::err(std::string msg) const {
    throw CanteraError("GibbsExcessVPSSTP","Base class method "
		       +msg+" called. Equation of state type: "+int2str(eosType()));
    return 0;
  }

  double GibbsExcessVPSSTP::checkMFSum(const doublereal * const x) const {
    doublereal norm = accumulate(x, x + m_kk, 0.0);
    if (fabs(norm - 1.0) > 1.0E-9) {
      throw CanteraError("GibbsExcessVPSSTP::checkMFSum",
			 "(MF sum - 1) exceeded tolerance of 1.0E-9:" + fp2str(norm));
    }
    return norm;
  }

  /*
   * Returns the units of the standard and general concentrations
   * Note they have the same units, as their divisor is
   * defined to be equal to the activity of the kth species
   * in the solution, which is unitless.
   *
   * This routine is used in print out applications where the
   * units are needed. Usually, MKS units are assumed throughout
   * the program and in the XML input files.
   *
   * On return uA contains the powers of the units (MKS assumed)
   * of the standard concentrations and generalized concentrations
   * for the kth species.
   *
   *  uA[0] = kmol units - default  = 1
   *  uA[1] = m    units - default  = -nDim(), the number of spatial
   *                                dimensions in the Phase class.
   *  uA[2] = kg   units - default  = 0;
   *  uA[3] = Pa(pressure) units - default = 0;
   *  uA[4] = Temperature units - default = 0;
   *  uA[5] = time units - default = 0
   */
  void GibbsExcessVPSSTP::getUnitsStandardConc(double *uA, int k, int sizeUA) const {
    for (int i = 0; i < sizeUA; i++) {
      if (i == 0) uA[0] = 1.0;
      if (i == 1) uA[1] = -nDim();
      if (i == 2) uA[2] = 0.0;
      if (i == 3) uA[3] = 0.0;
      if (i == 4) uA[4] = 0.0;
      if (i == 5) uA[5] = 0.0;
    }
  }

  /*
   * @internal Initialize. This method is provided to allow
   * subclasses to perform any initialization required after all
   * species have been added. For example, it might be used to
   * resize internal work arrays that must have an entry for
   * each species.  The base class implementation does nothing,
   * and subclasses that do not require initialization do not
   * need to overload this method.  When importing a CTML phase
   * description, this method is called just prior to returning
   * from function importPhase.
   *
   * @see importCTML.cpp
   */
  void GibbsExcessVPSSTP::initThermo() {
    initLengths();
    VPStandardStateTP::initThermo();

  }

  //   Initialize lengths of local variables after all species have
  //   been identified.
  void  GibbsExcessVPSSTP::initLengths() {
    m_kk = nSpecies();
    moleFractions_.resize(m_kk);
    lnActCoeff_Scaled_.resize(m_kk);
    dlnActCoeffdT_Scaled_.resize(m_kk);
    dlnActCoeffdlnC_Scaled_.resize(m_kk);
    m_pp.resize(m_kk);
  }

  /*
   * initThermoXML()                (virtual from ThermoPhase)
   *   Import and initialize a ThermoPhase object
   *
   * @param phaseNode This object must be the phase node of a
   *             complete XML tree
   *             description of the phase, including all of the
   *             species data. In other words while "phase" must
   *             point to an XML phase object, it must have
   *             sibling nodes "speciesData" that describe
   *             the species in the phase.
   * @param id   ID of the phase. If nonnull, a check is done
   *             to see if phaseNode is pointing to the phase
   *             with the correct id.
   */
  void GibbsExcessVPSSTP::initThermoXML(XML_Node& phaseNode, std::string id) {

    VPStandardStateTP::initThermoXML(phaseNode, id);
  }

 /**
   * Format a summary of the mixture state for output.
   */
  std::string GibbsExcessVPSSTP::report(bool show_thermo) const {

    char p[800];
    string s = "";
    try {
      if (name() != "") {
	sprintf(p, " \n  %s:\n", name().c_str());
	s += p;
      }
      sprintf(p, " \n       temperature    %12.6g  K\n", temperature());
      s += p;
      sprintf(p, "          pressure    %12.6g  Pa\n", pressure());
      s += p;
      sprintf(p, "           density    %12.6g  kg/m^3\n", density());
      s += p;
      sprintf(p, "  mean mol. weight    %12.6g  amu\n", meanMolecularWeight());
      s += p;

      doublereal phi = electricPotential();
      sprintf(p, "         potential    %12.6g  V\n", phi);
      s += p;

      int kk = nSpecies();
      array_fp x(kk);
      array_fp molal(kk);
      array_fp mu(kk);
      array_fp muss(kk);
      array_fp acMolal(kk);
      array_fp actMolal(kk);
      getMoleFractions(&x[0]);

      getChemPotentials(&mu[0]);
      getStandardChemPotentials(&muss[0]);
      getActivities(&actMolal[0]);

      if (show_thermo) {
        sprintf(p, " \n");
        s += p;
        sprintf(p, "                          1 kg            1 kmol\n");
        s += p;
        sprintf(p, "                       -----------      ------------\n");
        s += p;
        sprintf(p, "          enthalpy    %12.6g     %12.4g     J\n",
		enthalpy_mass(), enthalpy_mole());
        s += p;
        sprintf(p, "   internal energy    %12.6g     %12.4g     J\n",
		intEnergy_mass(), intEnergy_mole());
        s += p;
        sprintf(p, "           entropy    %12.6g     %12.4g     J/K\n",
		entropy_mass(), entropy_mole());
        s += p;
        sprintf(p, "    Gibbs function    %12.6g     %12.4g     J\n",
		gibbs_mass(), gibbs_mole());
        s += p;
        sprintf(p, " heat capacity c_p    %12.6g     %12.4g     J/K\n",
		cp_mass(), cp_mole());
        s += p;
        try {
	  sprintf(p, " heat capacity c_v    %12.6g     %12.4g     J/K\n",
		  cv_mass(), cv_mole());
	  s += p;
        }
        catch(CanteraError) {
	  sprintf(p, " heat capacity c_v    <not implemented>       \n");
	  s += p;
        }
      }

    } catch (CanteraError) {
      ;
    }
    return s;
  }

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ImportFilter.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <osl/diagnose.h>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <comphelper/mediadescriptor.hxx>
#include <oox/core/filterdetect.hxx>
#include <dmapper/DomainMapper.hxx>
#include <WriterFilter.hxx>
#include <doctok/WW8Document.hxx>
#include <ooxml/OOXMLDocument.hxx>
#ifdef DEBUG_IMPORT
#include <iostream>
#include <osl/process.h>
#endif

#include <resourcemodel/TagLogger.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
   throw (uno::RuntimeException)
{
    if( m_xSrcDoc.is() )
    {
        uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
        uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.DocxExport" ))), uno::UNO_QUERY_THROW);
        if (!xIfc.is())
            return sal_False;
        uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
        uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
        if (!xExprtr.is() || !xFltr.is())
            return sal_False;
        xExprtr->setSourceDocument(m_xSrcDoc);
        return xFltr->filter(aDescriptor);
    }
    else if (m_xDstDoc.is())
    {
        MediaDescriptor aMediaDesc( aDescriptor );
        OUString sFilterName = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_FILTERNAME(), OUString() );

        uno::Reference< io::XInputStream > xInputStream;
        try
        {
            // use the oox.core.FilterDetect implementation to extract the decrypted ZIP package
            uno::Reference< lang::XMultiServiceFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_QUERY_THROW );
            ::oox::core::FilterDetect aDetector( xFactory );
            xInputStream = aDetector.extractUnencryptedPackage( aMediaDesc );
        }
        catch( uno::Exception& )
        {
        }

        if ( !xInputStream.is() )
        {
            return sal_False;
        }

#ifdef DEBUG_ELEMENT
    writerfilter::TagLogger::Pointer_t debugLogger
    (writerfilter::TagLogger::getInstance("DEBUG"));
    debugLogger->startDocument();

    writerfilter::TagLogger::Pointer_t dmapperLogger
    (writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
    dmapperLogger->startDocument();
#endif

    writerfilter::dmapper::SourceDocumentType eType =
        (m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "writer_MS_Word_2007" ) ) ||
         m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "writer_MS_Word_2007_Template" ) )) ?
                writerfilter::dmapper::DOCUMENT_OOXML : writerfilter::dmapper::DOCUMENT_DOC;
    writerfilter::Stream::Pointer_t pStream(new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, eType));
    //create the tokenizer and domain mapper
    if( eType == writerfilter::dmapper::DOCUMENT_OOXML )
    {
        writerfilter::ooxml::OOXMLStream::Pointer_t pDocStream = writerfilter::ooxml::OOXMLDocumentFactory::createStream(m_xContext, xInputStream);
        writerfilter::ooxml::OOXMLDocument::Pointer_t pDocument(writerfilter::ooxml::OOXMLDocumentFactory::createDocument(pDocStream));

        uno::Reference<frame::XModel> xModel(m_xDstDoc, uno::UNO_QUERY_THROW);
        pDocument->setModel(xModel);

        uno::Reference<drawing::XDrawPageSupplier> xDrawings
            (m_xDstDoc, uno::UNO_QUERY_THROW);
        uno::Reference<drawing::XDrawPage> xDrawPage
            (xDrawings->getDrawPage(), uno::UNO_SET_THROW);
        pDocument->setDrawPage(xDrawPage);

        pDocument->resolve(*pStream);
    }
    else
    {
        writerfilter::doctok::WW8Stream::Pointer_t pDocStream = writerfilter::doctok::WW8DocumentFactory::createStream(m_xContext, xInputStream);
        writerfilter::doctok::WW8Document::Pointer_t pDocument(writerfilter::doctok::WW8DocumentFactory::createDocument(pDocStream));

        pDocument->resolve(*pStream);
    }

#ifdef DEBUG_ELEMENT
    debugLogger->endDocument();
    writerfilter::TagLogger::dump("DEBUG");
    dmapperLogger->endDocument();
    writerfilter::TagLogger::dump("DOMAINMAPPER");
#endif

    return sal_True;
    }
    return sal_False;
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::cancel(  ) throw (uno::RuntimeException)
{
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xDstDoc = xDoc;
}

void WriterFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xSrcDoc = xDoc;
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException)
{
   uno::Sequence < beans::PropertyValue > aAnySeq;
   sal_Int32 nLength = aArguments.getLength();
   if ( nLength && ( aArguments[0] >>= aAnySeq ) )
   {
       const beans::PropertyValue * pValue = aAnySeq.getConstArray();
       nLength = aAnySeq.getLength();
       for ( sal_Int32 i = 0 ; i < nLength; i++)
       {
           if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) )
           {
               pValue[i].Value >>= m_sFilterName;
               break;
           }
       }
   }
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
OUString WriterFilter_getImplementationName () throw (uno::RuntimeException)
{
   return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WriterFilter" ) );
}

#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter_supportsService( const OUString& ServiceName ) throw (uno::RuntimeException)
{
   return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
           ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ));
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Sequence< OUString > WriterFilter_getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
   uno::Sequence < OUString > aRet(2);
   OUString* pArray = aRet.getArray();
   pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
   pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
   return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Reference< uno::XInterface > WriterFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
                throw( uno::Exception )
{
   return (cppu::OWeakObject*) new WriterFilter( xContext );
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
OUString WriterFilter::getImplementationName(  ) throw (uno::RuntimeException)
{
   return WriterFilter_getImplementationName();
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
    return WriterFilter_supportsService( rServiceName );
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Sequence< OUString > WriterFilter::getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
    return WriterFilter_getSupportedServiceNames();
}

<commit_msg>undone previous changes to ImportFilter.cxx, side effects at work<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ImportFilter.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <osl/diagnose.h>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <comphelper/mediadescriptor.hxx>
#include <oox/core/filterdetect.hxx>
#include <dmapper/DomainMapper.hxx>
#include <WriterFilter.hxx>
#include <doctok/WW8Document.hxx>
#include <ooxml/OOXMLDocument.hxx>
#ifdef DEBUG_IMPORT
#include <iostream>
#include <osl/process.h>
#endif

#include <resourcemodel/TagLogger.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
   throw (uno::RuntimeException)
{
    if( m_xSrcDoc.is() )
    {
        uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
        uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.DocxExport" ))), uno::UNO_QUERY_THROW);
        if (!xIfc.is())
            return sal_False;
        uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
        uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
        if (!xExprtr.is() || !xFltr.is())
            return sal_False;
        xExprtr->setSourceDocument(m_xSrcDoc);
        return xFltr->filter(aDescriptor);
    }
    else if (m_xDstDoc.is())
    {
        MediaDescriptor aMediaDesc( aDescriptor );
        OUString sFilterName = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_FILTERNAME(), OUString() );

        uno::Reference< io::XInputStream > xInputStream;
        try
        {
            // use the oox.core.FilterDetect implementation to extract the decrypted ZIP package
            uno::Reference< lang::XMultiServiceFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_QUERY_THROW );
            ::oox::core::FilterDetect aDetector( xFactory );
            xInputStream = aDetector.extractUnencryptedPackage( aMediaDesc );
        }
        catch( uno::Exception& )
        {
        }

        if ( !xInputStream.is() )
        {
            return sal_False;
        }

#ifdef DEBUG_ELEMENT
    writerfilter::TagLogger::Pointer_t debugLogger
    (writerfilter::TagLogger::getInstance("DEBUG"));
    debugLogger->startDocument();

    writerfilter::TagLogger::Pointer_t dmapperLogger
    (writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
    dmapperLogger->startDocument();
#endif

    writerfilter::dmapper::SourceDocumentType eType =
        (m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "writer_MS_Word_2007" ) ) ||
         m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "writer_MS_Word_2007_Template" ) )) ?
                writerfilter::dmapper::DOCUMENT_OOXML : writerfilter::dmapper::DOCUMENT_DOC;
    writerfilter::Stream::Pointer_t pStream(new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, eType));
    //create the tokenizer and domain mapper
    if( eType == writerfilter::dmapper::DOCUMENT_OOXML )
    {
        writerfilter::ooxml::OOXMLStream::Pointer_t pDocStream = writerfilter::ooxml::OOXMLDocumentFactory::createStream(m_xContext, xInputStream);
        writerfilter::ooxml::OOXMLDocument::Pointer_t pDocument(writerfilter::ooxml::OOXMLDocumentFactory::createDocument(pDocStream));

        uno::Reference<frame::XModel> xModel(m_xDstDoc, uno::UNO_QUERY_THROW);
        pDocument->setModel(xModel);

        uno::Reference<drawing::XDrawPageSupplier> xDrawings
            (m_xDstDoc, uno::UNO_QUERY_THROW);
        uno::Reference<drawing::XDrawPage> xDrawPage
            (xDrawings->getDrawPage(), uno::UNO_SET_THROW);
        pDocument->setDrawPage(xDrawPage);

        pDocument->resolve(*pStream);
    }
    else
    {
        writerfilter::doctok::WW8Stream::Pointer_t pDocStream = writerfilter::doctok::WW8DocumentFactory::createStream(m_xContext, xInputStream);
        writerfilter::doctok::WW8Document::Pointer_t pDocument(writerfilter::doctok::WW8DocumentFactory::createDocument(pDocStream));

        pDocument->resolve(*pStream);
    }

#ifdef DEBUG_ELEMENT
    writerfilter::TagLogger::dump("DEBUG");
    debugLogger->endDocument();
    writerfilter::TagLogger::dump("DOMAINMAPPER");
    dmapperLogger->endDocument();
#endif

    return sal_True;
    }
    return sal_False;
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::cancel(  ) throw (uno::RuntimeException)
{
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xDstDoc = xDoc;
}

void WriterFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xSrcDoc = xDoc;
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
void WriterFilter::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException)
{
   uno::Sequence < beans::PropertyValue > aAnySeq;
   sal_Int32 nLength = aArguments.getLength();
   if ( nLength && ( aArguments[0] >>= aAnySeq ) )
   {
       const beans::PropertyValue * pValue = aAnySeq.getConstArray();
       nLength = aAnySeq.getLength();
       for ( sal_Int32 i = 0 ; i < nLength; i++)
       {
           if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) )
           {
               pValue[i].Value >>= m_sFilterName;
               break;
           }
       }
   }
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
OUString WriterFilter_getImplementationName () throw (uno::RuntimeException)
{
   return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WriterFilter" ) );
}

#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter_supportsService( const OUString& ServiceName ) throw (uno::RuntimeException)
{
   return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
           ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ));
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Sequence< OUString > WriterFilter_getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
   uno::Sequence < OUString > aRet(2);
   OUString* pArray = aRet.getArray();
   pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
   pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
   return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Reference< uno::XInterface > WriterFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
                throw( uno::Exception )
{
   return (cppu::OWeakObject*) new WriterFilter( xContext );
}

/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
OUString WriterFilter::getImplementationName(  ) throw (uno::RuntimeException)
{
   return WriterFilter_getImplementationName();
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool WriterFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
    return WriterFilter_supportsService( rServiceName );
}
/*-- 09.06.2006 10:15:20---------------------------------------------------

  -----------------------------------------------------------------------*/
uno::Sequence< OUString > WriterFilter::getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
    return WriterFilter_getSupportedServiceNames();
}

<|endoftext|>


<commit_before>#include <errno.h>
#include "qmodbus.h"

QModBus::QModBus(QObject *parent) :
    QObject(parent),
    dev(NULL),
    errNo(0)
{
}

QModBus::~QModBus()
{
    if (isOpen())
        close();
}

void QModBus::close()
{
    modbus_free(dev);
    dev = NULL;
}

bool QModBus::currentT(int *T)
{
    *T = 0;
    if (modbus_read_registers(dev, REG_PV_IN, 1, (uint16_t*)T) != 1) {
        errNo = errno;
        return false;
    }
    return true;
}

int QModBus::error() const
{
    return errNo;
}

QString QModBus::errorString() const
{
    return strerror(errNo);
}

bool QModBus::isOpen() const
{
    return (dev != NULL);
}

bool QModBus::open(const QString &port, int slave)
{
    dev = modbus_new_rtu(port.toLocal8Bit().constData(), 9600, 'N', 8, 1);
    if (dev == NULL) {
        errNo = errno;
        return false;
    }

    if (modbus_connect(dev) == -1)
    {
        errNo = errno;
        return false;
    }

    if (modbus_set_slave(dev, slave) == -1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::setTarget(int T)
{
    //return (modbus_write_register(dev, REG_SP_SEL, 0) == 1);
    if (modbus_write_registers(dev, REG_SP1, 1, (uint16_t*)&T) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::setProgram(bool enabled)
{
    if (modbus_write_register(dev, REG_IM, enabled ? 1 : 0) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::targetT(int *T)
{
    *T = 0;

    if (modbus_read_registers(dev, REG_TG_SP, 1, (uint16_t*)T) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::targetTRange(int *Tmin, int *Tmax)
{
    *Tmin = *Tmax = 0;

    if (modbus_read_registers(dev, REG_SP_LO, 1, (uint16_t*)Tmin) != 1) {
        errNo = errno;
        return false;
    }

    if (modbus_read_registers(dev, REG_SP_HI, 1, (uint16_t*)Tmax) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}
<commit_msg>QModBus clean up<commit_after>#include <errno.h>
#include "qmodbus.h"

QModBus::QModBus(QObject *parent) :
    QObject(parent),
    dev(NULL),
    errNo(0)
{
}

QModBus::~QModBus()
{
    if (isOpen())
        close();
}

void QModBus::close()
{
    modbus_free(dev);
    dev = NULL;
}

bool QModBus::currentT(int *T)
{
    *T = 0;
    if (modbus_read_registers(dev, REG_PV_IN, 1, (uint16_t*)T) != 1) {
        errNo = errno;
        return false;
    }
    return true;
}

int QModBus::error() const
{
    return errNo;
}

QString QModBus::errorString() const
{
    return strerror(errNo);
}

bool QModBus::isOpen() const
{
    return (dev != NULL);
}

bool QModBus::open(const QString &port, int slave)
{
    dev = modbus_new_rtu(port.toLocal8Bit().constData(), 9600, 'N', 8, 1);
    if (dev == NULL) {
        errNo = errno;
        return false;
    }

    if (modbus_connect(dev) == -1)
    {
        errNo = errno;
        return false;
    }

    if (modbus_set_slave(dev, slave) == -1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::setTarget(int T)
{
    if (modbus_write_register(dev, REG_SP1, T) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::setProgram(bool enabled)
{
    if (modbus_write_register(dev, REG_IM, enabled ? 1 : 0) != 1) {
        errNo = errno;
        return false;
    }

    // TODO: check: set output value to 0
    if (!enabled) {
        if (modbus_write_register(dev, REG_MAN_OP, 0) != 1) {
            errNo = errno;
            return false;
        }
    }
    return true;
}

bool QModBus::targetT(int *T)
{
    *T = 0;

    if (modbus_read_registers(dev, REG_TG_SP, 1, (uint16_t*)T) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}

bool QModBus::targetTRange(int *Tmin, int *Tmax)
{
    *Tmin = *Tmax = 0;

    if (modbus_read_registers(dev, REG_SP_LO, 1, (uint16_t*)Tmin) != 1) {
        errNo = errno;
        return false;
    }

    if (modbus_read_registers(dev, REG_SP_HI, 1, (uint16_t*)Tmax) != 1) {
        errNo = errno;
        return false;
    }

    return true;
}
<|endoftext|>


<commit_before>#include "hash.hpp"
#include "profiling.hpp"

namespace clover {
namespace util {

uint32 byteHash32(const uint8* buf, SizeType size){
	// Modified FNV-1a
	uint32 hash= 2166136261;
	for (SizeType i= 0; i < size; ++i){
		hash= ((hash ^ buf[i]) + 379721)*16777619;
	}
	return hash;
}

uint32 Hash32<real32>::operator()(real32 value) const {
	union { real32 f; uint32 i; } u;
	u.f= value;
	return u.i;
}

uint32 Hash32<real64>::operator()(real64 value) const {
	union { real64 f; uint32 i[2]; } u;
	u.f= value;
	return u.i[0]^u.i[1];
}

} // util
} // clover
<commit_msg>Duff's device seems to be helpful for hash function<commit_after>#include "hash.hpp"
#include "profiling.hpp"

namespace clover {
namespace util {

uint32 byteHash32(const uint8* buf, SizeType size){
#define USE_DUFF_OPTIMZ 1
	PROFILE();

	// Modified FNV-1a
	uint32 hash= 2166136261;

#if USE_DUFF_OPTIMZ
#define HASH \
	do { hash= ((hash ^ *buf++) + 379721)*16777619; } while (0)
	if (size == 0)
		return hash;
	SizeType n= (size + 7)/8;
	switch (size % 8) {
		case 0: do { HASH;
		case 7: HASH;
		case 6: HASH;
		case 5: HASH;
		case 4: HASH;
		case 3: HASH;
		case 2: HASH;
		case 1: HASH; } while (--n > 0);
	}
#undef HASH
#else
	for (SizeType i= 0; i < size; ++i){
		hash= ((hash ^ buf[i]) + 379721)*16777619;
	}
#endif

	return hash;
}

uint32 Hash32<real32>::operator()(real32 value) const {
	union { real32 f; uint32 i; } u;
	u.f= value;
	return u.i;
}

uint32 Hash32<real64>::operator()(real64 value) const {
	union { real64 f; uint32 i[2]; } u;
	u.f= value;
	return u.i[0]^u.i[1];
}

} // util
} // clover
<|endoftext|>


<commit_before>
#include "data.hpp"

#ifdef MUSTACHE_HAVE_LIBYAML
#include "yaml.h"
#endif

#if defined(MUSTACHE_HAVE_LIBJSON)
#include "json/json.h"
//#include "json/json_inttypes.h"
#include "json/json_object.h"
#include "json/json_tokener.h"
#elif defined(MUSTACHE_HAVE_LIBJANSSON)
#include "jansson.h"
#endif

#include "stdio.h"

namespace mustache {

Data::~Data()
{
  switch( this->type ) {
    case Data::TypeString:
      delete val;
      break;
    case Data::TypeMap:
      if( data.size() > 0 ) {
        Data::Map::iterator dataIt;
        for ( dataIt = data.begin() ; dataIt != data.end(); dataIt++ ) {
          delete (*dataIt).second;
        }
        data.clear();
      }
      break;
    case Data::TypeList:
      if( children.size() > 0 ) {
        Data::List::iterator childrenIt;
        for ( childrenIt = children.begin() ; childrenIt != children.end(); childrenIt++ ) {
          delete *childrenIt;
        }
        children.clear();
      }
    case Data::TypeArray:
      //delete[] array;
      break;
  }
}

void Data::init(Data::Type type, int size) {
  this->type = type;
  this->length = size;
  switch( type ) {
    case Data::TypeString:
      val = new std::string();
      val->reserve(size);
      break;
    case Data::TypeMap:
      // Do nothing
      break;
    case Data::TypeList:
      // Do nothing
      break;
    case Data::TypeArray:
      this->array.reserve(size);
      break;
  }
};

int Data::isEmpty()
{
  int ret = 0;
  switch( type ) {
    default:
    case Data::TypeNone:
      ret = 1;
      break;
    case Data::TypeString:
      if( val == NULL || val->length() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeList:
      if( children.size() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeMap:
      if( data.size() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeArray:
      if( length <= 0 ) {
        ret = 1;
      }
      break;
  }
  return ret;
}

Data * searchStack(Stack<Data *> * stack, std::string * key)
{
  // Resolve up the data stack
  Data * ref = NULL;
  Data::Map::iterator d_it;
  register int i;
  Data ** _stackPos = stack->end();
  for( i = 0; i < stack->size(); i++, _stackPos-- ) {
    if( (*_stackPos) == NULL ) continue;
    if( (*_stackPos)->type == Data::TypeMap ) {
      d_it = (*_stackPos)->data.find(*key);
      if( d_it != (*_stackPos)->data.end() ) {
        ref = d_it->second;
        if( ref != NULL ) {
          break;
        }
      }
    }
  }
  return ref;
}

Data * searchStackNR(Stack<Data *> * stack, std::string * key)
{
  Data * ref = NULL;
  Data * back = stack->back();
  Data::Map::iterator d_it;
  if( back != NULL && back->type == Data::TypeMap ) {
    d_it = back->data.find(*key);
    if( d_it != back->data.end() ) {
      ref = d_it->second;
      if( ref != NULL ) {
        return ref;
      }
    }
  }
  return NULL;
}

// Data integrations

#if defined(MUSTACHE_HAVE_LIBJSON)
static void _createFromJSON(Data * data, struct json_object * object)
{
  Data * child = NULL;

  switch( json_object_get_type(object) ) {
    case json_type_null:
      data->type = Data::TypeString;
      data->val = new std::string("");
      break;
    case json_type_boolean:
      data->type = Data::TypeString;
      if( 0 == (int) json_object_get_boolean(object) ) {
        data->val = new std::string("");
      } else {
        data->val = new std::string("true");
      }
      break;
    case json_type_double:
    case json_type_int:
    case json_type_string:
      data->type = Data::TypeString;
      data->val = new std::string(json_object_get_string(object));
      break;
    case json_type_object: {
      data->type = Data::TypeMap;
      std::string ckey;
      json_object_object_foreach(object, key, value)
      {
        ckey.assign(key);
        child = new Data();
        _createFromJSON(child, value);
        data->data.insert(std::pair<std::string,Data *>(ckey,child));
      }
      break;
    }
    case json_type_array: {
      int len = json_object_array_length(object);
      data->init(Data::TypeArray, len);
      //child = data->array;

      struct json_object * array_item;
      for( int i = 0; i < len; i++, child++ ) {
        //array_item = json_object_array_get_idx(object, i);
        //_createFromJSON(child, array_item);
      }
      break;
    }
    default: {
      throw Exception("Unknown json type");
    }
  }
}

Data * Data::createFromJSON(const char * string)
{
  struct json_object * result = json_tokener_parse((char *) string);
  if( result == NULL ) {
    throw Exception("Invalid JSON data");
  }
  Data * data = new Data();
  data->type = Data::TypeNone;
  _createFromJSON(data, result);
  json_object_put(result);
  return data;
}
#elif defined(MUSTACHE_HAVE_LIBJANNSON)
Data * Data::createFromJSON(const char * string)
{
  throw Exception("JSON support using libjannson not implemented");
}
#else
Data * Data::createFromJSON(const char * string)
{
  throw Exception("JSON support not enabled");
}
#endif

#if defined(MUSTACHE_HAVE_LIBYAML)
static void _createFromYAML(Data * data, yaml_document_t * document, yaml_node_t * node)
{
  Data * child = NULL;

  switch( node->type ) {
    case YAML_SCALAR_NODE: {
      char * value = reinterpret_cast<char *>(node->data.scalar.value);
      data->type = Data::TypeString;
      data->val = new std::string(value);
      break;
    }
    case YAML_MAPPING_NODE: {
      data->type = Data::TypeMap;
      std::string ckey;
      yaml_node_pair_t * pair;
      for( pair = node->data.mapping.pairs.start; pair < node->data.mapping.pairs.top; pair++ ) {
        yaml_node_t * keyNode = yaml_document_get_node(document, pair->key);
        yaml_node_t * valueNode = yaml_document_get_node(document, pair->value);
        char * keyValue = reinterpret_cast<char *>(keyNode->data.scalar.value);

        ckey.assign(keyValue);
        child = new Data();
        _createFromYAML(child, document, valueNode);
        data->data.insert(std::pair<std::string,Data *>(ckey,child));
      }
      break;
    }
    case YAML_SEQUENCE_NODE: {
      int len = (node->data.sequence.items.top - node->data.sequence.items.start);
      data->init(Data::TypeArray, len);
      //child = data->array;

      yaml_node_item_t * item;
      for( item = node->data.sequence.items.start; item < node->data.sequence.items.top; item++, child++) {
        //yaml_node_t * valueNode = yaml_document_get_node(document, *item);
        //_createFromYAML(child, document, valueNode);
      }
      break;
    }
    default: {
      throw Exception("Unknown yaml type");
    }
  }
}

Data * Data::createFromYAML(const char * string)
{
  yaml_parser_t parser;
  yaml_document_t document;
  yaml_parser_initialize(&parser);

  const unsigned char * input = reinterpret_cast<const unsigned char *>(string);

  yaml_parser_set_input_string(&parser, input, strlen(string));
  yaml_parser_load(&parser, &document);

  Data * data = new Data();
  data->type = Data::TypeNone;
  _createFromYAML(data, &document, yaml_document_get_root_node(&document));

  yaml_document_delete(&document);
  yaml_parser_delete(&parser);

  return data;
}
#else
Data * Data::createFromYAML(const char * string)
{
  throw Exception("YAML support not enabled");
}
#endif

} // namespace Mustache
<commit_msg>Fix missing case in data conversion for bin #8<commit_after>
#include "data.hpp"

#ifdef MUSTACHE_HAVE_LIBYAML
#include "yaml.h"
#endif

#if defined(MUSTACHE_HAVE_LIBJSON)
#include "json/json.h"
//#include "json/json_inttypes.h"
#include "json/json_object.h"
#include "json/json_tokener.h"
#elif defined(MUSTACHE_HAVE_LIBJANSSON)
#include "jansson.h"
#endif

#include "stdio.h"

namespace mustache {

Data::~Data()
{
  switch( this->type ) {
    case Data::TypeString:
      delete val;
      break;
    case Data::TypeMap:
      if( data.size() > 0 ) {
        Data::Map::iterator dataIt;
        for ( dataIt = data.begin() ; dataIt != data.end(); dataIt++ ) {
          delete (*dataIt).second;
        }
        data.clear();
      }
      break;
    case Data::TypeList:
      if( children.size() > 0 ) {
        Data::List::iterator childrenIt;
        for ( childrenIt = children.begin() ; childrenIt != children.end(); childrenIt++ ) {
          delete *childrenIt;
        }
        children.clear();
      }
    case Data::TypeArray:
      //delete[] array;
      break;
  }
}

void Data::init(Data::Type type, int size) {
  this->type = type;
  this->length = size;
  switch( type ) {
    case Data::TypeString:
      val = new std::string();
      val->reserve(size);
      break;
    case Data::TypeMap:
      // Do nothing
      break;
    case Data::TypeList:
      // Do nothing
      break;
    case Data::TypeArray:
      this->array.reserve(size);
      break;
  }
};

int Data::isEmpty()
{
  int ret = 0;
  switch( type ) {
    default:
    case Data::TypeNone:
      ret = 1;
      break;
    case Data::TypeString:
      if( val == NULL || val->length() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeList:
      if( children.size() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeMap:
      if( data.size() <= 0 ) {
        ret = 1;
      }
      break;
    case Data::TypeArray:
      if( length <= 0 ) {
        ret = 1;
      }
      break;
  }
  return ret;
}

Data * searchStack(Stack<Data *> * stack, std::string * key)
{
  // Resolve up the data stack
  Data * ref = NULL;
  Data::Map::iterator d_it;
  register int i;
  Data ** _stackPos = stack->end();
  for( i = 0; i < stack->size(); i++, _stackPos-- ) {
    if( (*_stackPos) == NULL ) continue;
    if( (*_stackPos)->type == Data::TypeMap ) {
      d_it = (*_stackPos)->data.find(*key);
      if( d_it != (*_stackPos)->data.end() ) {
        ref = d_it->second;
        if( ref != NULL ) {
          break;
        }
      }
    }
  }
  return ref;
}

Data * searchStackNR(Stack<Data *> * stack, std::string * key)
{
  Data * ref = NULL;
  Data * back = stack->back();
  Data::Map::iterator d_it;
  if( back != NULL && back->type == Data::TypeMap ) {
    d_it = back->data.find(*key);
    if( d_it != back->data.end() ) {
      ref = d_it->second;
      if( ref != NULL ) {
        return ref;
      }
    }
  }
  return NULL;
}

// Data integrations

#if defined(MUSTACHE_HAVE_LIBJSON)
static void _createFromJSON(Data * data, struct json_object * object)
{
  Data * child = NULL;
  int cindex = 0;

  switch( json_object_get_type(object) ) {
    case json_type_null:
      data->type = Data::TypeString;
      data->val = new std::string("");
      break;
    case json_type_boolean:
      data->type = Data::TypeString;
      if( 0 == (int) json_object_get_boolean(object) ) {
        data->val = new std::string("");
      } else {
        data->val = new std::string("true");
      }
      break;
    case json_type_double:
    case json_type_int:
    case json_type_string:
      data->type = Data::TypeString;
      data->val = new std::string(json_object_get_string(object));
      break;
    case json_type_object: {
      data->type = Data::TypeMap;
      std::string ckey;
      json_object_object_foreach(object, key, value)
      {
        ckey.assign(key);
        child = new Data();
        _createFromJSON(child, value);
        data->data.insert(std::pair<std::string,Data *>(ckey,child));
      }
      break;
    }
    case json_type_array: {
      int len = json_object_array_length(object);
      data->init(Data::TypeArray, len);

      struct json_object * array_item;
      for( int i = 0; i < len; i++, cindex++ ) {
        array_item = json_object_array_get_idx(object, i);
        data->array[cindex] = child = new Data();
        _createFromJSON(child, array_item);
      }
      break;
    }
    default: {
      throw Exception("Unknown json type");
    }
  }
}

Data * Data::createFromJSON(const char * string)
{
  struct json_object * result = json_tokener_parse((char *) string);
  if( result == NULL ) {
    throw Exception("Invalid JSON data");
  }
  Data * data = new Data();
  data->type = Data::TypeNone;
  _createFromJSON(data, result);
  json_object_put(result);
  return data;
}
#elif defined(MUSTACHE_HAVE_LIBJANNSON)
Data * Data::createFromJSON(const char * string)
{
  throw Exception("JSON support using libjannson not implemented");
}
#else
Data * Data::createFromJSON(const char * string)
{
  throw Exception("JSON support not enabled");
}
#endif

#if defined(MUSTACHE_HAVE_LIBYAML)
static void _createFromYAML(Data * data, yaml_document_t * document, yaml_node_t * node)
{
  Data * child = NULL;
  int cindex = 0;

  switch( node->type ) {
    case YAML_SCALAR_NODE: {
      char * value = reinterpret_cast<char *>(node->data.scalar.value);
      data->type = Data::TypeString;
      data->val = new std::string(value);
      break;
    }
    case YAML_MAPPING_NODE: {
      data->type = Data::TypeMap;
      std::string ckey;
      yaml_node_pair_t * pair;
      for( pair = node->data.mapping.pairs.start; pair < node->data.mapping.pairs.top; pair++ ) {
        yaml_node_t * keyNode = yaml_document_get_node(document, pair->key);
        yaml_node_t * valueNode = yaml_document_get_node(document, pair->value);
        char * keyValue = reinterpret_cast<char *>(keyNode->data.scalar.value);

        ckey.assign(keyValue);
        child = new Data();
        _createFromYAML(child, document, valueNode);
        data->data.insert(std::pair<std::string,Data *>(ckey,child));
      }
      break;
    }
    case YAML_SEQUENCE_NODE: {
      int len = (node->data.sequence.items.top - node->data.sequence.items.start);
      data->init(Data::TypeArray, len);

      yaml_node_item_t * item;
      for( item = node->data.sequence.items.start; item < node->data.sequence.items.top; item++, cindex++) {
        yaml_node_t * valueNode = yaml_document_get_node(document, *item);
        data->array[cindex] = child = new Data();
        _createFromYAML(child, document, valueNode);
      }
      break;
    }
    default: {
      throw Exception("Unknown yaml type");
    }
  }
}

Data * Data::createFromYAML(const char * string)
{
  yaml_parser_t parser;
  yaml_document_t document;
  yaml_parser_initialize(&parser);

  const unsigned char * input = reinterpret_cast<const unsigned char *>(string);

  yaml_parser_set_input_string(&parser, input, strlen(string));
  if( 0 == yaml_parser_load(&parser, &document) ) {
    throw Exception("Failed to parse yaml document");
  }

  Data * data = new Data();
  data->type = Data::TypeNone;
  _createFromYAML(data, &document, yaml_document_get_root_node(&document));

  yaml_document_delete(&document);
  yaml_parser_delete(&parser);

  return data;
}
#else
Data * Data::createFromYAML(const char * string)
{
  throw Exception("YAML support not enabled");
}
#endif

} // namespace Mustache
<|endoftext|>