<commit_before>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
//                           Brad T. Aagaard
//                        U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//

#include <portinfo>

#include "SimpleIOAscii.hh" // implementation of class methods

#include "SpatialDB.hh" // USES SimpleDB
#include "SimpleDB.hh" // USES SimpleDB

#include "SimpleDBData.hh" // USES SimpleDBData
#include "spatialdata/geocoords/CoordSys.hh" // USES CSCart
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/geocoords/CSPicklerAscii.hh" // USES CSPicklerAscii

#include "spatialdata/utils/LineParser.hh" // USES LineParser

#include <fstream> // USES std::ofstream, std::ifstream
#include <iomanip> // USES setw(), setiosflags(), resetiosflags()

#include <stdexcept> // USES std::runtime_error
#include <sstream> // USES std::ostringsgream
#include <strings.h> // USES strcasecmp()
#include <string.h> // USES strlen()
#include <assert.h> // USES assert()

// ----------------------------------------------------------------------
const char* spatialdata::spatialdb::SimpleIOAscii::HEADER =
  "#SPATIAL.ascii";

// ----------------------------------------------------------------------
// Read ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::read(
				   SimpleDBData* pData,
				   spatialdata::geocoords::CoordSys** ppCS)
{ // read
  assert(0 != pData);

  try {
    std::ifstream filein(filename());
    if (!filein.is_open() || !filein.good()) {
      std::ostringstream msg;
      msg << "Could not open spatial database file '" << filename()
	  << "' for reading.\n";
      throw std::runtime_error(msg.str());
    } // if

    utils::LineParser parser(filein, "//");
    parser.eatwhitespace(true);

    std::istringstream buffer;

    buffer.str(parser.next());
    buffer.clear();

    const int headerLen = strlen(HEADER);
    std::string hbuffer;
    hbuffer.resize(headerLen+1);
    buffer.read((char*) hbuffer.c_str(), sizeof(char)*headerLen);
    hbuffer[headerLen] = '\0';
    if (0 != strcasecmp(HEADER, hbuffer.c_str())) {
      std::ostringstream msg;
      msg
	<< "Magic header '" << buffer << "' does not match expected header '"
	<< HEADER << "' in spatial database file '" << filename() << "'.\n";
      throw std::runtime_error(msg.str());
    } // if
    int version = 0;
    buffer >> version;
    switch (version)
      { // switch
      case 1 :
	_readV1(pData, ppCS, filein);
	break;
      default :
	{ // default
	  std::ostringstream msg;
	  msg
	    << "Did not recognize format version " << version
	    << " of spatial database file '" << filename() << "'.\n";
	  throw std::runtime_error(msg.str());
	} // default
      } // switch
    if (!filein.good())
      throw std::runtime_error("Unknown error while reading.");
  } catch (const std::exception& err) {
    std::ostringstream msg;
    msg << "Error occurred while reading spatial database file '"
	<< filename() << "'.\n"
	<< err.what();
    throw std::runtime_error(msg.str());
  } catch (...) {
    std::ostringstream msg;
    msg << "Unknown error occurred while reading spatial database file '"
	<< filename() << "'.\n";
    throw std::runtime_error(msg.str());
  } // try/catch

} // read

// ----------------------------------------------------------------------
// Read ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::_readV1(
				     SimpleDBData* pData,
				     spatialdata::geocoords::CoordSys** ppCS,
				     std::istream& filein)
{ // ReadV1
  assert(0 != pData);
  assert(0 != ppCS);

  // Clear memory and set default values
  delete *ppCS; *ppCS = new spatialdata::geocoords::CSCart();

  utils::LineParser parser(filein, "//");
  parser.eatwhitespace(true);

  std::string token;
  std::istringstream buffer;
  const int maxIgnore = 256;

  buffer.str(parser.next());
  buffer.clear();
  buffer >> token;
  if (0 != strcasecmp(token.c_str(), "SimpleDB")) {
    std::ostringstream msg;
    msg << "Could not parse '" << token << "' into 'SimpleDB'.\n";
    throw std::runtime_error(msg.str());
  } // else

  int numValues = 0;
  int numLocs = 0;
  int spaceDim = 3; // default
  int dataDim = 0;
  std::string* names = 0;
  std::string* units = 0;

  buffer.str(parser.next());
  buffer.clear();
  buffer >> token;
  while (buffer.good() && token != "}") {
    if (0 == strcasecmp(token.c_str(), "num-values")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> numValues;
    } else if (0 == strcasecmp(token.c_str(), "num-locs")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> numLocs;
    } else if (0 == strcasecmp(token.c_str(), "value-names")) {
      if (numValues > 0)
	names = new std::string[numValues];
      else
	throw std::runtime_error("Number of values must be specified BEFORE "
				 "names of values in SimpleDB file.");
      buffer.ignore(maxIgnore, '=');
      for (int iVal=0; iVal < numValues; ++iVal)
	buffer >> names[iVal];
    } else if (0 == strcasecmp(token.c_str(), "value-units")) {
      if (numValues > 0)
	units = new std::string[numValues];
      else
	throw std::runtime_error("Number of values must be specified BEFORE "
				 "units of values in SimpleDB file.");
      buffer.ignore(maxIgnore, '=');
      for (int iVal=0; iVal < numValues; ++iVal)
	buffer >> units[iVal];
    } else if (0 == strcasecmp(token.c_str(), "data-dim")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> dataDim;
    } else if (0 == strcasecmp(token.c_str(), "space-dim")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> spaceDim;
    } else if (0 == strcasecmp(token.c_str(), "cs-data")) {
      buffer.ignore(maxIgnore, '=');
      std::string rbuffer(buffer.str());
      filein.putback('\n');
      filein.clear();
      int i = rbuffer.length()-1;
      while (i >= 0) {
	filein.putback(rbuffer[i]);
	if ('=' == rbuffer[i--])
	  break;
      } // while
      filein.clear();
      spatialdata::geocoords::CSPicklerAscii::unpickle(filein, ppCS);
    } else {
      std::ostringstream msg;
      msg << "Could not parse '" << token << "' into a SimpleDB setting.";
      throw std::runtime_error(msg.str());
    } // else

    buffer.str(parser.next());
    buffer.clear();
    buffer >> token;
  } // while
  if (token != "}" || !filein.good())
    throw std::runtime_error("I/O error while parsing SimpleDB settings.");

  bool ok = true;
  std::ostringstream msg;
  if (0 == numValues) {
    ok = false;
    msg << "SimpleDB settings must include 'num-values'.\n";
  } // if
  if (0 == numLocs) {
    ok = false;
    msg << "SimpleDB settings must include 'num-locs'.\n";
  } // if
  if (0 == names) {
    ok = false;
      msg << "SimpleDB settings must include 'value-names'.\n";
  } // if
  if (0 == units) {
    ok = false;
    msg << "SimpleDB settings must include 'value-units'.\n";
  } // if
  if (!ok)
    throw std::runtime_error(msg.str());

  pData->allocate(numLocs, numValues, spaceDim, dataDim);
  char** cnames = (numValues > 0) ? new char*[numValues] : 0;
  char** cunits = (numValues > 0) ? new char*[numValues] : 0;
  for (int i=0; i < numValues; ++i) {
    cnames[i] = const_cast<char*>(names[i].c_str());
    cunits[i] = const_cast<char*>(units[i].c_str());
  } // for
  pData->names(const_cast<const char**>(cnames), numValues);
  pData->units(const_cast<const char**>(cunits), numValues);

  for (int iLoc=0; iLoc < numLocs; ++iLoc) {
    buffer.str(parser.next());
    buffer.clear();
    double* coordinates = pData->coordinates(iLoc);
    for (int iDim=0; iDim < spaceDim; ++iDim)
      buffer >> coordinates[iDim];
    double* data = pData->data(iLoc);
    for (int iVal=0; iVal < numValues; ++iVal)
      buffer >> data[iVal];
  } // for
  if (!filein.good())
    throw std::runtime_error("I/O error while reading SimpleDB data.");

  // Check compatibility of dimension of data, spatial dimension and
  // number of points
  checkCompatibility(*pData, *ppCS);

  (*ppCS)->initialize();
} // _readV1

// ----------------------------------------------------------------------
// Write ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::write(
				const SimpleDBData& data,
				const spatialdata::geocoords::CoordSys* pCS)
{ // write
  try {
    std::ofstream fileout(filename());
    if (!fileout.is_open() || !fileout.good()) {
      std::ostringstream msg;
      msg << "Could not open spatial database file " << filename()
	  << "for writing.\n";
      throw std::runtime_error(msg.str());
    } // if

    const int version = 1;
    const int numLocs = data.numLocs();
    const int numValues = data.numValues();
    const int spaceDim = data.spaceDim();
    const int dataDim = data.dataDim();

    fileout
      << HEADER << " " << version << "\n"
      << "SimpleDB {\n"
      << "  num-values = " << std::setw(6) << numValues << "\n"
      << "  value-names =";
    for (int iVal=0; iVal < numValues; ++iVal)
      fileout << "  " << data.name(iVal);
    fileout << "\n";
    fileout << "  value-units =";
    for (int iVal=0; iVal < numValues; ++iVal)
      fileout << "  " << data.units(iVal);
    fileout << "\n";
    fileout
      << "  num-locs = " << std::setw(6) << numLocs << "\n"
      << "  data-dim = " << std::setw(4) << dataDim << "\n"
      << "  space-dim = " << std::setw(4) << spaceDim << "\n"
      << "  cs-data = ";
    spatialdata::geocoords::CSPicklerAscii::pickle(fileout, pCS);
    fileout << "}\n";
    if (!fileout.good())
      throw std::runtime_error("I/O error while writing SimpleDB settings.");

    fileout
      << std::resetiosflags(std::ios::fixed)
      << std::setiosflags(std::ios::scientific)
      << std::setprecision(6);
    for (int iLoc=0; iLoc < numLocs; ++iLoc) {
      const double* coordinates = data.coordinates(iLoc);
      for (int iCoord=0; iCoord < spaceDim; ++iCoord)
	fileout << std::setw(14) << coordinates[iCoord];
      const double* values = data.data(iLoc);
      for (int iVal=0; iVal < numValues; ++iVal)
	fileout << std::setw(14) << values[iVal];
      fileout << "\n";
    } // for
    if (!fileout.good())
      throw std::runtime_error("I/O error while writing SimpleDB data.");
  } catch (const std::exception& err) {
    std::ostringstream msg;
    msg << "Error occurred while writing spatial database file '"
	<< filename() << "'.\n"
	<< err.what();
    throw std::runtime_error(msg.str());
  } catch (...) {
    std::ostringstream msg;
    msg << "Unknown error occurred while writing spatial database file '"
	<< filename() << "'.";
    throw std::runtime_error(msg.str());
  } // try/catch
} // write

// End of file
<commit_msg>Fixed a few minor memory leaks.<commit_after>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
//                           Brad T. Aagaard
//                        U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//

#include <portinfo>

#include "SimpleIOAscii.hh" // implementation of class methods

#include "SpatialDB.hh" // USES SimpleDB
#include "SimpleDB.hh" // USES SimpleDB

#include "SimpleDBData.hh" // USES SimpleDBData
#include "spatialdata/geocoords/CoordSys.hh" // USES CSCart
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/geocoords/CSPicklerAscii.hh" // USES CSPicklerAscii

