<commit_before>#include "dataFile.h"
#include "debugUtils.h"
#include "boost/filesystem.hpp"

DataFile::DataFile(void)
    : file(0)
    , fileIsOpen(false)
{
}

DataFile::DataFile(const std::string& in_filename)
    : file(0)
{
    open(in_filename);
}

DataFile::~DataFile(void)
{
    close();
}

void DataFile::writeScalar(const std::string& name, const double x)
{
    require_file_open();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(0, NULL, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
}

double DataFile::readScalar(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) !=  0) {
        throw debugException("DataFile::readScalar: \"" + name + "\" is not a scalar.");
    }

    double value;
    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
    H5Dclose(dataset);
    return value;
}

void DataFile::writeVector(const std::string& name, const dvector& v)
{
    require_file_open();

    hsize_t dims = v.size();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
    H5Dclose(dataset);
}

dvector DataFile::readVector(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw debugException("DataFile::readVector: \"" + name + "\" is not a 1D array.");
    }

    hsize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvector values(N);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
    H5Dclose(dataset);
    return values;
}

void DataFile::writeArray2D(const std::string& name, const Cantera::Array2D& y)
{
    require_file_open();

    // Take the transpose because Array2D is column-major
    Cantera::Array2D yt(y.nColumns(), y.nRows());
    for (size_t i=0; i<y.nRows(); i++) {
        for (size_t j=0; j<y.nColumns(); j++) {
            yt(j,i) = y(i,j);
        }
    }

    hsize_t dims[2];
    dims[0] = yt.nColumns(); // TODO: double check the order of these
    dims[1] = yt.nRows();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(2, dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &yt.data()[0]);
    H5Dclose(dataset);
}

Cantera::Array2D DataFile::readArray2D(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 2) {
        throw debugException("DataFile::readVector: \"" + name + "\" is not a 1D array.");
    }

    hsize_t ndim = 2;
    vector<hsize_t> dimensions(2);
    H5Sget_simple_extent_dims(dataspace, &dimensions[0], &ndim);

    Cantera::Array2D y(dimensions[0], dimensions[1]);
    Cantera::Array2D yt(dimensions[1], dimensions[0]);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &yt.data()[0]);
    H5Dclose(dataset);

    // Take the transpose because Array2D is column-major
    for (size_t i=0; i<yt.nRows(); i++) {
        for (size_t j=0; j<yt.nColumns(); j++) {
            y(j,i) = yt(i,j);
        }
    }

    return y;
}

void DataFile::open(const std::string& in_filename)
{
    if (file) {
        close();
    }

    filename = in_filename;
    if (boost::filesystem::exists(filename)) {
        file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    } else {
        file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    }
    fileIsOpen = true;
}

void DataFile::close()
{
    if (file) {
        H5Fclose(file);
        file = 0;
    }
    fileIsOpen = false;
}

void DataFile::require_file_open()
{
    if (!file) {
        throw debugException(
            "Can't access DataFile object: H5File object not initialized.");
    } else if (!fileIsOpen) {
        throw debugException(
            "Can't access DataFile object: H5File is closed.");
    }
}

hid_t DataFile::get_dataset(const std::string& name, hid_t datatype, hid_t dataspace)
{
    if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
        H5Ldelete(file, name.c_str(), H5P_DEFAULT);
    }
    return H5Dcreate(file, name.c_str(), datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}

void dataFileTest()
{
    // Test reading from / writing to an HDF5 data file
    DataFile f("test.h5");
    double x;
    f.writeScalar("x", x);

    dvector v(10);
    for (int i=0; i<10; i++) {
        v[i] = i*i;
    }

    f.writeVector("v", v);

    Array2D A(3,7);
    for (int i=0; i<3; i++) {
        for (int j=0; j<7; j++) {
            A(i,j) = 10*i + j;
        }
    }

    cout << "rows:" << A.nRows() << endl;
    cout << "cols:" << A.nColumns() << endl;

    f.writeArray2D("A", A);
    f.close();

    DataFile g("test.h5");
    dvector w = g.readVector("v");
    for (int i=0; i<w.size(); i++) {
        std::cout << w[i] << std::endl;
    }

    std::cout << g.readScalar("x") << std::endl;
    std::cout << g.readArray2D("A") << std::endl;

    g.close();
}
<commit_msg>Eliminated some warnings in the HDF5 test function<commit_after>#include "dataFile.h"
#include "debugUtils.h"
#include "boost/filesystem.hpp"

DataFile::DataFile(void)
    : file(0)
    , fileIsOpen(false)
{
}

DataFile::DataFile(const std::string& in_filename)
    : file(0)
{
    open(in_filename);
}

DataFile::~DataFile(void)
{
    close();
}

void DataFile::writeScalar(const std::string& name, const double x)
{
    require_file_open();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(0, NULL, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
}

double DataFile::readScalar(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) !=  0) {
        throw debugException("DataFile::readScalar: \"" + name + "\" is not a scalar.");
    }

    double value;
    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
    H5Dclose(dataset);
    return value;
}

void DataFile::writeVector(const std::string& name, const dvector& v)
{
    require_file_open();

    hsize_t dims = v.size();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
    H5Dclose(dataset);
}

dvector DataFile::readVector(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw debugException("DataFile::readVector: \"" + name + "\" is not a 1D array.");
    }

    hsize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvector values(N);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
    H5Dclose(dataset);
    return values;
}

void DataFile::writeArray2D(const std::string& name, const Cantera::Array2D& y)
{
    require_file_open();

    // Take the transpose because Array2D is column-major
    Cantera::Array2D yt(y.nColumns(), y.nRows());
    for (size_t i=0; i<y.nRows(); i++) {
        for (size_t j=0; j<y.nColumns(); j++) {
            yt(j,i) = y(i,j);
        }
    }

    hsize_t dims[2];
    dims[0] = yt.nColumns(); // TODO: double check the order of these
    dims[1] = yt.nRows();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(2, dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &yt.data()[0]);
    H5Dclose(dataset);
}

Cantera::Array2D DataFile::readArray2D(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 2) {
        throw debugException("DataFile::readVector: \"" + name + "\" is not a 1D array.");
    }

    hsize_t ndim = 2;
    vector<hsize_t> dimensions(2);
    H5Sget_simple_extent_dims(dataspace, &dimensions[0], &ndim);

    Cantera::Array2D y(dimensions[0], dimensions[1]);
    Cantera::Array2D yt(dimensions[1], dimensions[0]);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &yt.data()[0]);
    H5Dclose(dataset);

    // Take the transpose because Array2D is column-major
    for (size_t i=0; i<yt.nRows(); i++) {
        for (size_t j=0; j<yt.nColumns(); j++) {
            y(j,i) = yt(i,j);
        }
    }

    return y;
}

void DataFile::open(const std::string& in_filename)
{
    if (file) {
        close();
    }

    filename = in_filename;
    if (boost::filesystem::exists(filename)) {
        file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    } else {
        file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    }
    fileIsOpen = true;
}

void DataFile::close()
{
    if (file) {
        H5Fclose(file);
        file = 0;
    }
    fileIsOpen = false;
}

void DataFile::require_file_open()
{
    if (!file) {
        throw debugException(
            "Can't access DataFile object: H5File object not initialized.");
    } else if (!fileIsOpen) {
        throw debugException(
            "Can't access DataFile object: H5File is closed.");
    }
}

hid_t DataFile::get_dataset(const std::string& name, hid_t datatype, hid_t dataspace)
{
    if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
        H5Ldelete(file, name.c_str(), H5P_DEFAULT);
    }
    return H5Dcreate(file, name.c_str(), datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}