#include "spatialdata/utils/LineParser.hh" // USES LineParser

#include <fstream> // USES std::ofstream, std::ifstream
#include <iomanip> // USES setw(), setiosflags(), resetiosflags()

#include <stdexcept> // USES std::runtime_error
#include <sstream> // USES std::ostringsgream
#include <strings.h> // USES strcasecmp()
#include <string.h> // USES strlen()
#include <assert.h> // USES assert()

// ----------------------------------------------------------------------
const char* spatialdata::spatialdb::SimpleIOAscii::HEADER =
  "#SPATIAL.ascii";

// ----------------------------------------------------------------------
// Read ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::read(
				   SimpleDBData* pData,
				   spatialdata::geocoords::CoordSys** ppCS)
{ // read
  assert(0 != pData);

  try {
    std::ifstream filein(filename());
    if (!filein.is_open() || !filein.good()) {
      std::ostringstream msg;
      msg << "Could not open spatial database file '" << filename()
	  << "' for reading.\n";
      throw std::runtime_error(msg.str());
    } // if

    utils::LineParser parser(filein, "//");
    parser.eatwhitespace(true);

    std::istringstream buffer;

    buffer.str(parser.next());
    buffer.clear();

    const int headerLen = strlen(HEADER);
    std::string hbuffer;
    hbuffer.resize(headerLen+1);
    buffer.read((char*) hbuffer.c_str(), sizeof(char)*headerLen);
    hbuffer[headerLen] = '\0';
    if (0 != strcasecmp(HEADER, hbuffer.c_str())) {
      std::ostringstream msg;
      msg
	<< "Magic header '" << buffer << "' does not match expected header '"
	<< HEADER << "' in spatial database file '" << filename() << "'.\n";
      throw std::runtime_error(msg.str());
    } // if
    int version = 0;
    buffer >> version;
    switch (version)
      { // switch
      case 1 :
	_readV1(pData, ppCS, filein);
	break;
      default :
	{ // default
	  std::ostringstream msg;
	  msg
	    << "Did not recognize format version " << version
	    << " of spatial database file '" << filename() << "'.\n";
	  throw std::runtime_error(msg.str());
	} // default
      } // switch
    if (!filein.good())
      throw std::runtime_error("Unknown error while reading.");
  } catch (const std::exception& err) {
    std::ostringstream msg;
    msg << "Error occurred while reading spatial database file '"
	<< filename() << "'.\n"
	<< err.what();
    throw std::runtime_error(msg.str());
  } catch (...) {
    std::ostringstream msg;
    msg << "Unknown error occurred while reading spatial database file '"
	<< filename() << "'.\n";
    throw std::runtime_error(msg.str());
  } // try/catch

} // read

// ----------------------------------------------------------------------
// Read ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::_readV1(
				     SimpleDBData* pData,
				     spatialdata::geocoords::CoordSys** ppCS,
				     std::istream& filein)
{ // ReadV1
  assert(0 != pData);
  assert(0 != ppCS);

  utils::LineParser parser(filein, "//");
  parser.eatwhitespace(true);

  std::string token;
  std::istringstream buffer;
  const int maxIgnore = 256;

  buffer.str(parser.next());
  buffer.clear();
  buffer >> token;
  if (0 != strcasecmp(token.c_str(), "SimpleDB")) {
    std::ostringstream msg;
    msg << "Could not parse '" << token << "' into 'SimpleDB'.\n";
    throw std::runtime_error(msg.str());
  } // else

  int numValues = 0;
  int numLocs = 0;
  int spaceDim = 3; // default
  int dataDim = 0;
  std::string* names = 0;
  std::string* units = 0;

  buffer.str(parser.next());
  buffer.clear();
  buffer >> token;
  while (buffer.good() && token != "}") {
    if (0 == strcasecmp(token.c_str(), "num-values")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> numValues;
    } else if (0 == strcasecmp(token.c_str(), "num-locs")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> numLocs;
    } else if (0 == strcasecmp(token.c_str(), "value-names")) {
      if (numValues > 0) {
	delete[] names; names = new std::string[numValues];
      } else
	throw std::runtime_error("Number of values must be specified BEFORE "
				 "names of values in SimpleDB file.");
      buffer.ignore(maxIgnore, '=');
      for (int iVal=0; iVal < numValues; ++iVal)
	buffer >> names[iVal];
    } else if (0 == strcasecmp(token.c_str(), "value-units")) {
      if (numValues > 0) {
	delete[] units; units = new std::string[numValues];
      } else
	throw std::runtime_error("Number of values must be specified BEFORE "
				 "units of values in SimpleDB file.");
      buffer.ignore(maxIgnore, '=');
      for (int iVal=0; iVal < numValues; ++iVal)
	buffer >> units[iVal];
    } else if (0 == strcasecmp(token.c_str(), "data-dim")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> dataDim;
    } else if (0 == strcasecmp(token.c_str(), "space-dim")) {
      buffer.ignore(maxIgnore, '=');
      buffer >> spaceDim;
    } else if (0 == strcasecmp(token.c_str(), "cs-data")) {
      buffer.ignore(maxIgnore, '=');
      std::string rbuffer(buffer.str());
      filein.putback('\n');
      filein.clear();
      int i = rbuffer.length()-1;
      while (i >= 0) {
	filein.putback(rbuffer[i]);
	if ('=' == rbuffer[i--])
	  break;
      } // while
      filein.clear();
      spatialdata::geocoords::CSPicklerAscii::unpickle(filein, ppCS);
    } else {
      std::ostringstream msg;
      msg << "Could not parse '" << token << "' into a SimpleDB setting.";
      throw std::runtime_error(msg.str());
    } // else

    buffer.str(parser.next());
    buffer.clear();
    buffer >> token;
  } // while
  if (token != "}" || !filein.good())
    throw std::runtime_error("I/O error while parsing SimpleDB settings.");

  bool ok = true;
  std::ostringstream msg;
  if (0 == numValues) {
    ok = false;
    msg << "SimpleDB settings must include 'num-values'.\n";
  } // if
  if (0 == numLocs) {
    ok = false;
    msg << "SimpleDB settings must include 'num-locs'.\n";
  } // if
  if (0 == names) {
    ok = false;
      msg << "SimpleDB settings must include 'value-names'.\n";
  } // if
  if (0 == units) {
    ok = false;
    msg << "SimpleDB settings must include 'value-units'.\n";
  } // if
  if (!ok)
    throw std::runtime_error(msg.str());

  pData->allocate(numLocs, numValues, spaceDim, dataDim);
  char** cnames = (numValues > 0) ? new char*[numValues] : 0;
  char** cunits = (numValues > 0) ? new char*[numValues] : 0;
  for (int i=0; i < numValues; ++i) {
    cnames[i] = const_cast<char*>(names[i].c_str());
    cunits[i] = const_cast<char*>(units[i].c_str());
  } // for
  pData->names(const_cast<const char**>(cnames), numValues);
  pData->units(const_cast<const char**>(cunits), numValues);
  delete[] names; names = 0;
  delete[] units; units = 0;
  delete[] cnames; cnames = 0;
  delete[] cunits; cunits = 0;

  for (int iLoc=0; iLoc < numLocs; ++iLoc) {
    buffer.str(parser.next());
    buffer.clear();
    double* coordinates = pData->coordinates(iLoc);
    for (int iDim=0; iDim < spaceDim; ++iDim)
      buffer >> coordinates[iDim];
    double* data = pData->data(iLoc);
    for (int iVal=0; iVal < numValues; ++iVal)
      buffer >> data[iVal];
  } // for
  if (!filein.good())
    throw std::runtime_error("I/O error while reading SimpleDB data.");

  // Check compatibility of dimension of data, spatial dimension and
  // number of points
  checkCompatibility(*pData, *ppCS);

  assert(0 != *ppCS);
  (*ppCS)->initialize();
} // _readV1

// ----------------------------------------------------------------------
// Write ascii database file.
void
spatialdata::spatialdb::SimpleIOAscii::write(
				const SimpleDBData& data,
				const spatialdata::geocoords::CoordSys* pCS)
{ // write
  try {
    std::ofstream fileout(filename());
    if (!fileout.is_open() || !fileout.good()) {
      std::ostringstream msg;
      msg << "Could not open spatial database file " << filename()
	  << "for writing.\n";
      throw std::runtime_error(msg.str());
    } // if

    const int version = 1;
    const int numLocs = data.numLocs();
    const int numValues = data.numValues();
    const int spaceDim = data.spaceDim();
    const int dataDim = data.dataDim();

    fileout
      << HEADER << " " << version << "\n"
      << "SimpleDB {\n"
      << "  num-values = " << std::setw(6) << numValues << "\n"
      << "  value-names =";
    for (int iVal=0; iVal < numValues; ++iVal)
      fileout << "  " << data.name(iVal);
    fileout << "\n";
    fileout << "  value-units =";
    for (int iVal=0; iVal < numValues; ++iVal)
      fileout << "  " << data.units(iVal);
    fileout << "\n";
    fileout
      << "  num-locs = " << std::setw(6) << numLocs << "\n"
      << "  data-dim = " << std::setw(4) << dataDim << "\n"
      << "  space-dim = " << std::setw(4) << spaceDim << "\n"
      << "  cs-data = ";
    spatialdata::geocoords::CSPicklerAscii::pickle(fileout, pCS);
    fileout << "}\n";
    if (!fileout.good())
      throw std::runtime_error("I/O error while writing SimpleDB settings.");

    fileout
      << std::resetiosflags(std::ios::fixed)
      << std::setiosflags(std::ios::scientific)
      << std::setprecision(6);
    for (int iLoc=0; iLoc < numLocs; ++iLoc) {
      const double* coordinates = data.coordinates(iLoc);
      for (int iCoord=0; iCoord < spaceDim; ++iCoord)
	fileout << std::setw(14) << coordinates[iCoord];
      const double* values = data.data(iLoc);
      for (int iVal=0; iVal < numValues; ++iVal)
	fileout << std::setw(14) << values[iVal];
      fileout << "\n";
    } // for
    if (!fileout.good())
      throw std::runtime_error("I/O error while writing SimpleDB data.");
  } catch (const std::exception& err) {
    std::ostringstream msg;
    msg << "Error occurred while writing spatial database file '"
	<< filename() << "'.\n"
	<< err.what();
    throw std::runtime_error(msg.str());
  } catch (...) {
    std::ostringstream msg;
    msg << "Unknown error occurred while writing spatial database file '"
	<< filename() << "'.";
    throw std::runtime_error(msg.str());
  } // try/catch
} // write

// End of file
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: frmfmt.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: od $ $Date: 2002-08-28 12:02:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source 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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FRMFMT_HXX
#define _FRMFMT_HXX

#ifndef _FORMAT_HXX
#include <format.hxx>
#endif

class SwDrawContact;
class SwFlyFrm;
class Graphic;
class Point;
class ImageMap;
class IMapObject;
class SwRect;
class SwContact;
class SdrObject;

class SwFrmFmt: public SwFmt
{
    friend class SwDoc;
    friend class SwPageDesc;    //darf den protected CTor rufen.
    friend class SwSwgReader;   // der SW2-Reader auch!
    friend class Sw3IoImp;      // der SW3-Reader auch!

protected:
    SwFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                SwFrmFmt *pDrvdFrm, USHORT nFmtWhich = RES_FRMFMT,
                const USHORT* pWhichRange = 0 )
          : SwFmt( rPool, pFmtNm, (pWhichRange ? pWhichRange : aFrmFmtSetRange),
                pDrvdFrm, nFmtWhich )
    {}

    SwFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                SwFrmFmt *pDrvdFrm, USHORT nFmtWhich = RES_FRMFMT,
                const USHORT* pWhichRange = 0 )
          : SwFmt( rPool, rFmtNm, (pWhichRange ? pWhichRange : aFrmFmtSetRange),
                pDrvdFrm, nFmtWhich )
    {}

public:
    TYPEINFO();     //Bereits in Basisklasse Client drin.

    //Vernichtet alle Frms in aDepend (Frms werden per PTR_CAST erkannt).
    virtual void DelFrms();

    //Erzeugt die Ansichten
    virtual void MakeFrms();

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    virtual void Modify( SfxPoolItem* pOldValue, SfxPoolItem* pNewValue );

    // returnt das IMapObject, das an dem Format (Fly), in der ImageMap
    // an der Point Position definiert ist.
    //  rPoint - teste auf der DocPosition
    //  pFly - optionaler FlyFrame, falls der schon bekannt ist.
    IMapObject* GetIMapObject( const Point& rPoint,
                                const SwFlyFrm *pFly = 0 ) const;

    // Gibt die tatsaechlche Groesse des Frames zurueck bzw. ein leeres
    // Rechteck, wenn kein Layout existiert. Wird pPoint angegeben, dann
    // wird der am dichtesten liegende Frame gesucht.
    SwRect FindLayoutRect( const BOOL bPrtArea = FALSE,
                            const Point* pPoint = 0,
                            const BOOL bCalcFrm = FALSE ) const;

    // Sucht das SdrObject. Der SdrObjUserCall ist Client vom Format.
    // Der UserCall kennt sein SdrObject.
          SwContact *FindContactObj();
    const SwContact *FindContactObj() const
        { return ((SwFrmFmt*)this)->FindContactObj(); }

    // returns the SdrObject, that ist connected to the ContactObject.
    // Only DrawFrmFmts are connected to the "real SdrObject". FlyFrmFmts
    // are connected to a Master and all FlyFrms has the "real SdrObject".
    // "Real SdrObject" has position and a Z-order.
          SdrObject *FindSdrObject();
    const SdrObject *FindSdrObject() const
        { return ((SwFrmFmt*)this)->FindSdrObject(); }

          SdrObject *FindRealSdrObject();
    const SdrObject *FindRealSdrObject() const
        { return ((SwFrmFmt*)this)->FindRealSdrObject(); }

    BOOL IsLowerOf( const SwFrmFmt& rFmt ) const;

    DECL_FIXEDMEMPOOL_NEWDEL(SwFrmFmt)
};

//Das FlyFrame-Format ------------------------------

class SwFlyFrmFmt: public SwFrmFmt
{
    friend class SwDoc;

    //Beide nicht vorhanden.
    SwFlyFrmFmt( const SwFlyFrmFmt &rCpy );
    SwFlyFrmFmt &operator=( const SwFlyFrmFmt &rCpy );

protected:
    SwFlyFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, pFmtNm, pDrvdFrm, RES_FLYFRMFMT )
    {}
    SwFlyFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, rFmtNm, pDrvdFrm, RES_FLYFRMFMT )
    {}

public:
    TYPEINFO();
    ~SwFlyFrmFmt();

    //Erzeugt die Ansichten
    virtual void MakeFrms();

    SwFlyFrm* GetFrm( const Point* pDocPos = 0,
                        const BOOL bCalcFrm = FALSE ) const;

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    virtual BOOL GetInfo( SfxPoolItem& rInfo ) const;

    /** SwFlyFrmFmt::IsBackgroundTransparent - for #99657#

        OD 22.08.2002 - overloading virtual method and its default implementation,
        because format of fly frame provides transparent backgrounds.
        Method determines, if background of fly frame has to be drawn transparent.

        @author OD

        @return true, if background color is transparent, but not "no fill"
        or a existing background graphic is transparent.
    */
    virtual const sal_Bool IsBackgroundTransparent() const;

    DECL_FIXEDMEMPOOL_NEWDEL(SwFlyFrmFmt)
};

//Das DrawFrame-Format -----------------------------

class SwDrawFrmFmt: public SwFrmFmt
{
    friend class SwDoc;

    //Beide nicht vorhanden.
    SwDrawFrmFmt( const SwDrawFrmFmt &rCpy );
    SwDrawFrmFmt &operator=( const SwDrawFrmFmt &rCpy );

protected:
    SwDrawFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, pFmtNm, pDrvdFrm, RES_DRAWFRMFMT )
    {}
    SwDrawFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, rFmtNm, pDrvdFrm, RES_DRAWFRMFMT )
    {}

public:
    TYPEINFO();
    ~SwDrawFrmFmt();

    //DrawObjecte werden aus den Arrays am Layout entfernt. Die DrawObjecte
    //werden als geloescht gekennzeichnet.
    virtual void DelFrms();

    //Anmelden der DrawObjecte in den Arrays am Layout. Loeschkennzeichen
    //werden zurueckgesetzt.
    virtual void MakeFrms();

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    DECL_FIXEDMEMPOOL_NEWDEL(SwDrawFrmFmt);
};

#endif

<commit_msg>#103898# - new method SwFlyFrmFmt::IsBackgroundBrushInherited for transparency<commit_after>/*************************************************************************
 *
 *  $RCSfile: frmfmt.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: od $ $Date: 2002-10-11 11:37:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source 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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FRMFMT_HXX
#define _FRMFMT_HXX

#ifndef _FORMAT_HXX
#include <format.hxx>
#endif

class SwDrawContact;
class SwFlyFrm;
class Graphic;
class Point;
class ImageMap;
class IMapObject;
class SwRect;
class SwContact;
class SdrObject;

class SwFrmFmt: public SwFmt
{
    friend class SwDoc;
    friend class SwPageDesc;    //darf den protected CTor rufen.
    friend class SwSwgReader;   // der SW2-Reader auch!
    friend class Sw3IoImp;      // der SW3-Reader auch!

protected:
    SwFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                SwFrmFmt *pDrvdFrm, USHORT nFmtWhich = RES_FRMFMT,
                const USHORT* pWhichRange = 0 )
          : SwFmt( rPool, pFmtNm, (pWhichRange ? pWhichRange : aFrmFmtSetRange),
                pDrvdFrm, nFmtWhich )
    {}

    SwFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                SwFrmFmt *pDrvdFrm, USHORT nFmtWhich = RES_FRMFMT,
                const USHORT* pWhichRange = 0 )
          : SwFmt( rPool, rFmtNm, (pWhichRange ? pWhichRange : aFrmFmtSetRange),
                pDrvdFrm, nFmtWhich )
    {}

public:
    TYPEINFO();     //Bereits in Basisklasse Client drin.

    //Vernichtet alle Frms in aDepend (Frms werden per PTR_CAST erkannt).
    virtual void DelFrms();

    //Erzeugt die Ansichten
    virtual void MakeFrms();

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    virtual void Modify( SfxPoolItem* pOldValue, SfxPoolItem* pNewValue );

    // returnt das IMapObject, das an dem Format (Fly), in der ImageMap
    // an der Point Position definiert ist.
    //  rPoint - teste auf der DocPosition
    //  pFly - optionaler FlyFrame, falls der schon bekannt ist.
    IMapObject* GetIMapObject( const Point& rPoint,
                                const SwFlyFrm *pFly = 0 ) const;

    // Gibt die tatsaechlche Groesse des Frames zurueck bzw. ein leeres
    // Rechteck, wenn kein Layout existiert. Wird pPoint angegeben, dann
    // wird der am dichtesten liegende Frame gesucht.
    SwRect FindLayoutRect( const BOOL bPrtArea = FALSE,
                            const Point* pPoint = 0,
                            const BOOL bCalcFrm = FALSE ) const;

    // Sucht das SdrObject. Der SdrObjUserCall ist Client vom Format.
    // Der UserCall kennt sein SdrObject.
          SwContact *FindContactObj();
    const SwContact *FindContactObj() const
        { return ((SwFrmFmt*)this)->FindContactObj(); }

    // returns the SdrObject, that ist connected to the ContactObject.
    // Only DrawFrmFmts are connected to the "real SdrObject". FlyFrmFmts
    // are connected to a Master and all FlyFrms has the "real SdrObject".
    // "Real SdrObject" has position and a Z-order.
          SdrObject *FindSdrObject();
    const SdrObject *FindSdrObject() const
        { return ((SwFrmFmt*)this)->FindSdrObject(); }

          SdrObject *FindRealSdrObject();
    const SdrObject *FindRealSdrObject() const
        { return ((SwFrmFmt*)this)->FindRealSdrObject(); }

    BOOL IsLowerOf( const SwFrmFmt& rFmt ) const;

    DECL_FIXEDMEMPOOL_NEWDEL(SwFrmFmt)
};

//Das FlyFrame-Format ------------------------------

class SwFlyFrmFmt: public SwFrmFmt
{
    friend class SwDoc;

    //Beide nicht vorhanden.
    SwFlyFrmFmt( const SwFlyFrmFmt &rCpy );
    SwFlyFrmFmt &operator=( const SwFlyFrmFmt &rCpy );

protected:
    SwFlyFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, pFmtNm, pDrvdFrm, RES_FLYFRMFMT )
    {}
    SwFlyFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, rFmtNm, pDrvdFrm, RES_FLYFRMFMT )
    {}

public:
    TYPEINFO();
    ~SwFlyFrmFmt();

    //Erzeugt die Ansichten
    virtual void MakeFrms();

    SwFlyFrm* GetFrm( const Point* pDocPos = 0,
                        const BOOL bCalcFrm = FALSE ) const;

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    virtual BOOL GetInfo( SfxPoolItem& rInfo ) const;

    /** SwFlyFrmFmt::IsBackgroundTransparent - for #99657#

        OD 22.08.2002 - overloading virtual method and its default implementation,
        because format of fly frame provides transparent backgrounds.
        Method determines, if background of fly frame is transparent.

        @author OD

        @return true, if background color is transparent, but not "no fill"
        or a existing background graphic is transparent.
    */
    virtual const sal_Bool IsBackgroundTransparent() const;

    /** SwFlyFrmFmt::IsBackgroundBrushInherited - for #103898#

        OD 08.10.2002 - method to determine, if the brush for drawing the
        background is "inherited" from its parent/grandparent.
        This is the case, if no background graphic is set and the background
        color is "no fill"/"auto fill"

        @author OD

        @return true, if background brush is "inherited" from parent/grandparent
    */
    const sal_Bool IsBackgroundBrushInherited() const;

    DECL_FIXEDMEMPOOL_NEWDEL(SwFlyFrmFmt)
};

//Das DrawFrame-Format -----------------------------

class SwDrawFrmFmt: public SwFrmFmt
{
    friend class SwDoc;