void dataFileTest()
{
    // Test reading from / writing to an HDF5 data file
    DataFile f("test.h5");
    double x = 9001;
    f.writeScalar("x", x);

    dvector v(10);
    for (size_t i=0; i<v.size(); i++) {
        v[i] = i*i;
    }

    f.writeVector("v", v);

    Array2D A(3,7);
    for (size_t i=0; i<A.nRows(); i++) {
        for (size_t j=0; j<A.nColumns(); j++) {
            A(i,j) = 10*i + j;
        }
    }

    std::cout << "rows:" << A.nRows() << std::endl;
    std::cout << "cols:" << A.nColumns() << std::endl;

    f.writeArray2D("A", A);
    f.close();

    DataFile g("test.h5");
    dvector w = g.readVector("v");
    for (size_t i=0; i<w.size(); i++) {
        std::cout << w[i] << std::endl;
    }

    std::cout << g.readScalar("x") << std::endl;
    std::cout << g.readArray2D("A") << std::endl;

    g.close();
}
<|endoftext|>


<commit_before>#include <array>
#include <cstdint>
#include <string>
#include <iostream>

#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>

#include "chip8.h"
#include "res/blip.h"
#include "qsfmlcanvas.h"
#include "emulatorcanvas.h"

std::array<sf::Keyboard::Key, 16> layout{{
    sf::Keyboard::Num1,
    sf::Keyboard::Num2,
    sf::Keyboard::Num3,
    sf::Keyboard::Q,
    sf::Keyboard::W,
    sf::Keyboard::E,
    sf::Keyboard::A,
    sf::Keyboard::S,
    sf::Keyboard::D,
    sf::Keyboard::X,
    sf::Keyboard::Y,
    sf::Keyboard::C,
    sf::Keyboard::Num4,
    sf::Keyboard::R,
    sf::Keyboard::F,
    sf::Keyboard::V
  }};

int main(int argc, char* argv[])
{
  /*
  // initialize chip8 module
  chip8 emu;
  */

  // parse arguments
  std::string filename;
  if (argc > 1) {
    filename = argv[1];
  } else {
    std::cerr << "No filename given!" << std::endl;
    return 1;
  }

  QApplication App(argc, argv);

  QFrame* MainFrame = new QFrame;
  MainFrame->setWindowTitle("SC8E");
  MainFrame->resize(680, 360);
  MainFrame->show();

  EmulatorCanvas* SFMLView = new EmulatorCanvas(MainFrame, QPoint(20, 20), QSize(640, 320), filename);
  SFMLView->show();

  return App.exec();

}
<commit_msg>Changed main window to the QMainWindow class<commit_after>#include <array>
#include <cstdint>
#include <string>
#include <iostream>

#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>

#include <QMainWindow>

#include "chip8.h"
#include "res/blip.h"
#include "qsfmlcanvas.h"
#include "emulatorcanvas.h"

std::array<sf::Keyboard::Key, 16> layout{{
    sf::Keyboard::Num1,
    sf::Keyboard::Num2,
    sf::Keyboard::Num3,
    sf::Keyboard::Q,
    sf::Keyboard::W,
    sf::Keyboard::E,
    sf::Keyboard::A,
    sf::Keyboard::S,
    sf::Keyboard::D,
    sf::Keyboard::X,
    sf::Keyboard::Y,
    sf::Keyboard::C,
    sf::Keyboard::Num4,
    sf::Keyboard::R,
    sf::Keyboard::F,
    sf::Keyboard::V
  }};

int main(int argc, char* argv[])
{
  /*
  // initialize chip8 module
  chip8 emu;
  */

  // parse arguments
  std::string filename;
  if (argc > 1) {
    filename = argv[1];
  } else {
    std::cerr << "No filename given!" << std::endl;
    return 1;
  }

  QApplication App(argc, argv);

  QMainWindow* MainFrame = new QMainWindow;
  MainFrame->setWindowTitle("SC8E");
  MainFrame->resize(640, 345);
  MainFrame->show();

  EmulatorCanvas* SFMLView = new EmulatorCanvas(MainFrame, QPoint(0, 25), QSize(640, 320), filename);
  SFMLView->show();

  return App.exec();

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cxxtools/envsubst.h>
#include <cxxtools/log.h>
#include <stdlib.h>

log_define("cxxtools.envsubst")

namespace cxxtools
{

namespace
{
  bool isVarChar(char ch)
  {
    return (ch >= 'a' && ch <= 'z')
        || (ch >= 'A' && ch <= 'Z')
        || (ch >= '0' && ch <= '9')
        || (ch == '_');
  }
}

EnvSubstSyntaxError::EnvSubstSyntaxError(const std::string& msg)
  : std::runtime_error(msg)
  { }

void EnvSubst::parse(char ch)
{
  switch (_state)
  {
    case state_0:
        if (ch == '\\')
          _state = state_esc;
        else if (ch == '$')
          _state = state_varbegin;
        else
          _ev.onChar(ch);
        break;

    case state_esc:
        _ev.onChar(ch);
        _state = state_0;
        break;

    case state_varbegin:
        if (isVarChar(ch))
        {
          _varname = ch;
          _state = state_varname;
        }
        else if (ch == '{')
        {
          _varname.clear();
          _state = state_bvarname;
        }
        else
          throw EnvSubstSyntaxError("expected env variable");
        break;

    case state_varname:
        if (isVarChar(ch))
          _varname += ch;
        else
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
          }
          else
            log_debug("envvar \"" << _varname << "\" is not set");

          if (ch == '\\')
            _state = state_esc;
          else
          {
            _ev.onChar(ch);
            _state = state_0;
          }
        }
        break;

    case state_bvarname:
        if (ch == '}')
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
          }
          else
            log_debug("envvar \"" << _varname << "\" is not set");

          _state = state_0;
        }
        else if (ch == ':')
        {
          _state = state_subst0;
        }
        else
          _varname += ch;
        break;

    case state_subst0:
        if (ch == '-')
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
            _state = state_nosubst;
          }
          else
          {
            log_debug("envvar \"" << _varname << "\" is not set");
            _next = new EnvSubst(_ev);
            _state = state_subst;
          }
        }
        else
          throw EnvSubstSyntaxError(std::string("invalid substitution operaror ") + ch);
        break;

    case state_subst:
        if (ch == '}' && !_next->isInBracket())
        {
          _next->parseEnd();
          delete _next;
          _next = 0;
          _state = state_0;
        }
        else
          _next->parse(ch);
        break;

    case state_nosubst:
        if (ch == '}')
          _state = state_0;
        break;
  }

}

void EnvSubst::parseEnd()
{
  switch (_state)
  {
    case state_0:
        break;

    case state_esc:
    case state_varbegin:
    case state_bvarname:
    case state_subst0:
    case state_subst:
    case state_nosubst:
        throw EnvSubstSyntaxError("unexpected end");

    case state_varname:
        const char* e = ::getenv(_varname.c_str());
        if (e)
        {
          log_debug("envvar \"" << _varname << "\": " << e);
          while (*e)
            _ev.onChar(*e++);
        }
        else
          log_debug("envvar \"" << _varname << "\" is not set");

        _state = state_0;
        break;
  }

}