    //Beide nicht vorhanden.
    SwDrawFrmFmt( const SwDrawFrmFmt &rCpy );
    SwDrawFrmFmt &operator=( const SwDrawFrmFmt &rCpy );

protected:
    SwDrawFrmFmt( SwAttrPool& rPool, const sal_Char* pFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, pFmtNm, pDrvdFrm, RES_DRAWFRMFMT )
    {}
    SwDrawFrmFmt( SwAttrPool& rPool, const String &rFmtNm,
                    SwFrmFmt *pDrvdFrm )
        : SwFrmFmt( rPool, rFmtNm, pDrvdFrm, RES_DRAWFRMFMT )
    {}

public:
    TYPEINFO();
    ~SwDrawFrmFmt();

    //DrawObjecte werden aus den Arrays am Layout entfernt. Die DrawObjecte
    //werden als geloescht gekennzeichnet.
    virtual void DelFrms();

    //Anmelden der DrawObjecte in den Arrays am Layout. Loeschkennzeichen
    //werden zurueckgesetzt.
    virtual void MakeFrms();

    virtual Graphic MakeGraphic( ImageMap* pMap = NULL );

    DECL_FIXEDMEMPOOL_NEWDEL(SwDrawFrmFmt);
};

#endif

<|endoftext|>


<commit_before>// This may look like C code, but it is really -*- C++ -*-
/*
Copyright (C) 1988 Free Software Foundation
    written by Dirk Grunwald (grunwald@cs.uiuc.edu)

This file is part of the GNU C++ Library.  This library is free
software; you can redistribute it and/or modify it under the terms of
the GNU Library General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.  This library is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#ifdef HAVE_CONFIG_H
#include <simgear_config.h>
#endif

#include <iostream>
#include <fstream>
#include "SGSmplhist.hxx"
#include <math.h>

#ifndef HUGE_VAL
#ifdef HUGE
#define HUGE_VAL HUGE
#else
#include <float.h>
#define HUGE_VAL DBL_MAX
#endif
#endif

const int SampleHistogramMinimum = -2;
const int SampleHistogramMaximum = -1;

SampleHistogram::SampleHistogram (double low, double high, double width)
{
  if (high < low)
    {
      double t = high;
      high = low;
      low = t;
    }

  if (width == -1)
    {
      width = (high - low) / 10;
    }

  howManyBuckets = int ((high - low) / width) + 2;
  bucketCount = new int[howManyBuckets];
  bucketLimit = new double[howManyBuckets];
  double lim = low;
  for (int i = 0; i < howManyBuckets; i++)
    {
      bucketCount[i] = 0;
      bucketLimit[i] = lim;
      lim += width;
    }
  bucketLimit[howManyBuckets - 1] = HUGE_VAL;	/* from math.h */
}

SampleHistogram::~SampleHistogram ()
{
  if (howManyBuckets > 0)
    {
      delete[]bucketCount;
      delete[]bucketLimit;
    }
}

void SampleHistogram::operator += (double value)
{
  int i;
  for (i = 0; i < howManyBuckets; i++)
    {
      if (value < bucketLimit[i])
	break;
    }
  bucketCount[i]++;
  this->SampleStatistic::operator += (value);
}

int SampleHistogram::similarSamples (double d)
{
  int i;
  for (i = 0; i < howManyBuckets; i++)
    {
      if (d < bucketLimit[i])
	return (bucketCount[i]);
    }
  return (0);
}

void SampleHistogram::printBuckets (std::ostream & s)
{
  for (int i = 0; i < howManyBuckets; i++)
    {
      if (bucketLimit[i] >= HUGE_VAL)
	{
	  s << "< max : " << bucketCount[i] << "\n";
	}
      else
	{
	  s << "< " << bucketLimit[i] << " : " << bucketCount[i] << "\n";
	}
    }
}

void SampleHistogram::reset ()
{
  this->SampleStatistic::reset ();
  if (howManyBuckets > 0)
    {
      for (register int i = 0; i < howManyBuckets; i++)
	{
	  bucketCount[i] = 0;
	}
    }
}
<commit_msg>Fix a clang warning<commit_after>// This may look like C code, but it is really -*- C++ -*-
/*
Copyright (C) 1988 Free Software Foundation
    written by Dirk Grunwald (grunwald@cs.uiuc.edu)

This file is part of the GNU C++ Library.  This library is free
software; you can redistribute it and/or modify it under the terms of
the GNU Library General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.  This library is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#ifdef HAVE_CONFIG_H
#include <simgear_config.h>
#endif

#include <iostream>
#include <fstream>
#include "SGSmplhist.hxx"
#include <math.h>

#ifndef HUGE_VAL
#ifdef HUGE
#define HUGE_VAL HUGE
#else
#include <float.h>
#define HUGE_VAL DBL_MAX
#endif
#endif

const int SampleHistogramMinimum = -2;
const int SampleHistogramMaximum = -1;

SampleHistogram::SampleHistogram (double low, double high, double width)
{
  if (high < low)
    {
      double t = high;
      high = low;
      low = t;
    }

  if (width == -1)
    {
      width = (high - low) / 10;
    }

  howManyBuckets = int ((high - low) / width) + 2;
  bucketCount = new int[howManyBuckets];
  bucketLimit = new double[howManyBuckets];
  double lim = low;
  for (int i = 0; i < howManyBuckets; i++)
    {
      bucketCount[i] = 0;
      bucketLimit[i] = lim;
      lim += width;
    }
  bucketLimit[howManyBuckets - 1] = HUGE_VAL;	/* from math.h */
}

SampleHistogram::~SampleHistogram ()
{
  if (howManyBuckets > 0)
    {
      delete[]bucketCount;
      delete[]bucketLimit;
    }
}

void SampleHistogram::operator += (double value)
{
  int i;
  for (i = 0; i < howManyBuckets; i++)
    {
      if (value < bucketLimit[i])
	break;
    }
  bucketCount[i]++;
  this->SampleStatistic::operator += (value);
}

int SampleHistogram::similarSamples (double d)
{
  int i;
  for (i = 0; i < howManyBuckets; i++)
    {
      if (d < bucketLimit[i])
	return (bucketCount[i]);
    }
  return (0);
}

void SampleHistogram::printBuckets (std::ostream & s)
{
  for (int i = 0; i < howManyBuckets; i++)
    {
      if (bucketLimit[i] >= HUGE_VAL)
	{
	  s << "< max : " << bucketCount[i] << "\n";
	}
      else
	{
	  s << "< " << bucketLimit[i] << " : " << bucketCount[i] << "\n";
	}
    }
}

void SampleHistogram::reset ()
{
  this->SampleStatistic::reset ();
  if (howManyBuckets > 0)
    {
      for (int i = 0; i < howManyBuckets; i++)
	{
	  bucketCount[i] = 0;
	}
    }
}
<|endoftext|>


<commit_before>/**
 * @file heisenberg.cpp
 * @brief The main c++ file for the DMRG
 *
 *
 * @author Roger Melko
 * @author Ivan Gonzalez
 * @date $Date$
 *
 * $Revision$
 *
 * Elementary DMRG simulation for the Heisenberg chain;
 *  \f$H= \sum_{ij} (S^x_i S^x_j + S^y_i S^y_j +  S^z_i S^z_j ) \f$
 *
 * <ul>
 *  <li> Begins with the "symmetric" infinite system algorithm to build
 *  up the chain
 *  <li> After this, a number of finite system algorithm sweeps are performed
 *  <li> The exact diagonalization performed with Lanczos
 *  <li> The output is the energy as a function of sweep
 *  <li> The code uses Blitz++ to handle tensors and matrices: see http://www.oonumerics.org/blitz/
 *  </ul>
 */
#include "blitz/array.h"
#include "block.h"
#include "matrixManipulation.h"
#include "lanczosDMRG.h"
#include "densityMatrix.h"
#include "main_helpers.h"

int main()
{
    // Read some input from user
    int numberOfHalfSweeps;
    int numberOfSites;
    int m;
    std::cout<<"Enter the number states to keep: ";
    std::cin>>m;
    std::cout<<"Enter the number of sites in the chain: ";
    std::cin>>numberOfSites;
    std::cout<<"Enter the number of FSA sweeps : ";
    std::cin>>numberOfHalfSweeps;

    Block system;   //create the system block
    Block environ;  //create the environment block

    //Below we declare the Blitz++ matrices used by the program
    blitz::Array<double,4> TSR(2,2,2,2);  //tensor product for Hab hamiltonian

    blitz::Array<double,4> Habcd(4,4,4,4); // superblock hamiltonian
    blitz::Array<double,2> Psi(4,4);       // ground state wavefunction
    blitz::Array<double,2> reducedDM(4,4); // reduced density matrix
    blitz::Array<double,2> OO(m,4);        // the truncation matrix
    blitz::Array<double,2> OT(4,m);        // transposed truncation matrix

    blitz::Array<double,2> HAp;   //A' block hamiltonian
    blitz::Array<double,2> SzB;   //Sz(left) operator
    blitz::Array<double,2> SmB;   //Sm(left) operator
    blitz::Array<double,2> SpB;   //Sp(left) operator

    // create the pauli matrices and the 2x2 identity matrix
    blitz::Array<double,2> sigma_z(2,2), sigma_p(2,2), sigma_m(2,2);
    sigma_z = 0.5, 0,
         0, -0.5;
    sigma_p = 0, 1.0,
         0, 0;
    sigma_m = 0, 0,
         1.0, 0;
    blitz::Array<double,2> I2=createIdentityMatrix(2);

    // declare tensor indices according to Blitz++ convention
    blitz::firstIndex i;    blitz::secondIndex j;
    blitz::thirdIndex k;    blitz::fourthIndex l;

    // build the Hamiltonian for two-sites only
    TSR = sigma_z(i,k)*sigma_z(j,l)+ 0.5*sigma_p(i,k)*sigma_m(j,l) +
	0.5*sigma_m(i,k)*sigma_p(j,l);
    system.blockH.resize(4,4);
    system.blockH = reduceM2M2(TSR);

    TSR = sigma_z(i,k)*I2(j,l);
    blitz::Array<double,2> S_z = reduceM2M2(TSR);

    TSR = sigma_m(i,k)*I2(j,l);
    blitz::Array<double,2> S_m = reduceM2M2(TSR);

    TSR = sigma_p(i,k)*I2(j,l);
    blitz::Array<double,2> S_p = reduceM2M2(TSR);
    // done building the Hamiltonian

    /**
     * Infinite system algorithm: build the Hamiltonian from 2 to N-sites
     */
    int statesToKeep=2;      //start with a 2^2=4 state system
    int sitesInSystem=2;     //# sites in the system block

    blitz::Array<double,2> I2st=createIdentityMatrix(4);

    while (sitesInSystem <= (numberOfSites)/2 )
    {
	// build the hamiltonian as a four-index tensor
        Habcd = system.blockH(i,k)*I2st(j,l)+
            I2st(i,k)*system.blockH(j,l)+
            S_z(i,k)*S_z(j,l)+0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);

	// calculate the ground state energy
        double groundStateEnergy=calculateGroundState(Habcd, Psi);

        printGroundStateEnergy(sitesInSystem, sitesInSystem, groundStateEnergy);

	// increase the number of states if you are not at m yet
        statesToKeep= (2*statesToKeep<=m)? 2*statesToKeep : m;

        // calculate the reduced density matrix and truncate
        reducedDM=calculateReducedDensityMatrix(Psi);

        OO.resize(statesToKeep,reducedDM.rows()); //resize transf. matrix
        OT.resize(reducedDM.rows(),statesToKeep); // and its inverse
        OO=truncateReducedDM(reducedDM, statesToKeep); //get transf. matrix
        OT=OO.transpose(blitz::secondDim, blitz::firstDim); //and its inverse

        //transform the operators to new basis
        HAp.resize(statesToKeep, statesToKeep);
        SzB.resize(statesToKeep, statesToKeep);
        SpB.resize(statesToKeep, statesToKeep);
        SmB.resize(statesToKeep, statesToKeep);
        HAp=transformOperator(system.blockH, OT, OO);
        SzB=transformOperator(S_z, OT, OO);
        SpB=transformOperator(S_p, OT, OO);
        SmB=transformOperator(S_m, OT, OO);

        //Hamiltonian for next iteration
        TSR.resize(statesToKeep,2,statesToKeep,2);
        TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
            0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l) ;

        system.blockH.resize(2*statesToKeep,2*statesToKeep);
        system.blockH = reduceM2M2(TSR);

	//redefine identity matrix
	int statesToKeepNext= (2*statesToKeep<=m)? 4*statesToKeep : 2*m;
	I2st.resize(statesToKeepNext, statesToKeepNext);
	I2st = createIdentityMatrix(statesToKeepNext);

	//redefine the operators for next iteration
	S_z.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_z(j,l);
	S_z = reduceM2M2(TSR);

	S_p.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_p(j,l);
	S_p = reduceM2M2(TSR);

	S_m.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_m(j,l);
	S_m = reduceM2M2(TSR);

	// re-prepare superblock matrix, wavefunction and reduced DM
	Habcd.resize(2*statesToKeep,2*statesToKeep,2*statesToKeep,2*statesToKeep);
	Psi.resize(2*statesToKeep,2*statesToKeep);
	reducedDM.resize(2*statesToKeep,2*statesToKeep);

	// make the system one site larger and save it
        system.size = ++sitesInSystem;
        system.ISAwrite(sitesInSystem);

    }//end INFINITE SYSTEM ALGORITHM

    std::cout<<"End of the infinite system algorithm\n";

    /**
     * Finite size algorithm
     */
    {
        // find minimum size of the enviroment
        int minEnviromentSize=calculateMinEnviromentSize(m,numberOfSites);

        // start in the middle of the chain
        int sitesInSystem = numberOfSites/2;
        system.FSAread(sitesInSystem,1);

        for (int halfSweep=0; halfSweep<numberOfHalfSweeps; halfSweep++)
        {
            while (sitesInSystem <= numberOfSites-minEnviromentSize)
            {
                int sitesInEnviroment = numberOfSites - sitesInSystem;

                // read the environment block from disk
                environ.FSAread(sitesInEnviroment,halfSweep);

                // build the hamiltonian as a four-index tensor
                Habcd = environ.blockH(i,k)*I2st(j,l)+
		    I2st(i,k)*system.blockH(j,l)+
                    S_z(i,k)*S_z(j,l)+
                    0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);

                // calculate the ground state energy
                double groundStateEnergy=calculateGroundState(Habcd, Psi);

                if (halfSweep%2 == 0)
                    printGroundStateEnergy(sitesInSystem, sitesInEnviroment,
                            groundStateEnergy);
                else
                    printGroundStateEnergy(sitesInEnviroment, sitesInSystem,
                            groundStateEnergy);

                // calculate the reduced density matrix and truncate
                reducedDM=calculateReducedDensityMatrix(Psi);

                blitz::Array<double,2> OO=truncateReducedDM(reducedDM, m);
                OT=OO.transpose(blitz::secondDim, blitz::firstDim);

                // transform the operators to new basis
                HAp=transformOperator(system.blockH, OT, OO);
                SzB=transformOperator(S_z, OT, OO);
                SpB=transformOperator(S_p, OT, OO);
                SmB=transformOperator(S_m, OT, OO);

                // add spin to the system block only
                TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
                    0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l);
                system.blockH = reduceM2M2(TSR);

                sitesInSystem++;

                system.size = sitesInSystem;
                system.FSAwrite(sitesInSystem,halfSweep);
            }// while

            sitesInSystem = minEnviromentSize;
            system.FSAread(sitesInSystem,halfSweep);

        }// for
    }  // end of the finite size algorithm
    return 0;
} // end main
<commit_msg>Last name changes.<commit_after>/**
 * @file heisenberg.cpp
 * @brief The main c++ file for the DMRG
 *
 *
 * @author Roger Melko
 * @author Ivan Gonzalez
 * @date $Date$
 *
 * $Revision$
 *
 * Elementary DMRG simulation for the Heisenberg chain;
 *  \f$H= \sum_{ij} (S^x_i S^x_j + S^y_i S^y_j +  S^z_i S^z_j ) \f$
 *
 * <ul>
 *  <li> Begins with the "symmetric" infinite system algorithm to build
 *  up the chain
 *  <li> After this, a number of finite system algorithm sweeps are performed
 *  <li> The exact diagonalization performed with Lanczos
 *  <li> The output is the energy as a function of sweep
 *  <li> The code uses Blitz++ to handle tensors and matrices: see http://www.oonumerics.org/blitz/
 *  </ul>
 */
#include "blitz/array.h"
#include "block.h"
#include "matrixManipulation.h"
#include "lanczosDMRG.h"
#include "densityMatrix.h"
#include "main_helpers.h"

int main()
{
    // Read some input from user
    int numberOfHalfSweeps;
    int numberOfSites;
    int m;
    std::cout<<"Enter the number states to keep: ";
    std::cin>>m;
    std::cout<<"Enter the number of sites in the chain: ";
    std::cin>>numberOfSites;
    std::cout<<"Enter the number of FSA sweeps : ";
    std::cin>>numberOfHalfSweeps;

    Block system;   //create the system block
    Block environ;  //create the environment block

    //Below we declare the Blitz++ matrices used by the program
    blitz::Array<double,4> TSR(2,2,2,2);   //tensor product for Hab hamiltonian

    blitz::Array<double,4> Habcd(4,4,4,4); // superblock hamiltonian
    blitz::Array<double,2> Psi(4,4);       // ground state wavefunction
    blitz::Array<double,2> reducedDM(4,4); // reduced density matrix
    blitz::Array<double,2> OO(m,4);        // the truncation matrix
    blitz::Array<double,2> OT(4,m);        // transposed truncation matrix

    blitz::Array<double,2> blockH_p;       //block hamiltonian after transform.
    blitz::Array<double,2> S_z_p;          //S_z operator after transformation
    blitz::Array<double,2> S_m_p;          //S_m operator after transformation
    blitz::Array<double,2> S_p_p;          //S_p operator after transformation

    // create the pauli matrices and the 2x2 identity matrix
    blitz::Array<double,2> sigma_z(2,2), sigma_p(2,2), sigma_m(2,2);
    sigma_z = 0.5, 0,
         0, -0.5;
    sigma_p = 0, 1.0,
         0, 0;
    sigma_m = 0, 0,
         1.0, 0;
    blitz::Array<double,2> I2=createIdentityMatrix(2);

    // declare tensor indices according to Blitz++ convention
    blitz::firstIndex i;    blitz::secondIndex j;
    blitz::thirdIndex k;    blitz::fourthIndex l;

    // build the Hamiltonian for two-sites only
    TSR = sigma_z(i,k)*sigma_z(j,l)+ 0.5*sigma_p(i,k)*sigma_m(j,l) +
	0.5*sigma_m(i,k)*sigma_p(j,l);
    system.blockH.resize(4,4);
    system.blockH = reduceM2M2(TSR);

    TSR = sigma_z(i,k)*I2(j,l);
    blitz::Array<double,2> S_z = reduceM2M2(TSR);

    TSR = sigma_m(i,k)*I2(j,l);
    blitz::Array<double,2> S_m = reduceM2M2(TSR);

    TSR = sigma_p(i,k)*I2(j,l);
    blitz::Array<double,2> S_p = reduceM2M2(TSR);
    // done building the Hamiltonian

    /**
     * Infinite system algorithm: build the Hamiltonian from 2 to N-sites
     */
    int statesToKeep=2;      //start with a 2^2=4 state system
    int sitesInSystem=2;     //# sites in the system block

    blitz::Array<double,2> I2st=createIdentityMatrix(4);

    while (sitesInSystem <= (numberOfSites)/2 )
    {
	// build the hamiltonian as a four-index tensor
        Habcd = system.blockH(i,k)*I2st(j,l)+
            I2st(i,k)*system.blockH(j,l)+
            S_z(i,k)*S_z(j,l)+0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);

	// calculate the ground state energy
        double groundStateEnergy=calculateGroundState(Habcd, Psi);

        printGroundStateEnergy(sitesInSystem, sitesInSystem, groundStateEnergy);

	// increase the number of states if you are not at m yet
        statesToKeep= (2*statesToKeep<=m)? 2*statesToKeep : m;

        // calculate the reduced density matrix and truncate
        reducedDM=calculateReducedDensityMatrix(Psi);

        OO.resize(statesToKeep,reducedDM.rows()); //resize transf. matrix
        OT.resize(reducedDM.rows(),statesToKeep); // and its inverse
        OO=truncateReducedDM(reducedDM, statesToKeep); //get transf. matrix
        OT=OO.transpose(blitz::secondDim, blitz::firstDim); //and its inverse

        //transform the operators to new basis
        blockH_p.resize(statesToKeep, statesToKeep);
        S_z_p.resize(statesToKeep, statesToKeep);
        S_p_p.resize(statesToKeep, statesToKeep);
        S_m_p.resize(statesToKeep, statesToKeep);
        blockH_p=transformOperator(system.blockH, OT, OO);
        S_z_p=transformOperator(S_z, OT, OO);
        S_p_p=transformOperator(S_p, OT, OO);
        S_m_p=transformOperator(S_m, OT, OO);

        //Hamiltonian for next iteration
        TSR.resize(statesToKeep,2,statesToKeep,2);
        TSR = blockH_p(i,k)*I2(j,l) + S_z_p(i,k)*sigma_z(j,l)+
            0.5*S_p_p(i,k)*sigma_m(j,l) + 0.5*S_m_p(i,k)*sigma_p(j,l) ;

        system.blockH.resize(2*statesToKeep,2*statesToKeep);
        system.blockH = reduceM2M2(TSR);

	//redefine identity matrix
	int statesToKeepNext= (2*statesToKeep<=m)? 4*statesToKeep : 2*m;
	I2st.resize(statesToKeepNext, statesToKeepNext);
	I2st = createIdentityMatrix(statesToKeepNext);

	//redefine the operators for next iteration
	S_z.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_z(j,l);
	S_z = reduceM2M2(TSR);

	S_p.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_p(j,l);
	S_p = reduceM2M2(TSR);

	S_m.resize(2*statesToKeep,2*statesToKeep);
	TSR = I2st(i,k)*sigma_m(j,l);
	S_m = reduceM2M2(TSR);

	// re-prepare superblock matrix, wavefunction and reduced DM
	Habcd.resize(2*statesToKeep,2*statesToKeep,2*statesToKeep,2*statesToKeep);
	Psi.resize(2*statesToKeep,2*statesToKeep);
	reducedDM.resize(2*statesToKeep,2*statesToKeep);

	// make the system one site larger and save it
        system.size = ++sitesInSystem;
        system.ISAwrite(sitesInSystem);

    }//end INFINITE SYSTEM ALGORITHM

    std::cout<<"End of the infinite system algorithm\n";

    /**
     * Finite size algorithm
     */
    {
        // find minimum size of the enviroment
        int minEnviromentSize=calculateMinEnviromentSize(m,numberOfSites);

        // start in the middle of the chain
        int sitesInSystem = numberOfSites/2;
        system.FSAread(sitesInSystem,1);

        for (int halfSweep=0; halfSweep<numberOfHalfSweeps; halfSweep++)
        {
            while (sitesInSystem <= numberOfSites-minEnviromentSize)
            {
                int sitesInEnviroment = numberOfSites - sitesInSystem;

                // read the environment block from disk
                environ.FSAread(sitesInEnviroment,halfSweep);

                // build the hamiltonian as a four-index tensor
                Habcd = environ.blockH(i,k)*I2st(j,l)+
		    I2st(i,k)*system.blockH(j,l)+
                    S_z(i,k)*S_z(j,l)+
                    0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);

                // calculate the ground state energy
                double groundStateEnergy=calculateGroundState(Habcd, Psi);

                if (halfSweep%2 == 0)
                    printGroundStateEnergy(sitesInSystem, sitesInEnviroment,
                            groundStateEnergy);
                else
                    printGroundStateEnergy(sitesInEnviroment, sitesInSystem,
                            groundStateEnergy);

                // calculate the reduced density matrix and truncate
                reducedDM=calculateReducedDensityMatrix(Psi);

                blitz::Array<double,2> OO=truncateReducedDM(reducedDM, m);
                OT=OO.transpose(blitz::secondDim, blitz::firstDim);

                // transform the operators to new basis
                blockH_p=transformOperator(system.blockH, OT, OO);
                S_z_p=transformOperator(S_z, OT, OO);
                S_p_p=transformOperator(S_p, OT, OO);
                S_m_p=transformOperator(S_m, OT, OO);

                // add spin to the system block only
                TSR = blockH_p(i,k)*I2(j,l) + S_z_p(i,k)*sigma_z(j,l)+
                    0.5*S_p_p(i,k)*sigma_m(j,l) + 0.5*S_m_p(i,k)*sigma_p(j,l);
                system.blockH = reduceM2M2(TSR);

                sitesInSystem++;

                system.size = sitesInSystem;
                system.FSAwrite(sitesInSystem,halfSweep);
            }// while

            sitesInSystem = minEnviromentSize;
            system.FSAread(sitesInSystem,halfSweep);

        }// for
    }  // end of the finite size algorithm
    return 0;
} // end main
<|endoftext|>