std::string envSubst(const std::string& str)
{
  struct Ev : public EnvSubst::Ev
  {
    std::string ret;
    void onChar(char ch)
    {
      ret += ch;
    }
  } ev;

  log_debug("envSubst(\"" << str << '"');

  EnvSubst es(ev);
  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
    es.parse(*it);
  es.parseEnd();

  log_debug("envSubst => \"" << ev.ret << '"');

  return ev.ret;
}

}
<commit_msg>better error message when string could not be parsed in envsubst<commit_after>/*
 * Copyright (C) 2015 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cxxtools/envsubst.h>
#include <cxxtools/log.h>
#include <stdlib.h>

log_define("cxxtools.envsubst")

namespace cxxtools
{

namespace
{
  bool isVarChar(char ch)
  {
    return (ch >= 'a' && ch <= 'z')
        || (ch >= 'A' && ch <= 'Z')
        || (ch >= '0' && ch <= '9')
        || (ch == '_');
  }
}

EnvSubstSyntaxError::EnvSubstSyntaxError(const std::string& msg)
  : std::runtime_error(msg)
  { }

void EnvSubst::parse(char ch)
{
  switch (_state)
  {
    case state_0:
        if (ch == '\\')
          _state = state_esc;
        else if (ch == '$')
          _state = state_varbegin;
        else
          _ev.onChar(ch);
        break;

    case state_esc:
        _ev.onChar(ch);
        _state = state_0;
        break;

    case state_varbegin:
        if (isVarChar(ch))
        {
          _varname = ch;
          _state = state_varname;
        }
        else if (ch == '{')
        {
          _varname.clear();
          _state = state_bvarname;
        }
        else
        {
          throw EnvSubstSyntaxError(
            std::string("expected env variable after \'$\', got '").append(1, ch).append(1, '\''));
        }

        break;

    case state_varname:
        if (isVarChar(ch))
          _varname += ch;
        else
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
          }
          else
            log_debug("envvar \"" << _varname << "\" is not set");

          if (ch == '\\')
            _state = state_esc;
          else
          {
            _ev.onChar(ch);
            _state = state_0;
          }
        }
        break;

    case state_bvarname:
        if (ch == '}')
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
          }
          else
            log_debug("envvar \"" << _varname << "\" is not set");

          _state = state_0;
        }
        else if (ch == ':')
        {
          _state = state_subst0;
        }
        else
          _varname += ch;
        break;

    case state_subst0:
        if (ch == '-')
        {
          const char* e = ::getenv(_varname.c_str());
          if (e)
          {
            log_debug("envvar \"" << _varname << "\": " << e);
            while (*e)
              _ev.onChar(*e++);
            _state = state_nosubst;
          }
          else
          {
            log_debug("envvar \"" << _varname << "\" is not set");
            _next = new EnvSubst(_ev);
            _state = state_subst;
          }
        }
        else
        {
          throw EnvSubstSyntaxError(
            std::string("invalid substitution operator ").append(1, ch));
        }

        break;

    case state_subst:
        if (ch == '}' && !_next->isInBracket())
        {
          _next->parseEnd();
          delete _next;
          _next = 0;
          _state = state_0;
        }
        else
          _next->parse(ch);
        break;

    case state_nosubst:
        if (ch == '}')
          _state = state_0;
        break;
  }

}

void EnvSubst::parseEnd()
{
  switch (_state)
  {
    case state_0:
        break;

    case state_esc:
    case state_varbegin:
    case state_bvarname:
    case state_subst0:
    case state_subst:
    case state_nosubst:
        throw EnvSubstSyntaxError("unexpected end");

    case state_varname:
        const char* e = ::getenv(_varname.c_str());
        if (e)
        {
          log_debug("envvar \"" << _varname << "\": " << e);
          while (*e)
            _ev.onChar(*e++);
        }
        else
          log_debug("envvar \"" << _varname << "\" is not set");

        _state = state_0;
        break;
  }

}

std::string envSubst(const std::string& str)
{
  struct Ev : public EnvSubst::Ev
  {
    std::string ret;
    void onChar(char ch)
    {
      ret += ch;
    }
  } ev;

  log_debug("envSubst(\"" << str << '"');

  try
  {
    EnvSubst es(ev);
    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
      es.parse(*it);
    es.parseEnd();
  }
  catch (const EnvSubstSyntaxError& e)
  {
    throw EnvSubstSyntaxError(
        std::string("failed to parse \"")
            .append(str)
            .append("\": ")
            .append(+ e.what()));
  }

  log_debug("envSubst => \"" << ev.ret << '"');

  return ev.ret;
}

}
<|endoftext|>


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

/** @file
 * Definition of the MSHRQueue.
 */

#include "mem/cache/miss/mshr_queue.hh"
#include "sim/eventq.hh"

using namespace std;

MSHRQueue::MSHRQueue(int num_mshrs, int reserve)
    : numMSHRs(num_mshrs + reserve - 1), numReserve(reserve)
{
    allocated = 0;
    inServiceMSHRs = 0;
    allocatedTargets = 0;
    registers = new MSHR[numMSHRs];
    for (int i = 0; i < numMSHRs; ++i) {
        freeList.push_back(&registers[i]);
    }
}

MSHRQueue::~MSHRQueue()
{
    delete [] registers;
}

MSHR*
MSHRQueue::findMatch(Addr addr) const
{
    MSHR::ConstIterator i = allocatedList.begin();
    MSHR::ConstIterator end = allocatedList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr == addr) {
            return mshr;
        }
    }
    return NULL;
}

bool
MSHRQueue::findMatches(Addr addr, vector<MSHR*>& matches) const
{
    // Need an empty vector
    assert(matches.empty());
    bool retval = false;
    MSHR::ConstIterator i = allocatedList.begin();
    MSHR::ConstIterator end = allocatedList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr == addr) {
            retval = true;
            matches.push_back(mshr);
        }
    }
    return retval;

}

MSHR*
MSHRQueue::findPending(Packet * &pkt) const
{
    MSHR::ConstIterator i = pendingList.begin();
    MSHR::ConstIterator end = pendingList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr < pkt->getAddr()) {
            if (mshr->addr + mshr->pkt->getSize() > pkt->getAddr()) {
                return mshr;
            }
        } else {
            if (pkt->getAddr() + pkt->getSize() > mshr->addr) {
                return mshr;
            }
        }

        //need to check destination address for copies.
        //TEMP NOT DOING COPIES
#if 0
        if (mshr->pkt->cmd == Copy) {
            Addr dest = mshr->pkt->dest;
            if (dest < pkt->addr) {
                if (dest + mshr->pkt->size > pkt->addr) {
                    return mshr;
                }
            } else {
                if (pkt->addr + pkt->size > dest) {
                    return mshr;
                }
            }
        }
#endif
    }
    return NULL;
}

MSHR*
MSHRQueue::allocate(Packet * &pkt, int size)
{
    Addr aligned_addr = pkt->getAddr() & ~((Addr)size - 1);
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();

    if (!pkt->needsResponse()) {
        mshr->allocateAsBuffer(pkt);
    } else {
        assert(size !=0);
        mshr->allocate(pkt->cmd, aligned_addr, size, pkt);
        allocatedTargets += 1;
    }
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);

    allocated += 1;
    return mshr;
}

MSHR*
MSHRQueue::allocateFetch(Addr addr, int size, Packet * &target)
{
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();
    mshr->allocate(Packet::ReadReq, addr, size, target);
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);

    allocated += 1;
    return mshr;
}

MSHR*
MSHRQueue::allocateTargetList(Addr addr, int size)
{
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();
    Packet * dummy;
    mshr->allocate(Packet::ReadReq, addr, size, dummy);
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->inService = true;
    ++inServiceMSHRs;
    ++allocated;
    return mshr;
}

void
MSHRQueue::deallocate(MSHR* mshr)
{
    deallocateOne(mshr);
}

MSHR::Iterator
MSHRQueue::deallocateOne(MSHR* mshr)
{
    MSHR::Iterator retval = allocatedList.erase(mshr->allocIter);
    freeList.push_front(mshr);
    allocated--;
    allocatedTargets -= mshr->getNumTargets();
    if (mshr->inService) {
        inServiceMSHRs--;
    } else {
        pendingList.erase(mshr->readyIter);
    }
    mshr->deallocate();
    return retval;
}

void
MSHRQueue::moveToFront(MSHR *mshr)
{
    if (!mshr->inService) {
        assert(mshr == *(mshr->readyIter));
        pendingList.erase(mshr->readyIter);
        mshr->readyIter = pendingList.insert(pendingList.begin(), mshr);
    }
}