<commit_before>/* Copyright (C) 2005-2011 Fabio Riccardi */

// standard
#include <X11/Xlib.h>
#include <iostream>

// local
#include "LC_JNIUtils.h"
#ifndef AUTO_DEP
#include "javah/com_lightcrafts_platform_linux_LinuxKeyUtil.h"
#endif

using namespace std;
using namespace LightCrafts;

////////// JNI ////////////////////////////////////////////////////////////////

#define LinuxKeyUtil_METHOD(method) \
        name4(Java_,com_lightcrafts_platform_linux_LinuxKeyUtil,_,method)

/**
 * Find the index of the first nonzero bit in the given char, where the least
 * significant bit has index zero.  Used in keysToKeycode().
 */
int indexOfBit(char c) {
    int n;
    for (n=0; n<8; n++) {
        if (c & 0x01) {
            return n;
        }
        c = c >> 1;
    }
}

/**
 * Determine the KeyCode of the first pressed key in the 32-character keys
 * array returned from XQueryKeymap.
 */
KeyCode keysToKeycode(char *keys) {
    int n;
    for (n=0; n<32; n++) {
        if (keys[n] != 0) {
            return 8 * n + indexOfBit(keys[n]);
        }
    }
    return 0;
}

/**
 * The X11 Display reference is a global variable, initialized in the first
 * call to isKeyPressed().
 */
Display *display = NULL;

/**
 * Detect whether the key corresponding to the given virtual key code is
 * currently pressed.  (For ASCII characters, the virtual key code is just
 * the ASCII code.)
 */
JNIEXPORT jboolean JNICALL LinuxKeyUtil_METHOD(isKeyPressed)
    ( JNIEnv *env, jclass, jint keyCode )
{
    if (display == NULL) {
        display = XOpenDisplay(NULL);
    }
    if (display == NULL) {
        cerr << "LinuxPlatform cannot connect to X server "
             << XDisplayName(NULL)
             << endl;
        return false;
    }
    char keys[32];
    XQueryKeymap(display, keys);

    KeyCode code = keysToKeycode(keys);

    KeySym sym = XKeycodeToKeysym(display, code, 0);

    bool pressed = keyCode == sym;
#ifdef DEBUG
    cout << "keyCode " << keyCode << " is ";
    if ( ! pressed ) {
        cout << "not ";
    }
    cout << "pressed" << endl;
#endif
    return pressed;
}
/* vim:set et sw=4 ts=4: */
<commit_msg>Linux - Replace deprecated XKeycodeToKeysym with XkbKeycodeToKeysym<commit_after>/* Copyright (C) 2005-2011 Fabio Riccardi */

// standard
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <iostream>

// local
#include "LC_JNIUtils.h"
#ifndef AUTO_DEP
#include "javah/com_lightcrafts_platform_linux_LinuxKeyUtil.h"
#endif

using namespace std;
using namespace LightCrafts;

////////// JNI ////////////////////////////////////////////////////////////////

#define LinuxKeyUtil_METHOD(method) \
        name4(Java_,com_lightcrafts_platform_linux_LinuxKeyUtil,_,method)

/**
 * Find the index of the first nonzero bit in the given char, where the least
 * significant bit has index zero.  Used in keysToKeycode().
 */
int indexOfBit(char c) {
    int n;
    for (n=0; n<8; n++) {
        if (c & 0x01) {
            return n;
        }
        c = c >> 1;
    }
}

/**
 * Determine the KeyCode of the first pressed key in the 32-character keys
 * array returned from XQueryKeymap.
 */
KeyCode keysToKeycode(char *keys) {
    int n;
    for (n=0; n<32; n++) {
        if (keys[n] != 0) {
            return 8 * n + indexOfBit(keys[n]);
        }
    }
    return 0;
}

/**
 * The X11 Display reference is a global variable, initialized in the first
 * call to isKeyPressed().
 */
Display *display = NULL;

/**
 * Detect whether the key corresponding to the given virtual key code is
 * currently pressed.  (For ASCII characters, the virtual key code is just
 * the ASCII code.)
 */
JNIEXPORT jboolean JNICALL LinuxKeyUtil_METHOD(isKeyPressed)
    ( JNIEnv *env, jclass, jint keyCode )
{
    if (display == NULL) {
        display = XOpenDisplay(NULL);
    }
    if (display == NULL) {
        cerr << "LinuxPlatform cannot connect to X server "
             << XDisplayName(NULL)
             << endl;
        return false;
    }
    char keys[32];
    XQueryKeymap(display, keys);

    KeyCode code = keysToKeycode(keys);

    KeySym sym = XkbKeycodeToKeysym(display, code, 0, 0);

    bool pressed = keyCode == sym;
#ifdef DEBUG
    cout << "keyCode " << keyCode << " is ";
    if ( ! pressed ) {
        cout << "not ";
    }
    cout << "pressed" << endl;
#endif
    return pressed;
}
/* vim:set et sw=4 ts=4: */
<|endoftext|>


<commit_before>#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <string>
#include <libgen.h>

int main(int argc, char *argv[]) {
  std::string input_filename = std::string(argv[1]);
  std::string input_basename = std::string(basename(argv[1]));
  Pix *image = pixRead(input_filename.c_str());
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, NULL, NULL);
  printf("Found %d textline image components.\n", boxes->n);
  for (int i = 0; i < boxes->n; i++) {
    BOX* box = boxaGetBox(boxes, i, L_CLONE);
    PIX* pixd= pixClipRectangle(image, box, NULL);
    int lastindex = input_basename.find_last_of(".");
    std::string basename = input_basename.substr(0, lastindex);
    std::string extension = input_basename.substr(lastindex + 1, 3);
    char* linefilename = (char*)malloc((basename.length()+strlen("-line_extract-00000.ext")+1)*sizeof(char));
    sprintf(linefilename, "%s-line_extract-%05d.%s", basename.c_str(), i, extension.c_str());
    pixWrite(linefilename, pixd, IFF_DEFAULT);
    pixDestroy(&pixd);
    boxDestroy(&box);
    free(linefilename);
  }
  return 0;
}
<commit_msg>edited for changes to ocular<commit_after>#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <string>
#include <libgen.h>

int main(int argc, char *argv[]) {
  if(argc != 3) { printf("USAGE: %s imagefile outputdir", argv[0]); }

  std::string input_filename = std::string(argv[1]);
  std::string input_basename = std::string(basename(argv[1]));

  std::string output_dir = std::string(argv[2]);

  Pix *image = pixRead(input_filename.c_str());
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, NULL, NULL);
  printf("Found %d textline image components.\n", boxes->n);

  int lastindex = input_basename.find_last_of(".");
  std::string basename = input_basename.substr(0, lastindex).c_str();
  std::string extension = input_basename.substr(lastindex + 1).c_str();
  std::string outdir = output_dir.c_str();
  int linedirLen = outdir.length()+1+basename.length()+strlen("-line_extract_")+extension.length()+1;
  char* linedir = (char*)malloc(linedirLen*sizeof(char));
  sprintf(linedir, "%s/%s-line_extract_%s", output_dir.c_str(), basename.c_str(), extension.c_str());
  printf("Writing to directory [%s].  If this fails, try:\n    mkdir -p %s\n\n\n", linedir, linedir);

  for (int i = 0; i < boxes->n; i++) {
    BOX* box = boxaGetBox(boxes, i, L_CLONE);
    PIX* pixd= pixClipRectangle(image, box, NULL);

    char* linefilename = (char*)malloc((linedirLen+strlen("/line00.")+extension.length()+1)*sizeof(char));
    sprintf(linefilename, "%s/line%02d.%s", linedir, i, extension.c_str());
    printf("  Writing %s\n", linefilename);
    pixWrite(linefilename, pixd, IFF_DEFAULT);
    pixDestroy(&pixd);
    boxDestroy(&box);
    free(linefilename);
  }
  return 0;
}
<|endoftext|>


<commit_before>//===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#if defined(_MSC_VER)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#endif

#include "lldb/Host/common/TCPSocket.h"

#include "lldb/Host/Config.h"
#include "lldb/Host/MainLoop.h"
#include "lldb/Utility/Log.h"

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#endif

#if defined(LLVM_ON_WIN32)
#include <winsock2.h>
#endif

#ifdef LLVM_ON_WIN32
#define CLOSE_SOCKET closesocket
#else
#define CLOSE_SOCKET ::close
#endif