void
MSHRQueue::markInService(MSHR* mshr)
{
    //assert(mshr == pendingList.front());
    if (!mshr->pkt->needsResponse()) {
        assert(mshr->getNumTargets() == 0);
        deallocate(mshr);
        return;
    }
    mshr->inService = true;
    pendingList.erase(mshr->readyIter);
    //mshr->readyIter = NULL;
    inServiceMSHRs += 1;
    //pendingList.pop_front();
}

void
MSHRQueue::markPending(MSHR* mshr, Packet::Command cmd)
{
    //assert(mshr->readyIter == NULL);
    mshr->pkt->cmd = cmd;
    mshr->pkt->flags &= ~SATISFIED;
    mshr->inService = false;
    --inServiceMSHRs;
    /**
     * @ todo might want to add rerequests to front of pending list for
     * performance.
     */
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);
}

void
MSHRQueue::squash(int threadNum)
{
    MSHR::Iterator i = allocatedList.begin();
    MSHR::Iterator end = allocatedList.end();
    for (; i != end;) {
        MSHR *mshr = *i;
        if (mshr->threadNum == threadNum) {
            while (mshr->hasTargets()) {
                Packet * target = mshr->getTarget();
                mshr->popTarget();

                assert(target->req->getThreadNum() == threadNum);
                target = NULL;
            }
            assert(!mshr->hasTargets());
            assert(mshr->ntargets==0);
            if (!mshr->inService) {
                i = deallocateOne(mshr);
            } else {
                //mshr->pkt->flags &= ~CACHE_LINE_FILL;
                ++i;
            }
        } else {
            ++i;
        }
    }
}
<commit_msg>Another thread number removed<commit_after>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Erik Hallnor
 */

/** @file
 * Definition of the MSHRQueue.
 */

#include "mem/cache/miss/mshr_queue.hh"
#include "sim/eventq.hh"

using namespace std;

MSHRQueue::MSHRQueue(int num_mshrs, int reserve)
    : numMSHRs(num_mshrs + reserve - 1), numReserve(reserve)
{
    allocated = 0;
    inServiceMSHRs = 0;
    allocatedTargets = 0;
    registers = new MSHR[numMSHRs];
    for (int i = 0; i < numMSHRs; ++i) {
        freeList.push_back(&registers[i]);
    }
}

MSHRQueue::~MSHRQueue()
{
    delete [] registers;
}

MSHR*
MSHRQueue::findMatch(Addr addr) const
{
    MSHR::ConstIterator i = allocatedList.begin();
    MSHR::ConstIterator end = allocatedList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr == addr) {
            return mshr;
        }
    }
    return NULL;
}

bool
MSHRQueue::findMatches(Addr addr, vector<MSHR*>& matches) const
{
    // Need an empty vector
    assert(matches.empty());
    bool retval = false;
    MSHR::ConstIterator i = allocatedList.begin();
    MSHR::ConstIterator end = allocatedList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr == addr) {
            retval = true;
            matches.push_back(mshr);
        }
    }
    return retval;

}

MSHR*
MSHRQueue::findPending(Packet * &pkt) const
{
    MSHR::ConstIterator i = pendingList.begin();
    MSHR::ConstIterator end = pendingList.end();
    for (; i != end; ++i) {
        MSHR *mshr = *i;
        if (mshr->addr < pkt->getAddr()) {
            if (mshr->addr + mshr->pkt->getSize() > pkt->getAddr()) {
                return mshr;
            }
        } else {
            if (pkt->getAddr() + pkt->getSize() > mshr->addr) {
                return mshr;
            }
        }

        //need to check destination address for copies.
        //TEMP NOT DOING COPIES
#if 0
        if (mshr->pkt->cmd == Copy) {
            Addr dest = mshr->pkt->dest;
            if (dest < pkt->addr) {
                if (dest + mshr->pkt->size > pkt->addr) {
                    return mshr;
                }
            } else {
                if (pkt->addr + pkt->size > dest) {
                    return mshr;
                }
            }
        }
#endif
    }
    return NULL;
}

MSHR*
MSHRQueue::allocate(Packet * &pkt, int size)
{
    Addr aligned_addr = pkt->getAddr() & ~((Addr)size - 1);
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();

    if (!pkt->needsResponse()) {
        mshr->allocateAsBuffer(pkt);
    } else {
        assert(size !=0);
        mshr->allocate(pkt->cmd, aligned_addr, size, pkt);
        allocatedTargets += 1;
    }
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);

    allocated += 1;
    return mshr;
}

MSHR*
MSHRQueue::allocateFetch(Addr addr, int size, Packet * &target)
{
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();
    mshr->allocate(Packet::ReadReq, addr, size, target);
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);

    allocated += 1;
    return mshr;
}

MSHR*
MSHRQueue::allocateTargetList(Addr addr, int size)
{
    MSHR *mshr = freeList.front();
    assert(mshr->getNumTargets() == 0);
    freeList.pop_front();
    Packet * dummy;
    mshr->allocate(Packet::ReadReq, addr, size, dummy);
    mshr->allocIter = allocatedList.insert(allocatedList.end(), mshr);
    mshr->inService = true;
    ++inServiceMSHRs;
    ++allocated;
    return mshr;
}

void
MSHRQueue::deallocate(MSHR* mshr)
{
    deallocateOne(mshr);
}

MSHR::Iterator
MSHRQueue::deallocateOne(MSHR* mshr)
{
    MSHR::Iterator retval = allocatedList.erase(mshr->allocIter);
    freeList.push_front(mshr);
    allocated--;
    allocatedTargets -= mshr->getNumTargets();
    if (mshr->inService) {
        inServiceMSHRs--;
    } else {
        pendingList.erase(mshr->readyIter);
    }
    mshr->deallocate();
    return retval;
}

void
MSHRQueue::moveToFront(MSHR *mshr)
{
    if (!mshr->inService) {
        assert(mshr == *(mshr->readyIter));
        pendingList.erase(mshr->readyIter);
        mshr->readyIter = pendingList.insert(pendingList.begin(), mshr);
    }
}

void
MSHRQueue::markInService(MSHR* mshr)
{
    //assert(mshr == pendingList.front());
    if (!mshr->pkt->needsResponse()) {
        assert(mshr->getNumTargets() == 0);
        deallocate(mshr);
        return;
    }
    mshr->inService = true;
    pendingList.erase(mshr->readyIter);
    //mshr->readyIter = NULL;
    inServiceMSHRs += 1;
    //pendingList.pop_front();
}

void
MSHRQueue::markPending(MSHR* mshr, Packet::Command cmd)
{
    //assert(mshr->readyIter == NULL);
    mshr->pkt->cmd = cmd;
    mshr->pkt->flags &= ~SATISFIED;
    mshr->inService = false;
    --inServiceMSHRs;
    /**
     * @ todo might want to add rerequests to front of pending list for
     * performance.
     */
    mshr->readyIter = pendingList.insert(pendingList.end(), mshr);
}

void
MSHRQueue::squash(int threadNum)
{
    MSHR::Iterator i = allocatedList.begin();
    MSHR::Iterator end = allocatedList.end();
    for (; i != end;) {
        MSHR *mshr = *i;
        if (mshr->threadNum == threadNum) {
            while (mshr->hasTargets()) {
                Packet * target = mshr->getTarget();
                mshr->popTarget();

                assert(0/*target->req->getThreadNum()*/ == threadNum);
                target = NULL;
            }
            assert(!mshr->hasTargets());
            assert(mshr->ntargets==0);
            if (!mshr->inService) {
                i = deallocateOne(mshr);
            } else {
                //mshr->pkt->flags &= ~CACHE_LINE_FILL;
                ++i;
            }
        } else {
            ++i;
        }
    }
}
<|endoftext|>


<commit_before>
/* Here's a small example of the code, written with usage of some basic
 * objects of the library. It covers initialization of the grids and objects,
 * defined on the grid. Here's what's done:
 */

// This includes the grid of real values.
#include "RealGrid.hpp"
// This includes the definition of a container class - a tool to store data.
#include "Container.hpp"
// This include the GridObject class - an object to store data, defined on a grid.
#include "GridObject.hpp"

/* Some more basic definitions, that are used:
 * RealType is double
 * ComplexType is complex<double>
 * INFO( something ) is the same as std::cout << something << std::endl;
 * DEBUG( something ) is the same as INFO, but it also prints the number of the
 * line in the code, where it is called from.
 * ERROR( something ) is the same as INFO but is used for outputting the errors,
 * it sends the text to the error stream (stderr).
 */

// This is a shorthand for not writing GFTools::RealGrid, GFTools::GridObject etc
using namespace GFTools;

int main()
{
    // Let's start with grids.
    // This generates a uniform grid of 20 real numbers from -5 to 5
    RealGrid grid1(-5,5,20);
    // And prints it
    INFO(grid1);

    // New c++ feature - store a function
    std::function<RealType(int)> f1;
    /* The right hand side of next line is called a "lambda" construction.
     * We construct some function of integer and assign it to f1. */
    f1 = [](int n){return std::pow(3,n);};
    // f1 is now 3^n. Let's now generate a non-uniform grid and print it.
    RealGrid grid2(0,10,f1);
    INFO(grid2)

    // Another option is to generate a set of values and generate a grid.
    std::vector<RealType> v1;
    for (RealType a=-3;a<=3;a+=0.01) v1.push_back(a);
    RealGrid grid3(v1);
    INFO(grid3);

    // Now let's make an integration over a grid
    // Let's create another function
    std::function<RealType(RealType)> sinF;
    sinF = [](RealType x){return sin(x);};
    // sinF is now sin(x). We integrate an even function and generate zero.
    INFO(grid1.integrate(sinF));

    // Ok, that's all for grids.
    // Now, let's define objects on a grid.
    // First, make a shorthand
    typedef GridObject<RealType,RealGrid> GFRetarded;
    // Now in order to construct an object on a grid, we need to provide a grid.
    // Let's use the one, already created.
    GFRetarded G1(grid1);
    // After construction, GridObject stores only zeros.
    // Let's fill it with something more interesting, say sin(x).
    G1.fill(sinF);
    INFO(G1)
    // And now let's integrate it. It should give zero once again.
    INFO(grid1.integrate(G1));

    // In order to have an access to the data points, one can just use [] operator.
    // Notice the values are counted from zero.
    INFO(G1[2]);

    //GridObjects also support mathematical operations. Let's create another
    //GridObject first.
    GFRetarded G2(grid1);
    std::function<RealType(RealType)> cosF;
    cosF = [](RealType x){return cos(x);};
    G2.fill(cosF);
    INFO(G2);
    // Now let's make some operations. sin^2(x) + cos^2(x) is trivial.
    GFRetarded G3 = G2*G2+G1*G1;
    INFO(G3);

    // Some advanced features. Grids allow to interpolate values.
/*
    INFO(grid1.getValue(G1,4.47));
    INFO(G1(4.47));
    INFO(grid1.getValue(G1,0.0));
    INFO(G1(0.0));
  */
    /*GridObjects allow for the extrapolation of the values, if they are out
     of grid bounds. For this we need to assign the extrapolation
     function. */
    G1._f = sinF;
//    INFO(G1(2*PI));

    Eigen::ArrayXd xvals(5),yvals(xvals);
    xvals << 1,2,3,4,5;
    DEBUG(xvals);
    yvals = xvals*xvals;
    DEBUG(yvals);

    Eigen::Spline<RealType,2>::PointType x1;
    DEBUG(x1);

    //Eigen::Array<RealType, 2, 5>
    Eigen::Spline2d::ControlPointVectorType x2(2,5);
    x2.row(0) = xvals;
    x2.row(1) = yvals;
    DEBUG(x2);
    //DEBUG(x2(0,0));
/*
    auto SplineF = Eigen::SplineFitting<Eigen::Spline<RealType,2>>::Interpolate(x2,3);
    typedef Eigen::Spline2d::PointType PointType;
    typedef Eigen::Spline2d::KnotVectorType KnotVectorType;
    typedef Eigen::Spline2d::ControlPointVectorType ControlPointVectorType;
    KnotVectorType chord_lengths; // knot parameters
    Eigen::ChordLengths(x2, chord_lengths);
    DEBUG(chord_lengths);
    for (Eigen::DenseIndex i=0; i<x2.cols()-1; ++i)
  {
    DEBUG(SplineF.span(chord_lengths(i) + (chord_lengths(i+1)-chord_lengths(i))*0.5) );
    PointType pt = SplineF(chord_lengths(i) + (chord_lengths(i+1)-chord_lengths(i))*0.5 );
    PointType ref = x2.col(i);
    DEBUG(ref);
    DEBUG(pt);
    DEBUG(chord_lengths(i));
    //DEBUG( (pt - ref).matrix().norm() );
  }
*/
}
<commit_msg>Example cleanup<commit_after>
/* Here's a small example of the code, written with usage of some basic
 * objects of the library. It covers initialization of the grids and objects,
 * defined on the grid. Here's what's done:
 */

// This includes the grid of real values.
#include "RealGrid.hpp"
// This includes the definition of a container class - a tool to store data.
#include "Container.hpp"
// This include the GridObject class - an object to store data, defined on a grid.
#include "GridObject.hpp"

/* Some more basic definitions, that are used:
 * RealType is double
 * ComplexType is complex<double>
 * INFO( something ) is the same as std::cout << something << std::endl;
 * DEBUG( something ) is the same as INFO, but it also prints the number of the
 * line in the code, where it is called from.
 * ERROR( something ) is the same as INFO but is used for outputting the errors,
 * it sends the text to the error stream (stderr).
 */

// This is a shorthand for not writing GFTools::RealGrid, GFTools::GridObject etc
using namespace GFTools;

int main()
{
    // Let's start with grids.
    // This generates a uniform grid of 20 real numbers from -5 to 5
    RealGrid grid1(-5,5,20);
    // And prints it
    INFO(grid1);

    // New c++ feature - store a function
    std::function<RealType(int)> f1;
    /* The right hand side of next line is called a "lambda" construction.
     * We construct some function of integer and assign it to f1. */
    f1 = [](int n){return std::pow(3,n);};
    // f1 is now 3^n. Let's now generate a non-uniform grid and print it.
    RealGrid grid2(0,10,f1);
    INFO(grid2)

    // Another option is to generate a set of values and generate a grid.
    std::vector<RealType> v1;
    for (RealType a=-3;a<=3;a+=0.01) v1.push_back(a);
    RealGrid grid3(v1);
    INFO(grid3);

    // Now let's make an integration over a grid
    // Let's create another function
    std::function<RealType(RealType)> sinF;
    sinF = [](RealType x){return sin(x);};
    // sinF is now sin(x). We integrate an even function and generate zero.
    INFO(grid1.integrate(sinF));

    // Ok, that's all for grids.
    // Now, let's define objects on a grid.
    // First, make a shorthand
    typedef GridObject<RealType,RealGrid> GFRetarded;
    // Now in order to construct an object on a grid, we need to provide a grid.
    // Let's use the one, already created.
    GFRetarded G1(grid1);
    // After construction, GridObject stores only zeros.
    // Let's fill it with something more interesting, say sin(x).
    G1.fill(sinF);
    INFO(G1)
    // And now let's integrate it. It should give zero once again.
    INFO(grid1.integrate(G1));

    // In order to have an access to the data points, one can just use [] operator.
    // Notice the values are counted from zero.
    INFO(G1[2]);

    //GridObjects also support mathematical operations. Let's create another
    //GridObject first.
    GFRetarded G2(grid1);
    std::function<RealType(RealType)> cosF;
    cosF = [](RealType x){return cos(x);};
    G2.fill(cosF);
    INFO(G2);
    // Now let's make some operations. sin^2(x) + cos^2(x) is trivial.
    GFRetarded G3 = G2*G2+G1*G1;
    INFO(G3);

    // Some advanced features. Grids allow to interpolate values.

    INFO(grid1.getValue(G1,4.47));
    INFO(G1(4.47));
    INFO(grid1.getValue(G1,0.0));
    INFO(G1(0.0));

    /*GridObjects allow for the extrapolation of the values, if they are out
     of grid bounds. For this we need to assign the extrapolation
     function. */
    G1._f = sinF;
    INFO(G1(2*PI));
}
<|endoftext|>