using namespace lldb;
using namespace lldb_private;

namespace {
const int kType = SOCK_STREAM;
}

TCPSocket::TCPSocket(bool should_close, bool child_processes_inherit)
    : Socket(ProtocolTcp, should_close, child_processes_inherit) {}

TCPSocket::TCPSocket(NativeSocket socket, const TCPSocket &listen_socket)
    : Socket(ProtocolTcp, listen_socket.m_should_close_fd,
             listen_socket.m_child_processes_inherit) {
  m_socket = socket;
}

TCPSocket::TCPSocket(NativeSocket socket, bool should_close,
                     bool child_processes_inherit)
    : Socket(ProtocolTcp, should_close, child_processes_inherit) {
  m_socket = socket;
}

TCPSocket::~TCPSocket() { CloseListenSockets(); }

bool TCPSocket::IsValid() const {
  return m_socket != kInvalidSocketValue || m_listen_sockets.size() != 0;
}

// Return the port number that is being used by the socket.
uint16_t TCPSocket::GetLocalPortNumber() const {
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetPort();
  } else if (!m_listen_sockets.empty()) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_listen_sockets.begin()->first, sock_addr,
                      &sock_addr_len) == 0)
      return sock_addr.GetPort();
  }
  return 0;
}

std::string TCPSocket::GetLocalIPAddress() const {
  // We bound to port zero, so we need to figure out which port we actually
  // bound to
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetIPAddress();
  }
  return "";
}

uint16_t TCPSocket::GetRemotePortNumber() const {
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetPort();
  }
  return 0;
}

std::string TCPSocket::GetRemoteIPAddress() const {
  // We bound to port zero, so we need to figure out which port we actually
  // bound to
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetIPAddress();
  }
  return "";
}

Error TCPSocket::CreateSocket(int domain) {
  Error error;
  if (IsValid())
    error = Close();
  if (error.Fail())
    return error;
  m_socket = Socket::CreateSocket(domain, kType, IPPROTO_TCP,
                                  m_child_processes_inherit, error);
  return error;
}

Error TCPSocket::Connect(llvm::StringRef name) {

  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
  if (log)
    log->Printf("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());

  Error error;
  std::string host_str;
  std::string port_str;
  int32_t port = INT32_MIN;
  if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
    return error;

  auto addresses = lldb_private::SocketAddress::GetAddressInfo(
      host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
  for (auto address : addresses) {
    error = CreateSocket(address.GetFamily());
    if (error.Fail())
      continue;

    address.SetPort(port);

    if (-1 == ::connect(GetNativeSocket(), &address.sockaddr(),
                        address.GetLength())) {
      CLOSE_SOCKET(GetNativeSocket());
      continue;
    }

    SetOptionNoDelay();

    error.Clear();
    return error;
  }

  error.SetErrorString("Failed to connect port");
  return error;
}

Error TCPSocket::Listen(llvm::StringRef name, int backlog) {
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
  if (log)
    log->Printf("TCPSocket::%s (%s)", __FUNCTION__, name.data());

  Error error;
  std::string host_str;
  std::string port_str;
  int32_t port = INT32_MIN;
  if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
    return error;

  auto addresses = lldb_private::SocketAddress::GetAddressInfo(
      host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
  for (auto address : addresses) {
    int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP,
                                  m_child_processes_inherit, error);
    if (error.Fail()) {
      error.Clear();
      continue;
    }

    // enable local address reuse
    int option_value = 1;
    set_socket_option_arg_type option_value_p =
        reinterpret_cast<get_socket_option_arg_type>(&option_value);
    ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, option_value_p,
                 sizeof(option_value));

    address.SetPort(port);

    int err = ::bind(fd, &address.sockaddr(), address.GetLength());
    if (-1 != err)
      err = ::listen(fd, backlog);

    if (-1 == err) {
      CLOSE_SOCKET(fd);
      continue;
    }

    if (port == 0) {
      socklen_t sa_len = address.GetLength();
      if (getsockname(fd, &address.sockaddr(), &sa_len) == 0)
        port = address.GetPort();
    }
    m_listen_sockets[fd] = address;
  }

  if (m_listen_sockets.size() == 0)
    error.SetErrorString("Failed to connect port");
  return error;
}

void TCPSocket::CloseListenSockets() {
  for (auto socket : m_listen_sockets)
  CLOSE_SOCKET(socket.first);
  m_listen_sockets.clear();
}

Error TCPSocket::Accept(Socket *&conn_socket) {
  Error error;
  if (m_listen_sockets.size() == 0) {
    error.SetErrorString("No open listening sockets!");
    return error;
  }

  int sock = -1;
  int listen_sock = -1;
  lldb_private::SocketAddress AcceptAddr;
  MainLoop accept_loop;
  std::vector<MainLoopBase::ReadHandleUP> handles;
  for (auto socket : m_listen_sockets) {
    auto fd = socket.first;
    auto inherit = this->m_child_processes_inherit;
    auto io_sp = IOObjectSP(new TCPSocket(socket.first, false, inherit));
    handles.emplace_back(accept_loop.RegisterReadObject(
        io_sp, [fd, inherit, &sock, &AcceptAddr, &error,
                        &listen_sock](MainLoopBase &loop) {
          socklen_t sa_len = AcceptAddr.GetMaxLength();
          sock = AcceptSocket(fd, &AcceptAddr.sockaddr(), &sa_len, inherit,
                              error);
          listen_sock = fd;
          loop.RequestTermination();
        }, error));
    if (error.Fail())
      return error;
  }

  bool accept_connection = false;
  std::unique_ptr<TCPSocket> accepted_socket;
  // Loop until we are happy with our connection
  while (!accept_connection) {
    accept_loop.Run();

    if (error.Fail())
        return error;

    lldb_private::SocketAddress &AddrIn = m_listen_sockets[listen_sock];
    if (!AddrIn.IsAnyAddr() && AcceptAddr != AddrIn) {
      CLOSE_SOCKET(sock);
      llvm::errs() << llvm::formatv(
          "error: rejecting incoming connection from {0} (expecting {1})",
          AcceptAddr.GetIPAddress(), AddrIn.GetIPAddress());
      continue;
    }
    accept_connection = true;
    accepted_socket.reset(new TCPSocket(sock, *this));
  }

  if (!accepted_socket)
    return error;

  // Keep our TCP packets coming without any delays.
  accepted_socket->SetOptionNoDelay();
  error.Clear();
  conn_socket = accepted_socket.release();
  return error;
}

int TCPSocket::SetOptionNoDelay() {
  return SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
}

int TCPSocket::SetOptionReuseAddress() {
  return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
}
<commit_msg>One more attempt to fix the broken bots.<commit_after>//===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#if defined(_MSC_VER)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#endif

#include "lldb/Host/common/TCPSocket.h"

#include "lldb/Host/Config.h"
#include "lldb/Host/MainLoop.h"
#include "lldb/Utility/Log.h"

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#endif

#if defined(LLVM_ON_WIN32)
#include <winsock2.h>
#endif

#ifdef LLVM_ON_WIN32
#define CLOSE_SOCKET closesocket
typedef const char *set_socket_option_arg_type;
#else
#define CLOSE_SOCKET ::close
typedef const void *set_socket_option_arg_type;
#endif

using namespace lldb;
using namespace lldb_private;

namespace {
const int kType = SOCK_STREAM;
}

TCPSocket::TCPSocket(bool should_close, bool child_processes_inherit)
    : Socket(ProtocolTcp, should_close, child_processes_inherit) {}

TCPSocket::TCPSocket(NativeSocket socket, const TCPSocket &listen_socket)
    : Socket(ProtocolTcp, listen_socket.m_should_close_fd,
             listen_socket.m_child_processes_inherit) {
  m_socket = socket;
}

TCPSocket::TCPSocket(NativeSocket socket, bool should_close,
                     bool child_processes_inherit)
    : Socket(ProtocolTcp, should_close, child_processes_inherit) {
  m_socket = socket;
}

TCPSocket::~TCPSocket() { CloseListenSockets(); }

bool TCPSocket::IsValid() const {
  return m_socket != kInvalidSocketValue || m_listen_sockets.size() != 0;
}

// Return the port number that is being used by the socket.
uint16_t TCPSocket::GetLocalPortNumber() const {
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetPort();
  } else if (!m_listen_sockets.empty()) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_listen_sockets.begin()->first, sock_addr,
                      &sock_addr_len) == 0)
      return sock_addr.GetPort();
  }
  return 0;
}

std::string TCPSocket::GetLocalIPAddress() const {
  // We bound to port zero, so we need to figure out which port we actually
  // bound to
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetIPAddress();
  }
  return "";
}

uint16_t TCPSocket::GetRemotePortNumber() const {
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetPort();
  }
  return 0;
}

std::string TCPSocket::GetRemoteIPAddress() const {
  // We bound to port zero, so we need to figure out which port we actually
  // bound to
  if (m_socket != kInvalidSocketValue) {
    SocketAddress sock_addr;
    socklen_t sock_addr_len = sock_addr.GetMaxLength();
    if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
      return sock_addr.GetIPAddress();
  }
  return "";
}

Error TCPSocket::CreateSocket(int domain) {
  Error error;
  if (IsValid())
    error = Close();
  if (error.Fail())
    return error;
  m_socket = Socket::CreateSocket(domain, kType, IPPROTO_TCP,
                                  m_child_processes_inherit, error);
  return error;
}