<commit_before>//============================================================================
// Name        : hw-verilog.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <random>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "Cromossomo.h"
#include "Populacao.h"
#include "IcarusFitnessCalculator.h"
#include "FPGAFitnessCalculator.h"
#include "SimulationFitnessCalculator.h"
#include "TournamentEvoStrategy.h"
#include "OnePlusLambdaEvoStrategy.h"
#include "RouletteEvoStrategy.h"
#include "GeneticParams.h"

const double MELHOR_FITNESS = 20000000.0;
const unsigned int NUM_SAMPLES = 100;
const unsigned int NUM_IN = 3;
const unsigned int NUM_OUT = 2;
const unsigned int NUM_ROWS = 3;
const unsigned int NUM_COLS = 3;
const unsigned int LE_NUM_IN = 2;
const bool FEED_FORWARD = true;

double fitness(const std::vector<std::vector<std::bitset<8>>>& individual_output) {
	int soma_distancias = 0;
	soma_distancias += individual_output[0][0].to_ulong();
	soma_distancias += abs((int) individual_output[1][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[2][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[3][0].to_ulong() - 2);
	soma_distancias += abs((int) individual_output[4][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[5][0].to_ulong() - 2);
	soma_distancias += abs((int) individual_output[6][0].to_ulong() - 2);
	soma_distancias += abs((int) individual_output[7][0].to_ulong() - 3);
	if (soma_distancias == 0) {
		return MELHOR_FITNESS;
	}
	return 1.0 / ((double) soma_distancias);
}

int main(int argc, char* argv[]) {
	std::vector<bool> funcs = {
			true, // AND
			true, // OR
			true, // XOR
			true, // NOT
			false, // NAND
			false, // XNOR
			false, // NOR
			};
	GeneticParams genetic_params(NUM_IN, NUM_OUT, funcs, LE_NUM_IN, NUM_ROWS,
			NUM_COLS, FEED_FORWARD);

	std::mt19937 mt;
	mt.seed(time(nullptr));

	Populacao populacao(
			new OnePlusLambdaEvoStrategy(mt, 5, genetic_params,
					new SimulationFitnessCalculator(genetic_params, fitness)));

	int geracao = 0;
	populacao.calcular_fitness();
	while (geracao < 10000
			&& populacao.melhor_individuo().fitness() != MELHOR_FITNESS) {
		std::cout << geracao << ": " << populacao.melhor_individuo().fitness()
				<< ", " << populacao.fitness_medio() << std::endl;
		populacao.proxima_geracao();
		populacao.calcular_fitness();
		geracao++;
	}

	CriadorArquivos::cria_arquivo_top_icarus(genetic_params, populacao.melhor_individuo(), "melhor.v");
	if (populacao.melhor_individuo().fitness() == MELHOR_FITNESS) {
		std::cout << "Solucao encontrada na geracao " << geracao << std::endl;
	}

	return 0;
}
<commit_msg>Mudanças principais:<commit_after>//============================================================================
// Name        : hw-verilog.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <random>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <functional>
#include "Cromossomo.h"
#include "Populacao.h"
#include "IcarusFitnessCalculator.h"
#include "FPGAFitnessCalculator.h"
#include "SimulationFitnessCalculator.h"
#include "TournamentEvoStrategy.h"
#include "OnePlusLambdaEvoStrategy.h"
#include "RouletteEvoStrategy.h"
#include "GeneticParams.h"

const double MELHOR_FITNESS = 20000000.0;
const unsigned int NUM_SAMPLES = 100;
const unsigned int NUM_IN = 4;
const unsigned int NUM_OUT = 1;
const unsigned int NUM_ROWS = 1;
const unsigned int NUM_COLS = 10;
const unsigned int LE_NUM_IN = 2;
const bool FEED_FORWARD = true;

double fitness0(const std::vector<std::vector<std::bitset<8>>>& individual_output) {
	int soma_distancias = 0;
	soma_distancias += abs((int) individual_output[0][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[1][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[2][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[3][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[4][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[5][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[6][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[7][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[8][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[9][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[10][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[11][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[12][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[13][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[14][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[15][0].to_ulong() - 0);
	if (soma_distancias == 0) {
		return MELHOR_FITNESS;
	}
	return 1.0 / ((double) soma_distancias);
}

double fitness1(const std::vector<std::vector<std::bitset<8>>>& individual_output) {
	int soma_distancias = 0;
	soma_distancias += abs((int) individual_output[0][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[1][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[2][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[3][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[4][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[5][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[6][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[7][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[8][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[9][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[10][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[11][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[12][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[13][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[14][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[15][0].to_ulong() - 1);
	if (soma_distancias == 0) {
		return MELHOR_FITNESS;
	}
	return 1.0 / ((double) soma_distancias);
}

double fitness2(const std::vector<std::vector<std::bitset<8>>>& individual_output) {
	int soma_distancias = 0;
	soma_distancias += abs((int) individual_output[0][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[1][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[2][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[3][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[4][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[5][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[6][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[7][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[8][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[9][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[10][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[11][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[12][0].to_ulong() - 0);
	soma_distancias += abs((int) individual_output[13][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[14][0].to_ulong() - 1);
	soma_distancias += abs((int) individual_output[15][0].to_ulong() - 1);
	if (soma_distancias == 0) {
		return MELHOR_FITNESS;
	}
	return 1.0 / ((double) soma_distancias);
}

int main(int argc, char* argv[]) {
	std::vector<bool> funcs = {
			true, // AND
			true, // OR
			true, // XOR
			true, // NOT
			false, // NAND
			false, // XNOR
			false, // NOR
			};
	GeneticParams genetic_params(NUM_IN, NUM_OUT, funcs, LE_NUM_IN, NUM_ROWS,
			NUM_COLS, FEED_FORWARD);

	std::mt19937 mt;
	mt.seed(time(nullptr));

	std::vector<
			std::function<double(const std::vector<std::vector<std::bitset<8>>>&)>>
	funcoes_fitness = {fitness0, fitness1, fitness2};
	std::vector<Populacao> populacoes;

	for (auto& funcao_fitness : funcoes_fitness) {
		populacoes.push_back(
				Populacao(
						new OnePlusLambdaEvoStrategy(mt, 5, genetic_params,
								new SimulationFitnessCalculator(genetic_params,
										funcao_fitness))));
	}

	for (auto& populacao : populacoes) {
		int geracao = 0;
		populacao.calcular_fitness();
		while (geracao < 10000
				&& populacao.melhor_individuo().fitness() != MELHOR_FITNESS) {
			std::cout << geracao << ": "
					<< populacao.melhor_individuo().fitness() << ", "
					<< populacao.fitness_medio() << std::endl;
			populacao.proxima_geracao();
			populacao.calcular_fitness();
			geracao++;
		}
		CriadorArquivos::cria_arquivo_top_icarus(genetic_params,
				populacao.melhor_individuo(), "melhor.v");
		if (populacao.melhor_individuo().fitness() == MELHOR_FITNESS) {
			std::cout << "Solucao encontrada na geracao " << geracao << std::endl;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>input arguments to WLOP<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/power_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "third_party/cros/chromeos_resume.h"

namespace chromeos {

class PowerLibraryImpl : public PowerLibrary {
 public:
  PowerLibraryImpl()
      : power_status_connection_(NULL),
        status_(chromeos::PowerStatus()) {
    if (CrosLibrary::Get()->EnsureLoaded()) {
      Init();
    }
  }

  ~PowerLibraryImpl() {
    if (power_status_connection_) {
      chromeos::DisconnectPowerStatus(power_status_connection_);
      power_status_connection_ = NULL;
    }
    if (resume_status_connection_) {
      chromeos::DisconnectResume(resume_status_connection_);
      resume_status_connection_ = NULL;
    }
  }

  void AddObserver(Observer* observer) {
    observers_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  bool line_power_on() const {
    return status_.line_power_on;
  }

  bool battery_is_present() const {
    return status_.battery_is_present;
  }

  bool battery_fully_charged() const {
    return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED;
  }

  double battery_percentage() const {
    return status_.battery_percentage;
  }

  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_empty);
  }

  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_full);
  }

  virtual void EnableScreenLock(bool enable) {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;

    // Make sure we run on FILE thread becuase chromeos::EnableScreenLock
    // would write power manager config file to disk.
    if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
      BrowserThread::PostTask(
          BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::EnableScreenLock, enable));
      return;
    }

    chromeos::EnableScreenLock(enable);
  }

  virtual void RequestRestart() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestRestart();
  }

  virtual void RequestShutdown() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestShutdown();
  }

 private:
  static void PowerStatusChangedHandler(void* object,
      const chromeos::PowerStatus& status) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->UpdatePowerStatus(status);
  }

  static void SystemResumedHandler(void* object) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->SystemResumed();
  }

  void Init() {
    power_status_connection_ = chromeos::MonitorPowerStatus(
        &PowerStatusChangedHandler, this);
    resume_status_connection_ =
        chromeos::MonitorResume(&SystemResumedHandler, this);
  }

  void UpdatePowerStatus(const chromeos::PowerStatus& status) {
    // Make sure we run on UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(
              this, &PowerLibraryImpl::UpdatePowerStatus, status));
      return;
    }

    DVLOG(1) << "Power lpo=" << status.line_power_on
             << " sta=" << status.battery_state
             << " per=" << status.battery_percentage
             << " tte=" << status.battery_time_to_empty
             << " ttf=" << status.battery_time_to_full;
    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this));
  }

  void SystemResumed() {
    // Make sure we run on the UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::SystemResumed));
      return;
    }

    FOR_EACH_OBSERVER(Observer, observers_, SystemResumed());
  }

  ObserverList<Observer> observers_;

  // A reference to the battery power api, to allow callbacks when the battery
  // status changes.
  chromeos::PowerStatusConnection power_status_connection_;

  // A reference to the resume alerts.
  chromeos::ResumeConnection resume_status_connection_;

  // The latest power status.
  chromeos::PowerStatus status_;

  DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl);
};

class PowerLibraryStubImpl : public PowerLibrary {
 public:
  PowerLibraryStubImpl() {}
  ~PowerLibraryStubImpl() {}
  void AddObserver(Observer* observer) {}
  void RemoveObserver(Observer* observer) {}
  bool line_power_on() const { return false; }
  bool battery_is_present() const { return false; }
  bool battery_fully_charged() const { return false; }
  double battery_percentage() const { return false; }
  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(0);
  }
  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(0);
  }
  virtual void EnableScreenLock(bool enable) {}
  virtual void RequestRestart() {}
  virtual void RequestShutdown() {}
};

// static
PowerLibrary* PowerLibrary::GetImpl(bool stub) {
  if (stub)
    return new PowerLibraryStubImpl();
  else
    return new PowerLibraryImpl();
}

}  // namespace chromeos

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl);
<commit_msg>Crash fix in chromeos tests BUG=chromium-os:11121 TEST=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/power_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "third_party/cros/chromeos_resume.h"

namespace chromeos {

class PowerLibraryImpl : public PowerLibrary {
 public:
  PowerLibraryImpl()
      : power_status_connection_(NULL),
        resume_status_connection_(NULL),
        status_(chromeos::PowerStatus()) {
    if (CrosLibrary::Get()->EnsureLoaded()) {
      Init();
    }
  }

  ~PowerLibraryImpl() {
    if (power_status_connection_) {
      chromeos::DisconnectPowerStatus(power_status_connection_);
      power_status_connection_ = NULL;
    }
    if (resume_status_connection_) {
      chromeos::DisconnectResume(resume_status_connection_);
      resume_status_connection_ = NULL;
    }
  }

  void AddObserver(Observer* observer) {
    observers_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  bool line_power_on() const {
    return status_.line_power_on;
  }

  bool battery_is_present() const {
    return status_.battery_is_present;
  }

  bool battery_fully_charged() const {
    return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED;
  }

  double battery_percentage() const {
    return status_.battery_percentage;
  }

  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_empty);
  }

  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(status_.battery_time_to_full);
  }

  virtual void EnableScreenLock(bool enable) {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;

    // Make sure we run on FILE thread becuase chromeos::EnableScreenLock
    // would write power manager config file to disk.
    if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
      BrowserThread::PostTask(
          BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::EnableScreenLock, enable));
      return;
    }

    chromeos::EnableScreenLock(enable);
  }

  virtual void RequestRestart() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestRestart();
  }

  virtual void RequestShutdown() {
    if (!CrosLibrary::Get()->EnsureLoaded())
      return;
    chromeos::RequestShutdown();
  }

 private:
  static void PowerStatusChangedHandler(void* object,
      const chromeos::PowerStatus& status) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->UpdatePowerStatus(status);
  }

  static void SystemResumedHandler(void* object) {
    PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object);
    power->SystemResumed();
  }

  void Init() {
    power_status_connection_ = chromeos::MonitorPowerStatus(
        &PowerStatusChangedHandler, this);
    resume_status_connection_ =
        chromeos::MonitorResume(&SystemResumedHandler, this);
  }

  void UpdatePowerStatus(const chromeos::PowerStatus& status) {
    // Make sure we run on UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(
              this, &PowerLibraryImpl::UpdatePowerStatus, status));
      return;
    }

    DVLOG(1) << "Power lpo=" << status.line_power_on
             << " sta=" << status.battery_state
             << " per=" << status.battery_percentage
             << " tte=" << status.battery_time_to_empty
             << " ttf=" << status.battery_time_to_full;
    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this));
  }

  void SystemResumed() {
    // Make sure we run on the UI thread.
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(this, &PowerLibraryImpl::SystemResumed));
      return;
    }

    FOR_EACH_OBSERVER(Observer, observers_, SystemResumed());
  }

  ObserverList<Observer> observers_;

  // A reference to the battery power api, to allow callbacks when the battery
  // status changes.
  chromeos::PowerStatusConnection power_status_connection_;

  // A reference to the resume alerts.
  chromeos::ResumeConnection resume_status_connection_;

  // The latest power status.
  chromeos::PowerStatus status_;

  DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl);
};

class PowerLibraryStubImpl : public PowerLibrary {
 public:
  PowerLibraryStubImpl() {}
  ~PowerLibraryStubImpl() {}
  void AddObserver(Observer* observer) {}
  void RemoveObserver(Observer* observer) {}
  bool line_power_on() const { return false; }
  bool battery_is_present() const { return false; }
  bool battery_fully_charged() const { return false; }
  double battery_percentage() const { return false; }
  base::TimeDelta battery_time_to_empty() const {
    return base::TimeDelta::FromSeconds(0);
  }
  base::TimeDelta battery_time_to_full() const {
    return base::TimeDelta::FromSeconds(0);
  }
  virtual void EnableScreenLock(bool enable) {}
  virtual void RequestRestart() {}
  virtual void RequestShutdown() {}
};

// static
PowerLibrary* PowerLibrary::GetImpl(bool stub) {
  if (stub)
    return new PowerLibraryStubImpl();
  else
    return new PowerLibraryImpl();
}

}  // namespace chromeos

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl);
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/app_launcher_handler.h"

#include "app/resource_bundle.h"
#include "base/base64.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/browser_resources.h"

namespace {

bool TreatAsApp(const Extension* extension) {
  return !extension->GetFullLaunchURL().is_empty();
}

}  // namespace

AppLauncherHandler::AppLauncherHandler(
    ExtensionsService* extension_service)
    : extensions_service_(extension_service) {
}

AppLauncherHandler::~AppLauncherHandler() {}

DOMMessageHandler* AppLauncherHandler::Attach(DOMUI* dom_ui) {
  // TODO(arv): Add initialization code to the Apps store etc.
  return DOMMessageHandler::Attach(dom_ui);
}

void AppLauncherHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getApps",
      NewCallback(this, &AppLauncherHandler::HandleGetApps));
  dom_ui_->RegisterMessageCallback("launchApp",
      NewCallback(this, &AppLauncherHandler::HandleLaunchApp));
}

void AppLauncherHandler::Observe(NotificationType type,
                                 const NotificationSource& source,
                                 const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::EXTENSION_LOADED:
    case NotificationType::EXTENSION_UNLOADED:
      if (dom_ui_->tab_contents())
        HandleGetApps(NULL);
      break;

    default:
      NOTREACHED();
  }
}

// static
void AppLauncherHandler::CreateAppInfo(Extension* extension,
                                          DictionaryValue* value) {
  value->Clear();
  value->SetString(L"id", extension->id());
  value->SetString(L"name", extension->name());
  value->SetString(L"description", extension->description());
  value->SetString(L"launch_url", extension->GetFullLaunchURL().spec());

  FilePath relative_path =
      extension->GetIconPath(Extension::EXTENSION_ICON_LARGE).relative_path();

#if defined(OS_POSIX)
  std::string path = relative_path.value();
#elif defined(OS_WIN)
  std::string path = WideToUTF8(relative_path.value());
#endif  // OS_WIN

  GURL icon_url = extension->GetResourceURL(path);
  value->SetString(L"icon", icon_url.spec());
}

void AppLauncherHandler::HandleGetApps(const Value* value) {
  ListValue list;
  const ExtensionList* extensions = extensions_service_->extensions();
  for (ExtensionList::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
     if (TreatAsApp(*it)) {
       DictionaryValue* app_info = new DictionaryValue();
       CreateAppInfo(*it, app_info);
       list.Append(app_info);
     }
  }

  dom_ui_->CallJavascriptFunction(L"getAppsCallback", list);

  // First time we get here we set up the observer so that we can tell update
  // the apps as they change.
  if (registrar_.IsEmpty()) {
    registrar_.Add(this, NotificationType::EXTENSION_LOADED,
        NotificationService::AllSources());
    registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
        NotificationService::AllSources());
  }
}

void AppLauncherHandler::HandleLaunchApp(const Value* value) {
  if (!value->IsType(Value::TYPE_LIST)) {
    NOTREACHED();
    return;
  }

  std::string extension_id;
  std::string launch_container;

  const ListValue* list = static_cast<const ListValue*>(value);
  if (!list->GetString(0, &extension_id) ||
      !list->GetString(1, &launch_container)) {
    NOTREACHED();
    return;
  }

  Profile* profile = extensions_service_->profile();
  if (launch_container.empty()) {
    Browser::OpenApplication(profile, extension_id);
    return;
  }

  // Override the default launch container.
  Extension* extension =
      extensions_service_->GetExtensionById(extension_id, false);
  DCHECK(extension);

  Extension::LaunchContainer container;
  if (launch_container == "tab")
    container = Extension::LAUNCH_TAB;
  else if (launch_container == "panel")
    container = Extension::LAUNCH_PANEL;
  else if (launch_container == "window")
    container = Extension::LAUNCH_WINDOW;
  else
    NOTREACHED() << "Unexpected launch container: " << launch_container << ".";

  Browser::OpenApplication(profile, extension, container);
}
<commit_msg>fix linux build<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/app_launcher_handler.h"

#include "app/resource_bundle.h"
#include "base/base64.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/browser_resources.h"

namespace {

bool TreatAsApp(const Extension* extension) {
  return !extension->GetFullLaunchURL().is_empty();
}

}  // namespace

AppLauncherHandler::AppLauncherHandler(
    ExtensionsService* extension_service)
    : extensions_service_(extension_service) {
}

AppLauncherHandler::~AppLauncherHandler() {}

DOMMessageHandler* AppLauncherHandler::Attach(DOMUI* dom_ui) {
  // TODO(arv): Add initialization code to the Apps store etc.
  return DOMMessageHandler::Attach(dom_ui);
}

void AppLauncherHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getApps",
      NewCallback(this, &AppLauncherHandler::HandleGetApps));
  dom_ui_->RegisterMessageCallback("launchApp",
      NewCallback(this, &AppLauncherHandler::HandleLaunchApp));
}

void AppLauncherHandler::Observe(NotificationType type,
                                 const NotificationSource& source,
                                 const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::EXTENSION_LOADED:
    case NotificationType::EXTENSION_UNLOADED:
      if (dom_ui_->tab_contents())
        HandleGetApps(NULL);
      break;

    default:
      NOTREACHED();
  }
}

// static
void AppLauncherHandler::CreateAppInfo(Extension* extension,
                                          DictionaryValue* value) {
  value->Clear();
  value->SetString(L"id", extension->id());
  value->SetString(L"name", extension->name());
  value->SetString(L"description", extension->description());
  value->SetString(L"launch_url", extension->GetFullLaunchURL().spec());

  FilePath relative_path =
      extension->GetIconPath(Extension::EXTENSION_ICON_LARGE).relative_path();

#if defined(OS_POSIX)
  std::string path = relative_path.value();
#elif defined(OS_WIN)
  std::string path = WideToUTF8(relative_path.value());
#endif  // OS_WIN

  GURL icon_url = extension->GetResourceURL(path);
  value->SetString(L"icon", icon_url.spec());
}

void AppLauncherHandler::HandleGetApps(const Value* value) {
  ListValue list;
  const ExtensionList* extensions = extensions_service_->extensions();
  for (ExtensionList::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
     if (TreatAsApp(*it)) {
       DictionaryValue* app_info = new DictionaryValue();
       CreateAppInfo(*it, app_info);
       list.Append(app_info);
     }
  }

  dom_ui_->CallJavascriptFunction(L"getAppsCallback", list);

  // First time we get here we set up the observer so that we can tell update
  // the apps as they change.
  if (registrar_.IsEmpty()) {
    registrar_.Add(this, NotificationType::EXTENSION_LOADED,
        NotificationService::AllSources());
    registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
        NotificationService::AllSources());
  }
}

void AppLauncherHandler::HandleLaunchApp(const Value* value) {
  if (!value->IsType(Value::TYPE_LIST)) {
    NOTREACHED();
    return;
  }

  std::string extension_id;
  std::string launch_container;

  const ListValue* list = static_cast<const ListValue*>(value);
  if (!list->GetString(0, &extension_id) ||
      !list->GetString(1, &launch_container)) {
    NOTREACHED();
    return;
  }

  Profile* profile = extensions_service_->profile();
  if (launch_container.empty()) {
    Browser::OpenApplication(profile, extension_id);
    return;
  }

  // Override the default launch container.
  Extension* extension =
      extensions_service_->GetExtensionById(extension_id, false);
  DCHECK(extension);

  Extension::LaunchContainer container = Extension::LAUNCH_TAB;
  if (launch_container == "tab")
    container = Extension::LAUNCH_TAB;
  else if (launch_container == "panel")
    container = Extension::LAUNCH_PANEL;
  else if (launch_container == "window")
    container = Extension::LAUNCH_WINDOW;
  else
    NOTREACHED() << "Unexpected launch container: " << launch_container << ".";

  Browser::OpenApplication(profile, extension, container);
}
<|endoftext|>