Error TCPSocket::Connect(llvm::StringRef name) {

  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
  if (log)
    log->Printf("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());

  Error error;
  std::string host_str;
  std::string port_str;
  int32_t port = INT32_MIN;
  if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
    return error;

  auto addresses = lldb_private::SocketAddress::GetAddressInfo(
      host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
  for (auto address : addresses) {
    error = CreateSocket(address.GetFamily());
    if (error.Fail())
      continue;

    address.SetPort(port);

    if (-1 == ::connect(GetNativeSocket(), &address.sockaddr(),
                        address.GetLength())) {
      CLOSE_SOCKET(GetNativeSocket());
      continue;
    }

    SetOptionNoDelay();

    error.Clear();
    return error;
  }

  error.SetErrorString("Failed to connect port");
  return error;
}

Error TCPSocket::Listen(llvm::StringRef name, int backlog) {
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
  if (log)
    log->Printf("TCPSocket::%s (%s)", __FUNCTION__, name.data());

  Error error;
  std::string host_str;
  std::string port_str;
  int32_t port = INT32_MIN;
  if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
    return error;

  auto addresses = lldb_private::SocketAddress::GetAddressInfo(
      host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
  for (auto address : addresses) {
    int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP,
                                  m_child_processes_inherit, error);
    if (error.Fail()) {
      error.Clear();
      continue;
    }

    // enable local address reuse
    int option_value = 1;
    set_socket_option_arg_type option_value_p =
        reinterpret_cast<get_socket_option_arg_type>(&option_value);
    ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, option_value_p,
                 sizeof(option_value));

    address.SetPort(port);

    int err = ::bind(fd, &address.sockaddr(), address.GetLength());
    if (-1 != err)
      err = ::listen(fd, backlog);

    if (-1 == err) {
      CLOSE_SOCKET(fd);
      continue;
    }

    if (port == 0) {
      socklen_t sa_len = address.GetLength();
      if (getsockname(fd, &address.sockaddr(), &sa_len) == 0)
        port = address.GetPort();
    }
    m_listen_sockets[fd] = address;
  }

  if (m_listen_sockets.size() == 0)
    error.SetErrorString("Failed to connect port");
  return error;
}

void TCPSocket::CloseListenSockets() {
  for (auto socket : m_listen_sockets)
  CLOSE_SOCKET(socket.first);
  m_listen_sockets.clear();
}

Error TCPSocket::Accept(Socket *&conn_socket) {
  Error error;
  if (m_listen_sockets.size() == 0) {
    error.SetErrorString("No open listening sockets!");
    return error;
  }

  int sock = -1;
  int listen_sock = -1;
  lldb_private::SocketAddress AcceptAddr;
  MainLoop accept_loop;
  std::vector<MainLoopBase::ReadHandleUP> handles;
  for (auto socket : m_listen_sockets) {
    auto fd = socket.first;
    auto inherit = this->m_child_processes_inherit;
    auto io_sp = IOObjectSP(new TCPSocket(socket.first, false, inherit));
    handles.emplace_back(accept_loop.RegisterReadObject(
        io_sp, [fd, inherit, &sock, &AcceptAddr, &error,
                        &listen_sock](MainLoopBase &loop) {
          socklen_t sa_len = AcceptAddr.GetMaxLength();
          sock = AcceptSocket(fd, &AcceptAddr.sockaddr(), &sa_len, inherit,
                              error);
          listen_sock = fd;
          loop.RequestTermination();
        }, error));
    if (error.Fail())
      return error;
  }

  bool accept_connection = false;
  std::unique_ptr<TCPSocket> accepted_socket;
  // Loop until we are happy with our connection
  while (!accept_connection) {
    accept_loop.Run();

    if (error.Fail())
        return error;

    lldb_private::SocketAddress &AddrIn = m_listen_sockets[listen_sock];
    if (!AddrIn.IsAnyAddr() && AcceptAddr != AddrIn) {
      CLOSE_SOCKET(sock);
      llvm::errs() << llvm::formatv(
          "error: rejecting incoming connection from {0} (expecting {1})",
          AcceptAddr.GetIPAddress(), AddrIn.GetIPAddress());
      continue;
    }
    accept_connection = true;
    accepted_socket.reset(new TCPSocket(sock, *this));
  }

  if (!accepted_socket)
    return error;

  // Keep our TCP packets coming without any delays.
  accepted_socket->SetOptionNoDelay();
  error.Clear();
  conn_socket = accepted_socket.release();
  return error;
}

int TCPSocket::SetOptionNoDelay() {
  return SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
}

int TCPSocket::SetOptionReuseAddress() {
  return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using std::cout;
using std::cerr;
using std::endl;
using std::string;

bool checkParameters(int argc, char* argv[]);

const string REPLACEMENT_ALGORITHMS[3] = {"lru", "clock", "fifo"},
             PAGING_METHODS[2] = {"d", "p"};
const int NUM_REPLACEMENT_ALGORITHMS = 3, NUM_PAGING_METHODS = 2;
int main(int argc, char* argv[])
{
  std::ifstream programListIn, programTraceIn;
  std::ofstream fileOut;
  int pageSize;
  string replacementAlgorithm, pagingMethod;

  if(checkParameters(argc, argv))
  {
    //Everything is cool

  }

  return 0;
}

bool checkParameters(int argc, char* argv[])
{
  std::ifstream programListIn, programTraceIn;
  std::ofstream fileOut;
  bool pageSizeGood = false, replacementAlgorithmGood = false, pagingMethodGood = false;
  int pageSize;
  string replacementAlgorithm, pagingMethod;

  //Valid number of arguments, but some may not make sense
  if(argc == 6)
  {
    //Check to see if programList exists
    programListIn.open(argv[1]);

    if(programListIn)
    {
      //File1 exists

      //Check to see if file2 exists
      programTraceIn.open(argv[2]);

      if(programTraceIn)
      {
        //File2 exists
        try
        {
          pageSize = std::stoi(argv[3]);

          //Page Size is numeric, but is it 1,2,4,8,16?
          for(int i = 0; i < 5; i++)
          {
            if(pageSize == std::pow(2, i))
            {
              //It is
              pageSizeGood = true;
              break;
            }
          }

          if(pageSizeGood)
          {
            //Page size is good

            //Check replacement algorithm
            replacementAlgorithm = argv[4];

            for(int i = 0; i < NUM_REPLACEMENT_ALGORITHMS; i++)
            {
              if(replacementAlgorithm == REPLACEMENT_ALGORITHMS[i])
              {
                //Replacement algorithm is valid
                replacementAlgorithmGood = true;
                break;
              }
            }

            if(replacementAlgorithmGood)
            {
              //Replacement algorithm is valid

              //Check paging method
              pagingMethod = argv[5];

              for(int i = 0; i < NUM_PAGING_METHODS; i++)
              {
                if(pagingMethod == PAGING_METHODS[i])
                {
                  pagingMethodGood = true;
                  break;
                }
              }

              if(pagingMethodGood)
              {
                //Paging Method is valid

                //All Options are valid
                return true;
              }
              else
              {
                //Paging Method is invalid
                cerr << "Error: Paging Method " << pagingMethod << " is invalid." << endl;
              }
            }
            else
            {
              //It's not
              cerr << "Error: Page Replacement Algorithm " << replacementAlgorithm << " is invalid." << endl;
            }

          }
          else
          {
            //Page size isn't good
            cerr << "Error: " << pageSize << " is not a power of two." << endl;
          }

        }
        catch(std::invalid_argument e)
        {
          //Third argument is not an integer
          cerr << "Error: " << pageSize << " is not a numeric type." << endl;
        }
      }
      else
      {
        //It doesn't
        cerr << "Error: File " << argv[2] << ".txt does not exist. Please provide a valid filename" << endl;
      }
    }
    else
    {
      //It doesn't
      cerr << "Error: File " << argv[1] << ".txt does not exist. Please provide a valid filename" << endl;
    }
  }
  else
  {
    //Invalid number of parameters
    cerr << "Error: Invalid number of parameters provided. Please provide exactly 5 arguments." << endl;
  }

  cerr << endl;
  cerr << "Usage " << argv[0] << " programListFile programTraceFile numPages replacementAlgorithm pagingMethod" << endl;
  cerr << endl;
  cerr << "programListFile:      The file containing the program list" << endl;
  cerr << "programTraceFile:     The file containing the program trace" << endl;
  cerr << "numPages:             The number of pages. Must be in the set {1,2,4,8,16}" << endl;
  cerr << "replacementAlgorithm: The replacement algorithm to use. Must be in the set {lru, fifo, clock}" << endl;
  cerr << "pagingMethod:         The paging method to use. Must be in the set {p(Prepaging), d(Demand Paging)}" << endl;

  return false;
}<commit_msg>Initialized pertinent parameters<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::stoi;

bool checkParameters(int argc, char* argv[]);

const string REPLACEMENT_ALGORITHMS[3] = {"lru", "clock", "fifo"},
             PAGING_METHODS[2] = {"d", "p"};
const int NUM_REPLACEMENT_ALGORITHMS = 3, NUM_PAGING_METHODS = 2;
int main(int argc, char* argv[])
{
  std::ifstream programListIn, programTraceIn;
  std::ofstream fileOut;
  int pageSize;
  string replacementAlgorithm, pagingMethod;

  if(checkParameters(argc, argv))
  {
    //Everything is cool
    programListIn.open(argv[1]);
    programTraceIn.open(argv[2]);
    pageSize = stoi(argv[3]);
    replacementAlgorithm = argv[4];
    pagingMethod = argv[5];

    //We're ready to roll
  }

  return 0;
}

bool checkParameters(int argc, char* argv[])
{
  std::ifstream programListIn, programTraceIn;
  std::ofstream fileOut;
  bool pageSizeGood = false, replacementAlgorithmGood = false, pagingMethodGood = false;
  int pageSize;
  string replacementAlgorithm, pagingMethod;

  //Valid number of arguments, but some may not make sense
  if(argc == 6)
  {
    //Check to see if programList exists
    programListIn.open(argv[1]);

    if(programListIn)
    {
      //File1 exists

      //Check to see if file2 exists
      programTraceIn.open(argv[2]);

      if(programTraceIn)
      {
        //File2 exists
        try
        {
          pageSize = std::stoi(argv[3]);

          //Page Size is numeric, but is it 1,2,4,8,16?
          for(int i = 0; i < 5; i++)
          {
            if(pageSize == std::pow(2, i))
            {
              //It is
              pageSizeGood = true;
              break;
            }
          }

          if(pageSizeGood)
          {
            //Page size is good

            //Check replacement algorithm
            replacementAlgorithm = argv[4];

            for(int i = 0; i < NUM_REPLACEMENT_ALGORITHMS; i++)
            {
              if(replacementAlgorithm == REPLACEMENT_ALGORITHMS[i])
              {
                //Replacement algorithm is valid
                replacementAlgorithmGood = true;
                break;
              }
            }

            if(replacementAlgorithmGood)
            {
              //Replacement algorithm is valid

              //Check paging method
              pagingMethod = argv[5];

              for(int i = 0; i < NUM_PAGING_METHODS; i++)
              {
                if(pagingMethod == PAGING_METHODS[i])
                {
                  pagingMethodGood = true;
                  break;
                }
              }

              if(pagingMethodGood)
              {
                //Paging Method is valid

                //All Options are valid
                return true;
              }
              else
              {
                //Paging Method is invalid
                cerr << "Error: Paging Method " << pagingMethod << " is invalid." << endl;
              }
            }
            else
            {
              //It's not
              cerr << "Error: Page Replacement Algorithm " << replacementAlgorithm << " is invalid." << endl;
            }

          }
          else
          {
            //Page size isn't good
            cerr << "Error: " << pageSize << " is not a power of two." << endl;
          }

        }
        catch(std::invalid_argument e)
        {
          //Third argument is not an integer
          cerr << "Error: " << pageSize << " is not a numeric type." << endl;
        }
      }
      else
      {
        //It doesn't
        cerr << "Error: File " << argv[2] << ".txt does not exist. Please provide a valid filename" << endl;
      }
    }
    else
    {
      //It doesn't
      cerr << "Error: File " << argv[1] << ".txt does not exist. Please provide a valid filename" << endl;
    }
  }
  else
  {
    //Invalid number of parameters
    cerr << "Error: Invalid number of parameters provided. Please provide exactly 5 arguments." << endl;
  }

  cerr << endl;
  cerr << "Usage " << argv[0] << " programListFile programTraceFile numPages replacementAlgorithm pagingMethod" << endl;
  cerr << endl;
  cerr << "programListFile:      The file containing the program list" << endl;
  cerr << "programTraceFile:     The file containing the program trace" << endl;
  cerr << "numPages:             The number of pages. Must be in the set {1,2,4,8,16}" << endl;
  cerr << "replacementAlgorithm: The replacement algorithm to use. Must be in the set {lru, fifo, clock}" << endl;
  cerr << "pagingMethod:         The paging method to use. Must be in the set {p(Prepaging), d(Demand Paging)}" << endl;

  return false;
}<|endoftext|>