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

#include "rdf_calculator.h"
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <votca/csg/beadlist.h>
#include <votca/csg/imcio.h>
#include <votca/csg/nblistgrid.h>
#include <votca/tools/constants.h>
#include <votca/tools/rangeparser.h>

namespace votca {
namespace csg {

RDFCalculator::RDFCalculator()
    : _write_every(0),
      _do_blocks(false),
      _nblock(0),
      _subvol_rad(0),
      _do_vol_corr(false),
      _processed_some_frames(false) {}

RDFCalculator::~RDFCalculator() = default;

// begin the coarse graining process
// here the data structures are prepared to handle all the data
void RDFCalculator::Initialize() {
  // do some output
  std::cout << "begin to calculate distribution functions\n";
  std::cout << "# of bonded interactions: " << _bonded.size() << std::endl;
  std::cout << "# of non-bonded interactions: " << _nonbonded.size()
            << std::endl;

  if (_bonded.size() + _nonbonded.size() == 0) {
    throw std::runtime_error(
        "No interactions defined in options xml-file - nothing to be done");
  }

  // initialize non-bonded structures
  for (Property *prop : _nonbonded) {
    interaction_t *i = AddInteraction(prop);
    i->_is_bonded = false;
  }
}

void RDFCalculator::BeginEvaluate(Topology *top, Topology *) {
  Eigen::Matrix3d box = top->getBox();
  Eigen::Vector3d a = box.col(0);
  Eigen::Vector3d b = box.col(1);
  Eigen::Vector3d c = box.col(2);
  _boxc = box.rowwise().sum() / 2.0;

  std::cout << "Using center of box: " << _boxc << std::endl;
  // we didn't process any frames so far
  _nframes = 0;
  _nblock = 0;
  _processed_some_frames = false;

  // initialize non-bonded structures
  for (Property *prop : _nonbonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_interactions[name];

    // count total species for ideal densities

    BeadList allbeads1, allbeads2;
    allbeads1.Generate(*top, prop->get("type1").value());
    allbeads2.Generate(*top, prop->get("type2").value());

    if (allbeads1.size() == 0) {
      throw std::runtime_error("Topology does not have beads of type \"" +
                               prop->get("type1").value() +
                               "\"\n"
                               "This was specified in type1 of interaction \"" +
                               name + "\"");
    }
    if (allbeads2.size() == 0) {
      throw std::runtime_error("Topology does not have beads of type \"" +
                               prop->get("type2").value() +
                               "\"\n"
                               "This was specified in type2 of interaction \"" +
                               name + "\"");
    }
    // calculate normalization factor for rdf

    if (_do_vol_corr) {
      std::cout << "Volume correction on" << std::endl;
      i._norm = 1. / (4.0 * votca::tools::conv::Pi * i._step);
    } else {
      std::cout << "Volume correction off" << std::endl;
      i._norm = 1. / (4. * votca::tools::conv::Pi * i._step);
    }
  }
}
// create an entry for interactions
RDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) {
  std::string name = p->get("name").value();
  std::string group;

  group = "none";

  interaction_t *i = new interaction_t;
  i->_index = _interactions.size();
  _interactions[name] = i;
  getGroup(group)->_interactions.push_back(i);

  i->_step = p->get("step").as<double>();
  i->_min = p->get("min").as<double>();
  i->_max = p->get("max").as<double>();
  i->_norm = 1.0;
  i->_p = p;

  // initialize the current and average histogram
  int n = (int)((i->_max - i->_min) / i->_step + 1.000000001);

  i->_average.Initialize(i->_min, i->_max + i->_step, n);

  return i;
}

// end of trajectory, post processing data
void RDFCalculator::EndEvaluate() {
  if (_nframes > 0) {
    if (!_do_blocks) {
      WriteDist();
    }
  }
  // clear interactions and groups
  _interactions.clear();
  _groups.clear();
  if (!_processed_some_frames) {
    throw std::runtime_error(
        "no frames were processed. Please check your input");
  }
}

// load options from xml file
void RDFCalculator::LoadOptions(const std::string &file) {
  _options.LoadFromXML(file);
  _bonded = _options.Select("cg.bonded");
  _nonbonded = _options.Select("cg.non-bonded");
}

// evaluate current conformation
void RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) {
  _cur_vol = 4.0 / 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad *
             _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad;
  // process non-bonded interactions
  DoNonbonded(top);
  // process bonded interactions
  DoBonded(top);
}

void RDFCalculator::ClearAverages() {

  _nframes = 0;
  for (auto &_interaction : _interactions) {
    _interaction.second->_average.Clear();
  }

  for (auto &_group : _groups) {
    _group.second->_corr.setZero();
  }
}

class IMCNBSearchHandler {
 public:
  IMCNBSearchHandler(HistogramNew *hist, double subvol_rad,
                     Eigen::Vector3d boxc, bool do_vol_corr)
      : _hist(hist),
        _subvol_rad(subvol_rad),
        _boxc(boxc),
        _do_vol_corr(do_vol_corr) {}

  HistogramNew *_hist;
  double _subvol_rad;
  Eigen::Vector3d _boxc;  // center of box
  bool _do_vol_corr;

  bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) {

    if (_do_vol_corr) {
      double dr = (b1->Pos() - _boxc).norm();
      if (dist + dr > _subvol_rad) {
        // 2.0 is because everything is normalized to 4 PI
        _hist->Process(dist, 2.0 / SurfaceRatio(dist, dr));
      } else {
        _hist->Process(dist);
      }

    } else {
      _hist->Process(dist);
    }
    return false;
  }

  double SurfaceRatio(double dist, double r) {
    // r: distance of particle from ex center
    // dist: distance between particles
    return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) /
                      (2.0 * dist * r));
  }
};

// process non-bonded interactions for current frame
void RDFCalculator::Worker::DoNonbonded(Topology *top) {
  for (Property *prop : _rdfcalculator->_nonbonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_rdfcalculator->_interactions[name];

    // generate the bead lists
    BeadList beads1, beads2;

    beads1.GenerateInSphericalSubvolume(*top, prop->get("type1").value(),
                                        _rdfcalculator->_boxc,
                                        _rdfcalculator->_subvol_rad);
    beads2.GenerateInSphericalSubvolume(*top, prop->get("type2").value(),
                                        _rdfcalculator->_boxc,
                                        _rdfcalculator->_subvol_rad);

    _cur_beadlist_1_count = (double)beads1.size();
    _cur_beadlist_2_count = (double)beads2.size();

    // same types, so put factor 1/2 because of already counted interactions
    if (prop->get("type1").value() == prop->get("type2").value()) {
      _cur_beadlist_2_count /= 2.0;
    }

    // generate the neighbour list
    std::unique_ptr<NBList> nb;

    bool gridsearch = true;

    if (_rdfcalculator->_options.exists("cg.nbsearch")) {
      if (_rdfcalculator->_options.get("cg.nbsearch").as<std::string>() ==
          "grid") {
        gridsearch = true;
      } else if (_rdfcalculator->_options.get("cg.nbsearch")
                     .as<std::string>() == "simple") {
        gridsearch = false;
      } else {
        throw std::runtime_error("cg.nbsearch invalid, can be grid or simple");
      }
    }
    if (gridsearch) {
      nb = std::make_unique<NBList>(NBListGrid());
    } else {
      nb = std::make_unique<NBList>(NBList());
    }

    nb->setCutoff(i._max + i._step);

    // clear the current histogram
    _current_hists[i._index].Clear();

    IMCNBSearchHandler h(&(_current_hists[i._index]),
                         _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc,
                         _rdfcalculator->_do_vol_corr);
    nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair);

    // is it same types or different types?
    if (prop->get("type1").value() == prop->get("type2").value()) {
      nb->Generate(beads1);
    } else {
      nb->Generate(beads1, beads2);
    }

    // store particle number in subvolume for each interaction
    i._avg_beadlist_1_count.Process(_cur_beadlist_1_count);
    i._avg_beadlist_2_count.Process(_cur_beadlist_2_count);
  }
}

// process non-bonded interactions for current frame
void RDFCalculator::Worker::DoBonded(Topology *top) {
  for (Property *prop : _rdfcalculator->_bonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_rdfcalculator->_interactions[name];

    // clear the current histogram
    _current_hists[i._index].Clear();

    // now fill with new data
    std::list<Interaction *> list = top->InteractionsInGroup(name);

    for (auto ic : list) {
      double v = ic->EvaluateVar(*top);
      _current_hists[i._index].Process(v);
    }
  }
}

// returns a group, creates it if doesn't exist
RDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) {
  std::map<std::string, group_t *>::iterator iter;
  iter = _groups.find(name);
  if (iter == _groups.end()) {
    return _groups[name] = new group_t;
  }
  return (*iter).second;
}

// write the distribution function
void RDFCalculator::WriteDist(const std::string &suffix) {

  // for all interactions
  for (auto &_interaction : _interactions) {
    // calculate the rdf
    Table &t = _interaction.second->_average.data();
    Table dist(t);

    _interaction.second->_norm /=
        (_interaction.second->_avg_beadlist_1_count.getAvg() *
         _interaction.second->_avg_beadlist_2_count.getAvg());
    dist.y() = _avg_vol.getAvg() * _interaction.second->_norm *
               dist.y().cwiseQuotient(dist.x().cwiseAbs2());

    dist.Save((_interaction.first) + suffix + ".dist.new");
    std::cout << "written " << (_interaction.first) + suffix + ".dist.new\n";

    std::cout << "Avg. number of particles in subvol for "
              << (_interaction.first) << std::endl;
    std::cout << "beadlist 1: "
              << _interaction.second->_avg_beadlist_1_count.getAvg()
              << std::endl;
    std::cout << "beadlist 2: "
              << _interaction.second->_avg_beadlist_2_count.getAvg()
              << std::endl;
  }

  std::cout << "Volume used for normalization: " << _avg_vol.getAvg()
            << std::endl;
}

CsgApplication::Worker *RDFCalculator::ForkWorker() {
  RDFCalculator::Worker *worker;
  worker = new RDFCalculator::Worker;

  worker->_current_hists.resize(_interactions.size());
  worker->_rdfcalculator = this;

  for (auto &_interaction : _interactions) {
    interaction_t *i = _interaction.second;
    worker->_current_hists[i->_index].Initialize(
        i->_average.getMin(), i->_average.getMax(), i->_average.getNBins());
  }
  return worker;
}

void RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) {
  _processed_some_frames = true;
  RDFCalculator::Worker *worker =
      dynamic_cast<RDFCalculator::Worker *>(worker_);
  // update the average

  ++_nframes;

  _avg_vol.Process(worker->_cur_vol);

  for (auto &_interaction : _interactions) {
    interaction_t *i = _interaction.second;
    i->_average.data().y() =
        (((double)_nframes - 1.0) * i->_average.data().y() +
         worker->_current_hists[i->_index].data().y()) /
        (double)_nframes;
  }

  if (_write_every != 0) {
    if ((_nframes % _write_every) == 0) {
      _nblock++;
      std::string suffix =
          std::string("_") + boost::lexical_cast<std::string>(_nblock);
      WriteDist(suffix);
      if (_do_blocks) {
        ClearAverages();
      }
    }
  }
}

}  // namespace csg
}  // namespace votca
<commit_msg>Update rdf_calculator.cc<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "rdf_calculator.h"
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <votca/csg/beadlist.h>
#include <votca/csg/imcio.h>
#include <votca/csg/nblistgrid.h>
#include <votca/tools/constants.h>
#include <votca/tools/rangeparser.h>

namespace votca {
namespace csg {

RDFCalculator::RDFCalculator()
    : _write_every(0),
      _do_blocks(false),
      _nblock(0),
      _subvol_rad(0),
      _do_vol_corr(false),
      _processed_some_frames(false) {}

RDFCalculator::~RDFCalculator() = default;

// begin the coarse graining process
// here the data structures are prepared to handle all the data
void RDFCalculator::Initialize() {
  // do some output
  std::cout << "begin to calculate distribution functions\n";
  std::cout << "# of bonded interactions: " << _bonded.size() << std::endl;
  std::cout << "# of non-bonded interactions: " << _nonbonded.size()
            << std::endl;

  if (_bonded.size() + _nonbonded.size() == 0) {
    throw std::runtime_error(
        "No interactions defined in options xml-file - nothing to be done");
  }

  // initialize non-bonded structures
  for (Property *prop : _nonbonded) {
    interaction_t *i = AddInteraction(prop);
    i->_is_bonded = false;
  }
}

void RDFCalculator::BeginEvaluate(Topology *top, Topology *) {
  Eigen::Matrix3d box = top->getBox();
  _boxc = box.rowwise().sum() / 2.0;

  std::cout << "Using center of box: " << _boxc << std::endl;
  // we didn't process any frames so far
  _nframes = 0;
  _nblock = 0;
  _processed_some_frames = false;

  // initialize non-bonded structures
  for (Property *prop : _nonbonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_interactions[name];

    // count total species for ideal densities

    BeadList allbeads1, allbeads2;
    allbeads1.Generate(*top, prop->get("type1").value());
    allbeads2.Generate(*top, prop->get("type2").value());

    if (allbeads1.size() == 0) {
      throw std::runtime_error("Topology does not have beads of type \"" +
                               prop->get("type1").value() +
                               "\"\n"
                               "This was specified in type1 of interaction \"" +
                               name + "\"");
    }
    if (allbeads2.size() == 0) {
      throw std::runtime_error("Topology does not have beads of type \"" +
                               prop->get("type2").value() +
                               "\"\n"
                               "This was specified in type2 of interaction \"" +
                               name + "\"");
    }
    // calculate normalization factor for rdf

    if (_do_vol_corr) {
      std::cout << "Volume correction on" << std::endl;
      i._norm = 1. / (4.0 * votca::tools::conv::Pi * i._step);
    } else {
      std::cout << "Volume correction off" << std::endl;
      i._norm = 1. / (4. * votca::tools::conv::Pi * i._step);
    }
  }
}
// create an entry for interactions
RDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) {
  std::string name = p->get("name").value();
  std::string group;

  group = "none";

  interaction_t *i = new interaction_t;
  i->_index = _interactions.size();
  _interactions[name] = i;
  getGroup(group)->_interactions.push_back(i);

  i->_step = p->get("step").as<double>();
  i->_min = p->get("min").as<double>();
  i->_max = p->get("max").as<double>();
  i->_norm = 1.0;
  i->_p = p;

  // initialize the current and average histogram
  int n = (int)((i->_max - i->_min) / i->_step + 1.000000001);

  i->_average.Initialize(i->_min, i->_max + i->_step, n);

  return i;
}

// end of trajectory, post processing data
void RDFCalculator::EndEvaluate() {
  if (_nframes > 0) {
    if (!_do_blocks) {
      WriteDist();
    }
  }
  // clear interactions and groups
  _interactions.clear();
  _groups.clear();
  if (!_processed_some_frames) {
    throw std::runtime_error(
        "no frames were processed. Please check your input");
  }
}

// load options from xml file
void RDFCalculator::LoadOptions(const std::string &file) {
  _options.LoadFromXML(file);
  _bonded = _options.Select("cg.bonded");
  _nonbonded = _options.Select("cg.non-bonded");
}

// evaluate current conformation
void RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) {
  _cur_vol = 4.0 / 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad *
             _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad;
  // process non-bonded interactions
  DoNonbonded(top);
  // process bonded interactions
  DoBonded(top);
}

void RDFCalculator::ClearAverages() {

  _nframes = 0;
  for (auto &_interaction : _interactions) {
    _interaction.second->_average.Clear();
  }

  for (auto &_group : _groups) {
    _group.second->_corr.setZero();
  }
}

class IMCNBSearchHandler {
 public:
  IMCNBSearchHandler(HistogramNew *hist, double subvol_rad,
                     Eigen::Vector3d boxc, bool do_vol_corr)
      : _hist(hist),
        _subvol_rad(subvol_rad),
        _boxc(boxc),
        _do_vol_corr(do_vol_corr) {}

  HistogramNew *_hist;
  double _subvol_rad;
  Eigen::Vector3d _boxc;  // center of box
  bool _do_vol_corr;

  bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) {

    if (_do_vol_corr) {
      double dr = (b1->Pos() - _boxc).norm();
      if (dist + dr > _subvol_rad) {
        // 2.0 is because everything is normalized to 4 PI
        _hist->Process(dist, 2.0 / SurfaceRatio(dist, dr));
      } else {
        _hist->Process(dist);
      }

    } else {
      _hist->Process(dist);
    }
    return false;
  }

  double SurfaceRatio(double dist, double r) {
    // r: distance of particle from ex center
    // dist: distance between particles
    return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) /
                      (2.0 * dist * r));
  }
};

// process non-bonded interactions for current frame
void RDFCalculator::Worker::DoNonbonded(Topology *top) {
  for (Property *prop : _rdfcalculator->_nonbonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_rdfcalculator->_interactions[name];

    // generate the bead lists
    BeadList beads1, beads2;

    beads1.GenerateInSphericalSubvolume(*top, prop->get("type1").value(),
                                        _rdfcalculator->_boxc,
                                        _rdfcalculator->_subvol_rad);
    beads2.GenerateInSphericalSubvolume(*top, prop->get("type2").value(),
                                        _rdfcalculator->_boxc,
                                        _rdfcalculator->_subvol_rad);

    _cur_beadlist_1_count = (double)beads1.size();
    _cur_beadlist_2_count = (double)beads2.size();

    // same types, so put factor 1/2 because of already counted interactions
    if (prop->get("type1").value() == prop->get("type2").value()) {
      _cur_beadlist_2_count /= 2.0;
    }

    // generate the neighbour list
    std::unique_ptr<NBList> nb;

    bool gridsearch = true;

    if (_rdfcalculator->_options.exists("cg.nbsearch")) {
      if (_rdfcalculator->_options.get("cg.nbsearch").as<std::string>() ==
          "grid") {
        gridsearch = true;
      } else if (_rdfcalculator->_options.get("cg.nbsearch")
                     .as<std::string>() == "simple") {
        gridsearch = false;
      } else {
        throw std::runtime_error("cg.nbsearch invalid, can be grid or simple");
      }
    }
    if (gridsearch) {
      nb = std::make_unique<NBList>(NBListGrid());
    } else {
      nb = std::make_unique<NBList>(NBList());
    }

    nb->setCutoff(i._max + i._step);

    // clear the current histogram
    _current_hists[i._index].Clear();

    IMCNBSearchHandler h(&(_current_hists[i._index]),
                         _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc,
                         _rdfcalculator->_do_vol_corr);
    nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair);

    // is it same types or different types?
    if (prop->get("type1").value() == prop->get("type2").value()) {
      nb->Generate(beads1);
    } else {
      nb->Generate(beads1, beads2);
    }

    // store particle number in subvolume for each interaction
    i._avg_beadlist_1_count.Process(_cur_beadlist_1_count);
    i._avg_beadlist_2_count.Process(_cur_beadlist_2_count);
  }
}

// process non-bonded interactions for current frame
void RDFCalculator::Worker::DoBonded(Topology *top) {
  for (Property *prop : _rdfcalculator->_bonded) {
    std::string name = prop->get("name").value();

    interaction_t &i = *_rdfcalculator->_interactions[name];

    // clear the current histogram
    _current_hists[i._index].Clear();

    // now fill with new data
    std::list<Interaction *> list = top->InteractionsInGroup(name);

    for (auto ic : list) {
      double v = ic->EvaluateVar(*top);
      _current_hists[i._index].Process(v);
    }
  }
}

// returns a group, creates it if doesn't exist
RDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) {
  std::map<std::string, group_t *>::iterator iter;
  iter = _groups.find(name);
  if (iter == _groups.end()) {
    return _groups[name] = new group_t;
  }
  return (*iter).second;
}

// write the distribution function
void RDFCalculator::WriteDist(const std::string &suffix) {

  // for all interactions
  for (auto &_interaction : _interactions) {
    // calculate the rdf
    Table &t = _interaction.second->_average.data();
    Table dist(t);

    _interaction.second->_norm /=
        (_interaction.second->_avg_beadlist_1_count.getAvg() *
         _interaction.second->_avg_beadlist_2_count.getAvg());
    dist.y() = _avg_vol.getAvg() * _interaction.second->_norm *
               dist.y().cwiseQuotient(dist.x().cwiseAbs2());

    dist.Save((_interaction.first) + suffix + ".dist.new");
    std::cout << "written " << (_interaction.first) + suffix + ".dist.new\n";

    std::cout << "Avg. number of particles in subvol for "
              << (_interaction.first) << std::endl;
    std::cout << "beadlist 1: "
              << _interaction.second->_avg_beadlist_1_count.getAvg()
              << std::endl;
    std::cout << "beadlist 2: "
              << _interaction.second->_avg_beadlist_2_count.getAvg()
              << std::endl;
  }

  std::cout << "Volume used for normalization: " << _avg_vol.getAvg()
            << std::endl;
}

CsgApplication::Worker *RDFCalculator::ForkWorker() {
  RDFCalculator::Worker *worker;
  worker = new RDFCalculator::Worker;

  worker->_current_hists.resize(_interactions.size());
  worker->_rdfcalculator = this;

  for (auto &_interaction : _interactions) {
    interaction_t *i = _interaction.second;
    worker->_current_hists[i->_index].Initialize(
        i->_average.getMin(), i->_average.getMax(), i->_average.getNBins());
  }
  return worker;
}

void RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) {
  _processed_some_frames = true;
  RDFCalculator::Worker *worker =
      dynamic_cast<RDFCalculator::Worker *>(worker_);
  // update the average

  ++_nframes;

  _avg_vol.Process(worker->_cur_vol);

  for (auto &_interaction : _interactions) {
    interaction_t *i = _interaction.second;
    i->_average.data().y() =
        (((double)_nframes - 1.0) * i->_average.data().y() +
         worker->_current_hists[i->_index].data().y()) /
        (double)_nframes;
  }

  if (_write_every != 0) {
    if ((_nframes % _write_every) == 0) {
      _nblock++;
      std::string suffix =
          std::string("_") + boost::lexical_cast<std::string>(_nblock);
      WriteDist(suffix);
      if (_do_blocks) {
        ClearAverages();
      }
    }
  }
}

}  // namespace csg
}  // namespace votca
<|endoftext|>


<commit_before>/**
 * @file py_sql_well.cpp
 * @brief python wraper for well fracture storage
 * @author Oleg Borschuk
 * @version
 * @date 2011-07-29
 */

#include "py_sql_well.h"
#include "sql_well.h"
#include "bs_serialize.h"
#include "bs_prop_base.h"

using namespace boost::python;
#ifdef BSPY_EXPORTING_PLUGIN

namespace blue_sky {
namespace python {
  void py_export_compdat_ident();

  //////////////////////////////////////////////////////////////////////////

  // helper function to write well_pool to given fname
  std::string serialize_to_str_fname(
      smart_ptr< well_pool_iface > wp,
      const std::string& prj_path,
      const std::string& prj_name
  ) {
    // save project path for serialization code
    kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type("hdm").td_);
    //std::string well_pool_filename = prj_name + "_well_pool.db";
    p_dt->insert< std::string >(prj_path);
    // and project name
    p_dt->insert< std::string >(prj_name);

    // invoke serializetion
    std::string res = serialize_to_str< well_pool_iface >(wp);
    // clear table
    p_dt->clear< std::string >();

    return res;
  }

  //////////////////////////////////////////////////////////////////////////
  //! export matrices to python
  void py_export_sql_well ()
  {
    using namespace boost::python;

    base_exporter <well_pool_iface, py_sql_well_exporter>::export_class ("well_pool_iface");

    class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class ("sql_well");

    py_export_compdat_ident();

    def("serialize_to_str", &blue_sky::serialize_to_str< well_pool_iface >);
    def("serialize_from_str", &blue_sky::serialize_from_str< well_pool_iface >);
    def("serialize_to_str_fname", &serialize_to_str_fname);

    // register implicit conversion to interface
    implicitly_convertible<
      smart_ptr< sql_well >,
      smart_ptr< well_pool_iface >
    >();
  }

}	// namespace python
}	// namespace blue_sky
#endif // #ifdef BSPY_EXPORTING_PLUGIN
<commit_msg>SQW: export to Python explicit serialization functions for sql_well class<commit_after>/**
 * @file py_sql_well.cpp
 * @brief python wraper for well fracture storage
 * @author Oleg Borschuk
 * @version
 * @date 2011-07-29
 */

#include "py_sql_well.h"
#include "sql_well.h"
#include "bs_serialize.h"
#include "bs_prop_base.h"

using namespace boost::python;
#ifdef BSPY_EXPORTING_PLUGIN

BLUE_SKY_TYPE_SERIALIZE_GUID(blue_sky::sql_well)
BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::sql_well)

namespace blue_sky {
namespace python {
  void py_export_compdat_ident();

  //////////////////////////////////////////////////////////////////////////

  // helper function to write well_pool to given fname
  std::string serialize_to_str_fname(
      smart_ptr< well_pool_iface > wp,
      const std::string& prj_path,
      const std::string& prj_name
  ) {
    // save project path for serialization code
    kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type("hdm").td_);
    //std::string well_pool_filename = prj_name + "_well_pool.db";
    p_dt->insert< std::string >(prj_path);
    // and project name
    p_dt->insert< std::string >(prj_name);

    // invoke serializetion
    std::string res = serialize_to_str< well_pool_iface >(wp);
    // clear table
    p_dt->clear< std::string >();

    return res;
  }

  //////////////////////////////////////////////////////////////////////////
  //! export matrices to python
  void py_export_sql_well ()
  {
    using namespace boost::python;

    base_exporter <well_pool_iface, py_sql_well_exporter>::export_class ("well_pool_iface");

    class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class ("sql_well");

    py_export_compdat_ident();

    std::string (*s2s_wpi)(smart_ptr< well_pool_iface >&) = &blue_sky::serialize_to_str< well_pool_iface >;
    std::string (*s2s_sqw)(smart_ptr< sql_well >&) = &blue_sky::serialize_to_str< sql_well >;
    smart_ptr< well_pool_iface > (*sfs_wpi)(const std::string&) = &blue_sky::serialize_from_str< well_pool_iface >;
    smart_ptr< sql_well > (*sfs_sqw)(const std::string&) = &blue_sky::serialize_from_str< sql_well >;

    def("serialize_to_str", s2s_wpi);
    def("serialize_to_str", s2s_sqw);
    def("serialize_from_str", sfs_wpi);
    def("serialize_from_str", sfs_sqw);

    //def("serialize_to_str", &blue_sky::serialize_to_str< well_pool_iface >);
    //def("serialize_from_str", &blue_sky::serialize_from_str< well_pool_iface >);
    def("serialize_to_str_fname", &serialize_to_str_fname);

    // register implicit conversion to interface
    implicitly_convertible<
      smart_ptr< sql_well >,
      smart_ptr< well_pool_iface >
    >();
  }

}	// namespace python
}	// namespace blue_sky
#endif // #ifdef BSPY_EXPORTING_PLUGIN
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <iostream>
#include <Context.h>
#include <Filter.h>
#include <util.h>
#include <text.h>
#include <i18n.h>
#include <main.h>
#include <CmdDelete.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdDelete::CmdDelete ()
{
  _keyword       = "delete";
  _usage         = "task <filter> delete <mods>";
  _description   = STRING_CMD_DELETE_USAGE;
  _read_only     = false;
  _displays_id   = false;
  _needs_confirm = true;
}

////////////////////////////////////////////////////////////////////////////////
int CmdDelete::execute (std::string& output)
{
  int rc = 0;
  int count = 0;

  // Apply filter.
  Filter filter;
  std::vector <Task> filtered;
  filter.subset (filtered);
  if (filtered.size () == 0)
  {
    context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
    return 1;
  }

  // Accumulated project change notifications.
  std::map <std::string, std::string> projectChanges;

  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    Task before (*task);

    if (task->getStatus () != Task::deleted)
    {
      // Delete the specified task.
      std::string question;
      if (task->id)
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->id,
                           task->get ("description"));
      else
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->get ("uuid"),
                           task->get ("description"));

      task->modify (Task::modAnnotate);
      task->setStatus (Task::deleted);
      if (! task->has ("end"))
        task->setEnd ();

      if (permission (*task, question, filtered.size ()))
      {
        updateRecurrenceMask (*task);
        ++count;
        context.tdb2.modify (*task);
        feedback_affected (STRING_CMD_DELETE_TASK, *task);
        feedback_unblocked (*task);
        dependencyChainOnComplete (*task);
        if (context.verbose ("project"))
          projectChanges[task->get ("project")] = onProjectChange (*task);

        // Delete siblings.
        if (task->has ("parent"))
        {
          if (confirm (STRING_CMD_DELETE_CONFIRM_R))
          {
            std::vector <Task> siblings = context.tdb2.siblings (*task);
            std::vector <Task>::iterator sibling;
            for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)
            {
              sibling->modify (Task::modAnnotate);
              sibling->setStatus (Task::deleted);
              if (! sibling->has ("end"))
                sibling->setEnd ();

              updateRecurrenceMask (*sibling);
              context.tdb2.modify (*sibling);
              feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling);
              feedback_unblocked (*sibling);
              ++count;
            }

            // Delete the parent
            Task parent;
            context.tdb2.get (task->get ("parent"), parent);
            parent.setStatus (Task::deleted);
            if (! parent.has ("end"))
              parent.setEnd ();

            context.tdb2.modify (parent);
          }
        }

        // Task potentially has child tasks - optionally delete them.
        else
        {
          std::vector <Task> children = context.tdb2.children (*task);
          if (children.size () &&
              confirm (STRING_CMD_DELETE_CONFIRM_R))
          {
            std::vector <Task>::iterator child;
            for (child = children.begin (); child != children.end (); ++child)
            {
              child->modify (Task::modAnnotate);
              child->setStatus (Task::deleted);
              if (! child->has ("end"))
                child->setEnd ();

              updateRecurrenceMask (*child);
              context.tdb2.modify (*child);
              feedback_affected (STRING_CMD_DELETE_TASK_R, *child);
              feedback_unblocked (*child);
              ++count;
            }
          }
        }
      }
      else
      {
        std::cout << STRING_CMD_DELETE_NO << "\n";
        rc = 1;
        if (_permission_quit)
          break;
      }
    }
    else
    {
      std::cout << format (STRING_CMD_DELETE_NOT_DEL,
                           task->id,
                           task->get ("description"))
          << "\n";
      rc = 1;
    }
  }

  // Now list the project changes.
  std::map <std::string, std::string>::iterator i;
  for (i = projectChanges.begin (); i != projectChanges.end (); ++i)
    if (i->first != "")
      context.footnote (i->second);

  context.tdb2.commit ();
  feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count);
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdDelete<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <iostream>
#include <Context.h>
#include <Filter.h>
#include <util.h>
#include <text.h>
#include <i18n.h>
#include <main.h>
#include <CmdDelete.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdDelete::CmdDelete ()
{
  _keyword       = "delete";
  _usage         = "task <filter> delete <mods>";
  _description   = STRING_CMD_DELETE_USAGE;
  _read_only     = false;
  _displays_id   = false;
  _needs_confirm = true;
}

////////////////////////////////////////////////////////////////////////////////
int CmdDelete::execute (std::string& output)
{
  int rc = 0;
  int count = 0;

  // Apply filter.
  Filter filter;
  std::vector <Task> filtered;
  filter.subset (filtered);
  if (filtered.size () == 0)
  {
    context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
    return 1;
  }

  // Accumulated project change notifications.
  std::map <std::string, std::string> projectChanges;

  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    Task before (*task);

    if (task->getStatus () != Task::deleted)
    {
      // Delete the specified task.
      std::string question;
      if (task->id)
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->id,
                           task->get ("description"));
      else
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->get ("uuid"),
                           task->get ("description"));

      task->modify (Task::modAnnotate);
      task->setStatus (Task::deleted);
      if (! task->has ("end"))
        task->setEnd ();

      if (permission (*task, question, filtered.size ()))
      {
        updateRecurrenceMask (*task);
        ++count;
        context.tdb2.modify (*task);
        feedback_affected (STRING_CMD_DELETE_TASK, *task);
        feedback_unblocked (*task);
        dependencyChainOnComplete (*task);
        if (context.verbose ("project"))
          projectChanges[task->get ("project")] = onProjectChange (*task);

        // Delete siblings.
        if (task->has ("parent"))
        {
          if (confirm (STRING_CMD_DELETE_CONFIRM_R))
          {
            std::vector <Task> siblings = context.tdb2.siblings (*task);
            std::vector <Task>::iterator sibling;
            for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)
            {
              sibling->modify (Task::modAnnotate);
              sibling->setStatus (Task::deleted);
              if (! sibling->has ("end"))
                sibling->setEnd ();

              updateRecurrenceMask (*sibling);
              context.tdb2.modify (*sibling);
              feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling);
              feedback_unblocked (*sibling);
              ++count;
            }

            // Delete the parent
            Task parent;
            context.tdb2.get (task->get ("parent"), parent);
            parent.setStatus (Task::deleted);
            if (! parent.has ("end"))
              parent.setEnd ();

            context.tdb2.modify (parent);
          }
        }

        // Task potentially has child tasks - optionally delete them.
        else
        {
          std::vector <Task> children = context.tdb2.children (*task);
          if (children.size () &&
              confirm (STRING_CMD_DELETE_CONFIRM_R))
          {
            std::vector <Task>::iterator child;
            for (child = children.begin (); child != children.end (); ++child)
            {
              child->modify (Task::modAnnotate);
              child->setStatus (Task::deleted);
              if (! child->has ("end"))
                child->setEnd ();

              updateRecurrenceMask (*child);
              context.tdb2.modify (*child);
              feedback_affected (STRING_CMD_DELETE_TASK_R, *child);
              feedback_unblocked (*child);
              ++count;
            }
          }
        }
      }
      else
      {
        std::cout << STRING_CMD_DELETE_NO << "\n";
        rc = 1;
        if (_permission_quit)
          break;
      }
    }
    else
    {
      std::cout << format (STRING_CMD_DELETE_NOT_DEL,
                           task->id,
                           task->get ("description"))
          << "\n";
      rc = 1;
    }
  }

  // Now list the project changes.
  std::map <std::string, std::string>::iterator i;
  for (i = projectChanges.begin (); i != projectChanges.end (); ++i)
    if (i->first != "")
      context.footnote (i->second);

  feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count);
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/// @author uentity
/// @date 01.07.2019
/// @copyright
/// This Source Code Form is subject to the terms of the Mozilla Public License,
/// v. 2.0. If a copy of the MPL was not distributed with this file,
/// You can obtain one at https://mozilla.org/MPL/2.0/

#include <bs/serialize/object_formatter.h>
#include <bs/objbase.h>
#include <bs/kernel/misc.h>
#include <bs/uuid.h>

#include <map>
#include <unordered_map>
#include <set>
#include <mutex>

NAMESPACE_BEGIN(blue_sky)
NAMESPACE_BEGIN()

/*-----------------------------------------------------------------------------
 *  Formatters manip impl
 *-----------------------------------------------------------------------------*/
struct fmaster {
	// obj_type_id -> set of unique object_formatter instances sorted by name
	// [NOTE] type_id is stored as string view!
	using fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >;
	fmt_storage_t fmt_storage;

	using registry_t = std::unordered_map<const objbase*, const object_formatter*>;
	registry_t registry;

	using archive_registry_t = std::unordered_multimap<const object_formatter*, void*>;
	archive_registry_t archive_registry;

	// sync access to data above
	std::mutex fmt_guard, reg_guard, arch_reg_guard;

	fmaster() {}
	fmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {}
	fmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {}

	static auto self() -> fmaster& {
		static fmaster& self = []() -> fmaster& {
			// generate random key
			auto& kstorage = kernel::idx_key_storage(to_string(gen_uuid()));
			auto r = kstorage.insert_element(0, fmaster());
			if(!r.first) throw error("Failed to make impl of object formatters in kernel storage!");
			return *r.first;
		}();

		return self;
	}

	auto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool {
		auto solo = std::lock_guard{ fmt_guard };
		return fmt_storage[obj_type.name].insert(std::move(of)).second;
	}

	auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {
		// deny removing fallback binary formatter
		if(fmt_name == detail::bin_fmt_name) return false;

		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			auto& fmt_set = fmts->second;
			if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) {
				// erase format
				fmt_set.erase(pfmt);
				return true;
			}
		}
		return false;
	}

	auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {
		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end())
			return fmts->second.find(fmt_name) != fmts->second.end();
		return false;
	}

	auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {
		auto solo = std::lock_guard{ fmt_guard };
		auto res = std::vector<std::string>{};
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			res.reserve(fmts->second.size());
			for(const auto& f : fmts->second)
				res.emplace_back(f.name);
		}
		return res;
	}

	auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {
		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			auto& fmt_set = fmts->second;
			if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end())
				return &const_cast<object_formatter&>(*pfmt);
		}
		return nullptr;
	}

	auto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void {
		auto solo = std::lock_guard{ reg_guard };
		registry[&obj] = obj_fmt;
	}

	auto deregister_formatter(const objbase& obj) -> void {
		auto solo = std::lock_guard{ reg_guard };
		registry.erase(&obj);
	}

	auto get_obj_formatter(const objbase* obj) -> const object_formatter* {
		auto solo = std::lock_guard{ reg_guard };
		if(auto r = registry.find(obj); r != registry.end())
			return r->second;
		return nullptr;
	}

	auto register_archive(const object_formatter* frm, void* archive) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		archive_registry.emplace(frm, archive);
	}

	auto deregister_archive(const object_formatter* frm) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		archive_registry.erase(frm);
	}

	auto deregister_archive(const object_formatter* frm, void* archive) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {
			if(a->second == archive) {
				archive_registry.erase(a);
				break;
			}
		}
	}

	auto contains_archive(const object_formatter* frm, void* archive) -> bool {
		auto solo = std::lock_guard{ arch_reg_guard };
		for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {
			if(a->second == archive)
				return true;
		}
		return false;
	}

};

NAMESPACE_END()

/*-----------------------------------------------------------------------------
 *  Formatters manip public API
 *-----------------------------------------------------------------------------*/
#define FM fmaster::self()

auto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool {
	return FM.install_formatter(obj_type, std::move(of));
}

auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {
	return FM.uninstall_formatter(obj_type_id, std::move(fmt_name));
}

auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {
	return FM.formatter_installed(obj_type_id, fmt_name);
}

auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {
	return FM.list_installed_formatters(obj_type_id);
}

auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {
	return FM.get_formatter(obj_type_id, fmt_name);
}

auto get_obj_formatter(const objbase* obj) -> const object_formatter* {
	return FM.get_obj_formatter(obj);
}

/*-----------------------------------------------------------------------------
 *  object_formatter
 *-----------------------------------------------------------------------------*/
object_formatter::object_formatter(
	std::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_
) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_)
{}

// compare formatters by name
auto operator<(const object_formatter& lhs, const object_formatter& rhs) {
	return lhs.name < rhs.name;
}
// ... and with arbitrary string key
auto operator<(const object_formatter& lhs, std::string_view rhs) {
	return lhs.name < rhs;
}
auto operator<(std::string_view lhs, const object_formatter& rhs) {
	return lhs < rhs.name;
}

auto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error {
	// if obj has empty payload, skip save
	if(obj.empty_payload()) return tree::Error::EmptyData;

	const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};
	return error::eval_safe([&] {
		FM.register_formatter(obj, this);
		first(*this, obj, std::move(obj_fname), name);
	});
}

auto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error {
	const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};
	return error::eval_safe([&] {
		FM.register_formatter(obj, this);
		second(*this, obj, std::move(obj_fname), name);
	});
}

auto object_formatter::bind_archive(void* archive) const -> void {
	FM.register_archive(this, archive);
}

auto object_formatter::unbind_archive(void* archive) const -> void {
	FM.deregister_archive(this, archive);
}

auto object_formatter::unbind_archive() const -> void {
	FM.deregister_archive(this);
}

auto object_formatter::is_archive_binded(void* archive) const -> bool {
	return FM.contains_archive(this, archive);
}

NAMESPACE_END(blue_sky)
<commit_msg>serial/objformatter: fix loud EmptyData from object_formatter::save()<commit_after>/// @author uentity
/// @date 01.07.2019
/// @copyright
/// This Source Code Form is subject to the terms of the Mozilla Public License,
/// v. 2.0. If a copy of the MPL was not distributed with this file,
/// You can obtain one at https://mozilla.org/MPL/2.0/

#include <bs/serialize/object_formatter.h>
#include <bs/objbase.h>
#include <bs/kernel/misc.h>
#include <bs/uuid.h>

#include <map>
#include <unordered_map>
#include <set>
#include <mutex>

NAMESPACE_BEGIN(blue_sky)
NAMESPACE_BEGIN()

/*-----------------------------------------------------------------------------
 *  Formatters manip impl
 *-----------------------------------------------------------------------------*/
struct fmaster {
	// obj_type_id -> set of unique object_formatter instances sorted by name
	// [NOTE] type_id is stored as string view!
	using fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >;
	fmt_storage_t fmt_storage;

	using registry_t = std::unordered_map<const objbase*, const object_formatter*>;
	registry_t registry;

	using archive_registry_t = std::unordered_multimap<const object_formatter*, void*>;
	archive_registry_t archive_registry;

	// sync access to data above
	std::mutex fmt_guard, reg_guard, arch_reg_guard;

	fmaster() {}
	fmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {}
	fmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {}

	static auto self() -> fmaster& {
		static fmaster& self = []() -> fmaster& {
			// generate random key
			auto& kstorage = kernel::idx_key_storage(to_string(gen_uuid()));
			auto r = kstorage.insert_element(0, fmaster());
			if(!r.first) throw error("Failed to make impl of object formatters in kernel storage!");
			return *r.first;
		}();

		return self;
	}

	auto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool {
		auto solo = std::lock_guard{ fmt_guard };
		return fmt_storage[obj_type.name].insert(std::move(of)).second;
	}

	auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {
		// deny removing fallback binary formatter
		if(fmt_name == detail::bin_fmt_name) return false;

		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			auto& fmt_set = fmts->second;
			if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) {
				// erase format
				fmt_set.erase(pfmt);
				return true;
			}
		}
		return false;
	}

	auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {
		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end())
			return fmts->second.find(fmt_name) != fmts->second.end();
		return false;
	}

	auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {
		auto solo = std::lock_guard{ fmt_guard };
		auto res = std::vector<std::string>{};
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			res.reserve(fmts->second.size());
			for(const auto& f : fmts->second)
				res.emplace_back(f.name);
		}
		return res;
	}

	auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {
		auto solo = std::lock_guard{ fmt_guard };
		if(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {
			auto& fmt_set = fmts->second;
			if(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end())
				return &const_cast<object_formatter&>(*pfmt);
		}
		return nullptr;
	}

	auto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void {
		auto solo = std::lock_guard{ reg_guard };
		registry[&obj] = obj_fmt;
	}

	auto deregister_formatter(const objbase& obj) -> void {
		auto solo = std::lock_guard{ reg_guard };
		registry.erase(&obj);
	}

	auto get_obj_formatter(const objbase* obj) -> const object_formatter* {
		auto solo = std::lock_guard{ reg_guard };
		if(auto r = registry.find(obj); r != registry.end())
			return r->second;
		return nullptr;
	}

	auto register_archive(const object_formatter* frm, void* archive) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		archive_registry.emplace(frm, archive);
	}

	auto deregister_archive(const object_formatter* frm) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		archive_registry.erase(frm);
	}

	auto deregister_archive(const object_formatter* frm, void* archive) -> void {
		auto solo = std::lock_guard{ arch_reg_guard };
		for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {
			if(a->second == archive) {
				archive_registry.erase(a);
				break;
			}
		}
	}

	auto contains_archive(const object_formatter* frm, void* archive) -> bool {
		auto solo = std::lock_guard{ arch_reg_guard };
		for(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {
			if(a->second == archive)
				return true;
		}
		return false;
	}

};

NAMESPACE_END()

/*-----------------------------------------------------------------------------
 *  Formatters manip public API
 *-----------------------------------------------------------------------------*/
#define FM fmaster::self()

auto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool {
	return FM.install_formatter(obj_type, std::move(of));
}

auto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {
	return FM.uninstall_formatter(obj_type_id, std::move(fmt_name));
}

auto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {
	return FM.formatter_installed(obj_type_id, fmt_name);
}

auto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {
	return FM.list_installed_formatters(obj_type_id);
}

auto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {
	return FM.get_formatter(obj_type_id, fmt_name);
}

auto get_obj_formatter(const objbase* obj) -> const object_formatter* {
	return FM.get_obj_formatter(obj);
}

/*-----------------------------------------------------------------------------
 *  object_formatter
 *-----------------------------------------------------------------------------*/
object_formatter::object_formatter(
	std::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_
) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_)
{}

// compare formatters by name
auto operator<(const object_formatter& lhs, const object_formatter& rhs) {
	return lhs.name < rhs.name;
}
// ... and with arbitrary string key
auto operator<(const object_formatter& lhs, std::string_view rhs) {
	return lhs.name < rhs;
}
auto operator<(std::string_view lhs, const object_formatter& rhs) {
	return lhs < rhs.name;
}

auto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error {
	// if obj has empty payload, skip save
	if(obj.empty_payload()) return error::quiet(tree::Error::EmptyData);

	const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};
	return error::eval_safe([&] {
		FM.register_formatter(obj, this);
		first(*this, obj, std::move(obj_fname), name);
	});
}

auto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error {
	const auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};
	return error::eval_safe([&] {
		FM.register_formatter(obj, this);
		second(*this, obj, std::move(obj_fname), name);
	});
}

auto object_formatter::bind_archive(void* archive) const -> void {
	FM.register_archive(this, archive);
}

auto object_formatter::unbind_archive(void* archive) const -> void {
	FM.deregister_archive(this, archive);
}

auto object_formatter::unbind_archive() const -> void {
	FM.deregister_archive(this);
}

auto object_formatter::is_archive_binded(void* archive) const -> bool {
	return FM.contains_archive(this, archive);
}

NAMESPACE_END(blue_sky)
<|endoftext|>


<commit_before>#include <iostream>
#include "net/genecis_server.h"

using namespace std ;

int main() {

	cout << "server running..." << endl ;

//	try{
		int port = 45000 ;
		genecis_server server( port ) ;

		while( true ) {
			genecis_server new_sock ;
			server.accept( new_sock ) ;
//			try{
				while( true ) {
					string data ;
					new_sock >> data ;
					data = "How are you doing today?" ;
					new_sock << data ;
				}
//			} catch (int) {}
		}
//	} catch (int) {}

	cout << "server shutdown" << endl ;
}
<commit_msg>Added couts for debugging.<commit_after>#include <iostream>
#include "net/genecis_server.h"

using namespace std ;

int main() {

	cout << "server running..." << endl ;

//	try{
		int port = 45000 ;
		genecis_server server( port ) ;

		while( true ) {
			cout << "waiting for response from client..." << endl ;
			genecis_server new_sock ;
			server.accept( new_sock ) ;
//			try{
				while( true ) {
					cout << "Client intialized..." << endl ;
					string data ;
					new_sock >> data ;
					data = "How are you doing today?" ;
					new_sock << data ;
				}
//			} catch (int) {}
		}
//	} catch (int) {}

	cout << "server shutdown" << endl ;
}
<|endoftext|>


<commit_before>#include <vector>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <opkele/util.h>
#include <opkele/exception.h>
#include <opkele/server.h>
#include <opkele/data.h>

namespace opkele {
    using namespace std;

    void server_t::associate(const params_t& pin,params_t& pout) {
	util::dh_t dh;
	util::bignum_t c_pub;
	unsigned char key_sha1[SHA_DIGEST_LENGTH];
	enum {
	    sess_cleartext,
	    sess_dh_sha1
	} st = sess_cleartext;
	if(
		pin.has_param("openid.session_type")
		&& pin.get_param("openid.session_type")=="DH-SHA1" ) {
	    /* TODO: fallback to cleartext in case of exceptions here? */
	    if(!(dh = DH_new()))
		throw exception_openssl(OPKELE_CP_ "failed to DH_new()");
	    c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public"));
	    if(pin.has_param("openid.dh_modulus"))
		dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus"));
	    else
		dh->p = util::dec_to_bignum(data::_default_p);
	    if(pin.has_param("openid.dh_gen"))
		dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen"));
	    else
		dh->g = util::dec_to_bignum(data::_default_g);
	    if(!DH_generate_key(dh))
		throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()");
	    vector<unsigned char> ck(DH_size(dh)+1);
	    unsigned char *ckptr = &(ck.front())+1;
	    int cklen = DH_compute_key(&(ck.front()),c_pub,dh);
	    if(cklen<0)
		throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()");
	    if(cklen && (*ckptr)&0x80) {
		(*(--ckptr)) = 0; ++cklen;
	    }
	    SHA1(ckptr,cklen,key_sha1);
	    st = sess_dh_sha1;
	}
	assoc_t assoc = alloc_assoc(mode_associate);
	time_t now = time(0);
	pout.clear();
	pout["assoc_type"] = assoc->assoc_type();
	pout["assoc_handle"] = assoc->handle();
	/* TODO: eventually remove deprecated stuff */
	pout["issued"] = util::time_to_w3c(now);
	pout["expiry"] = util::time_to_w3c(now+assoc->expires_in());
	pout["expires_in"] = util::long_to_string(assoc->expires_in());
	secret_t secret = assoc->secret();
	switch(st) {
	    case sess_dh_sha1:
		pout["session_type"] = "DH-SHA1";
		pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key);
		secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]);
		break;
	    default:
		secret.to_base64(pout["mac_key"]);
		break;
	}
    }

    void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	checkid_(mode_checkid_immediate,pin,return_to,pout,ext);
    }

    void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	checkid_(mode_checkid_setup,pin,return_to,pout,ext);
    }

    void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)
	    throw bad_input(OPKELE_CP_ "invalid checkid_* mode");
	pout.clear();
	assoc_t assoc;
	try {
	    assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
	}catch(failed_lookup& fl) {
	    // no handle specified or no valid handle found, going dumb
	    assoc = alloc_assoc(mode_checkid_setup);
	    if(pin.has_param("openid.assoc_handle"))
		pout["invalidate_handle"]=pin.get_param("openid.assoc_handle");
	}
	string trust_root;
	try {
	    trust_root = pin.get_param("openid.trust_root");
	}catch(failed_lookup& fl) { }
	string identity = pin.get_param("openid.identity");
	return_to = pin.get_param("openid.return_to");
	validate(*assoc,pin,identity,trust_root);
	pout["mode"] = "id_res";
	pout["assoc_handle"] = assoc->handle();
	if(pin.has_param("openid.assoc_handle") && assoc->stateless())
	    pout["invalidate_handle"] = pin.get_param("openid.assoc_handle");
	pout["identity"] = identity;
	pout["return_to"] = return_to;
	/* TODO: eventually remove deprecated stuff */
	time_t now = time(0);
	pout["issued"] = util::time_to_w3c(now);
	pout["valid_to"] = util::time_to_w3c(now+120);
	pout["exipres_in"] = "120";
	pout["signed"]="mode,identity,return_to";
	if(ext) ext->checkid_hook(pin,pout);
	pout.sign(assoc->secret(),pout["sig"],pout["signed"]);
    }

    void server_t::check_authentication(const params_t& pin,params_t& pout) {
	vector<unsigned char>  sig;
	const string& sigenc = pin.get_param("openid.sig");
	util::decode_base64(sigenc,sig);
	assoc_t assoc;
	try {
	    assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
	}catch(failed_lookup& fl) {
	    throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified");
	}
	if(!assoc->stateless())
	    throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle");
	const string& slist = pin.get_param("openid.signed");
	string kv;
	string::size_type p =0;
	while(true) {
	    string::size_type co = slist.find(',',p);
	    string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);
	    kv += f;
	    kv += ':';
	    if(f=="mode")
		kv += "id_res";
	    else {
		f.insert(0,"openid.");
		kv += pin.get_param(f);
	    }
	    kv += '\n';
	    if(co==string::npos)
		break;
	    p = co+1;
	}
	secret_t secret = assoc->secret();
	unsigned int md_len = 0;
	unsigned char *md = HMAC(
		EVP_sha1(),
		&(secret.front()),secret.size(),
		(const unsigned char *)kv.data(),kv.length(),
		0,&md_len);
	pout.clear();
	if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {
	    pout["is_valid"]="true";
	    pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */
	}else{
	    pout["is_valid"]="false";
	    pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */
	}
	if(pin.has_param("openid.invalidate_handle")) {
	    string h = pin.get_param("openid.invalidate_handle");
	    try {
		assoc_t assoc = retrieve_assoc(h);
	    }catch(invalid_handle& ih) {
		pout["invalidate_handle"] = h;
	    }catch(failed_lookup& fl) { }
	}
    }

}
<commit_msg>yet another signature bugfix<commit_after>#include <vector>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <opkele/util.h>
#include <opkele/exception.h>
#include <opkele/server.h>
#include <opkele/data.h>

namespace opkele {
    using namespace std;

    void server_t::associate(const params_t& pin,params_t& pout) {
	util::dh_t dh;
	util::bignum_t c_pub;
	unsigned char key_sha1[SHA_DIGEST_LENGTH];
	enum {
	    sess_cleartext,
	    sess_dh_sha1
	} st = sess_cleartext;
	if(
		pin.has_param("openid.session_type")
		&& pin.get_param("openid.session_type")=="DH-SHA1" ) {
	    /* TODO: fallback to cleartext in case of exceptions here? */
	    if(!(dh = DH_new()))
		throw exception_openssl(OPKELE_CP_ "failed to DH_new()");
	    c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public"));
	    if(pin.has_param("openid.dh_modulus"))
		dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus"));
	    else
		dh->p = util::dec_to_bignum(data::_default_p);
	    if(pin.has_param("openid.dh_gen"))
		dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen"));
	    else
		dh->g = util::dec_to_bignum(data::_default_g);
	    if(!DH_generate_key(dh))
		throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()");
	    vector<unsigned char> ck(DH_size(dh)+1);
	    unsigned char *ckptr = &(ck.front())+1;
	    int cklen = DH_compute_key(ckptr,c_pub,dh);
	    if(cklen<0)
		throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()");
	    if(cklen && (*ckptr)&0x80) {
		(*(--ckptr)) = 0; ++cklen;
	    }
	    SHA1(ckptr,cklen,key_sha1);
	    st = sess_dh_sha1;
	}
	assoc_t assoc = alloc_assoc(mode_associate);
	time_t now = time(0);
	pout.clear();
	pout["assoc_type"] = assoc->assoc_type();
	pout["assoc_handle"] = assoc->handle();
	/* TODO: eventually remove deprecated stuff */
	pout["issued"] = util::time_to_w3c(now);
	pout["expiry"] = util::time_to_w3c(now+assoc->expires_in());
	pout["expires_in"] = util::long_to_string(assoc->expires_in());
	secret_t secret = assoc->secret();
	switch(st) {
	    case sess_dh_sha1:
		pout["session_type"] = "DH-SHA1";
		pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key);
		secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]);
		break;
	    default:
		secret.to_base64(pout["mac_key"]);
		break;
	}
    }

    void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	checkid_(mode_checkid_immediate,pin,return_to,pout,ext);
    }

    void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	checkid_(mode_checkid_setup,pin,return_to,pout,ext);
    }

    void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
	if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)
	    throw bad_input(OPKELE_CP_ "invalid checkid_* mode");
	pout.clear();
	assoc_t assoc;
	try {
	    assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
	}catch(failed_lookup& fl) {
	    // no handle specified or no valid handle found, going dumb
	    assoc = alloc_assoc(mode_checkid_setup);
	    if(pin.has_param("openid.assoc_handle"))
		pout["invalidate_handle"]=pin.get_param("openid.assoc_handle");
	}
	string trust_root;
	try {
	    trust_root = pin.get_param("openid.trust_root");
	}catch(failed_lookup& fl) { }
	string identity = pin.get_param("openid.identity");
	return_to = pin.get_param("openid.return_to");
	validate(*assoc,pin,identity,trust_root);
	pout["mode"] = "id_res";
	pout["assoc_handle"] = assoc->handle();
	if(pin.has_param("openid.assoc_handle") && assoc->stateless())
	    pout["invalidate_handle"] = pin.get_param("openid.assoc_handle");
	pout["identity"] = identity;
	pout["return_to"] = return_to;
	/* TODO: eventually remove deprecated stuff */
	time_t now = time(0);
	pout["issued"] = util::time_to_w3c(now);
	pout["valid_to"] = util::time_to_w3c(now+120);
	pout["exipres_in"] = "120";
	pout["signed"]="mode,identity,return_to";
	if(ext) ext->checkid_hook(pin,pout);
	pout.sign(assoc->secret(),pout["sig"],pout["signed"]);
    }

    void server_t::check_authentication(const params_t& pin,params_t& pout) {
	vector<unsigned char>  sig;
	const string& sigenc = pin.get_param("openid.sig");
	util::decode_base64(sigenc,sig);
	assoc_t assoc;
	try {
	    assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
	}catch(failed_lookup& fl) {
	    throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified");
	}
	if(!assoc->stateless())
	    throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle");
	const string& slist = pin.get_param("openid.signed");
	string kv;
	string::size_type p =0;
	while(true) {
	    string::size_type co = slist.find(',',p);
	    string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);
	    kv += f;
	    kv += ':';
	    if(f=="mode")
		kv += "id_res";
	    else {
		f.insert(0,"openid.");
		kv += pin.get_param(f);
	    }
	    kv += '\n';
	    if(co==string::npos)
		break;
	    p = co+1;
	}
	secret_t secret = assoc->secret();
	unsigned int md_len = 0;
	unsigned char *md = HMAC(
		EVP_sha1(),
		&(secret.front()),secret.size(),
		(const unsigned char *)kv.data(),kv.length(),
		0,&md_len);
	pout.clear();
	if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {
	    pout["is_valid"]="true";
	    pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */
	}else{
	    pout["is_valid"]="false";
	    pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */
	}
	if(pin.has_param("openid.invalidate_handle")) {
	    string h = pin.get_param("openid.invalidate_handle");
	    try {
		assoc_t assoc = retrieve_assoc(h);
	    }catch(invalid_handle& ih) {
		pout["invalidate_handle"] = h;
	    }catch(failed_lookup& fl) { }
	}
    }

}
<|endoftext|>


<commit_before>// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

/*============================================================================*/
/*==== Titre: Aspect_Handle.hxx                                               */
/*==== Role : The header file of primitive type "Handle" from packages        */
/*==== "Xw" & "WNT"                                                           */
/*==== Implementation:  This is a primitive type implemented with typedef     */
/*============================================================================*/

#ifndef _Aspect_Handle_HeaderFile
#define _Aspect_Handle_HeaderFile

#ifdef WNT
 typedef void*         HANDLE;
 typedef HANDLE        Aspect_Handle;
#else
 typedef unsigned long Aspect_Handle;
#endif /* WNT */

#if defined(__cplusplus) || defined(c_plusplus)
/*==== Definition de Type ====================================================*/

#include <Standard_Macro.hxx>
class Handle(Standard_Type);
const Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);

/*============================================================================*/
#endif

#endif /* _Aspect_Handle_HeaderFile */
<commit_msg>Define OCE_NULL_Aspect_Handle for use in V3d_View.hxx<commit_after>// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

/*============================================================================*/
/*==== Titre: Aspect_Handle.hxx                                               */
/*==== Role : The header file of primitive type "Handle" from packages        */
/*==== "Xw" & "WNT"                                                           */
/*==== Implementation:  This is a primitive type implemented with typedef     */
/*============================================================================*/

#ifndef _Aspect_Handle_HeaderFile
#define _Aspect_Handle_HeaderFile

#ifdef WNT
 typedef void*         HANDLE;
 typedef HANDLE        Aspect_Handle;
#else
 typedef unsigned long Aspect_Handle;
#endif /* WNT */

#if defined(__cplusplus) || defined(c_plusplus)
/*==== Definition de Type ====================================================*/

#include <Standard_Macro.hxx>
class Handle(Standard_Type);
const Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);

/*============================================================================*/
#endif

#define OCE_NULL_Aspect_Handle ((Aspect_Handle)NULL)

#endif /* _Aspect_Handle_HeaderFile */
<|endoftext|>


<commit_before>/*
  This file is part of Kontact.

  Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

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

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

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "todoplugin.h"
#include "todosummarywidget.h"
#include "korg_uniqueapp.h"
#include "calendarinterface.h"

#include <kontactinterfaces/core.h>

#include <libkdepim/maillistdrag.h>
#include <libkdepim/kdepimprotocols.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/kpimprefs.h>

#include <kcal/calendarlocal.h>
#include <kcal/icaldrag.h>

#include <kaction.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <ktemporaryfile.h>

#include <QWidget>
#include <QDropEvent>
#include <QtDBus/QtDBus>

EXPORT_KONTACT_PLUGIN( TodoPlugin, todo )

TodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )
  : Kontact::Plugin( core, core, "korganizer" ), mIface( 0 )
{
  setComponentData( KontactPluginFactory::componentData() );
  KIconLoader::global()->addAppDir( "korganizer" );
  KIconLoader::global()->addAppDir( "kdepim" );

  KAction *action =
    new KAction( KIcon( "task-new" ), i18n( "New To-do..." ), this );
  actionCollection()->addAction( "new_todo", action );
  action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );
  connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );
  insertNewAction( action );

  KAction *syncAction =
    new KAction( KIcon( "view-refresh" ), i18n( "Sync To-do List" ), this );
  connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );
  insertSyncAction( syncAction );

  mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
    new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}

TodoPlugin::~TodoPlugin()
{
}

Kontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )
{
  return new TodoSummaryWidget( this, parent );
}

KParts::ReadOnlyPart *TodoPlugin::createPart()
{
  KParts::ReadOnlyPart *part = loadPart();

  if ( !part ) {
    return 0;
  }

  mIface = new OrgKdeKorganizerCalendarInterface(
    "org.kde.korganizer", "/Calendar", QDBusConnection::sessionBus(), this );

  return part;
}

void TodoPlugin::select()
{
  interface()->showTodoView();
}

QStringList TodoPlugin::invisibleToolbarActions() const
{
  QStringList invisible;
  invisible += "new_event";
  invisible += "new_todo";
  invisible += "new_journal";

  invisible += "view_day";
  invisible += "view_list";
  invisible += "view_workweek";
  invisible += "view_week";
  invisible += "view_nextx";
  invisible += "view_month";
  invisible += "view_journal";
  return invisible;
}

OrgKdeKorganizerCalendarInterface *TodoPlugin::interface()
{
  if ( !mIface ) {
    part();
  }
  Q_ASSERT( mIface );
  return mIface;
}

void TodoPlugin::slotNewTodo()
{
  interface()->openTodoEditor( "" );
}

void TodoPlugin::slotSyncTodos()
{
  QDBusMessage message =
      QDBusMessage::createMethodCall( "org.kde.kmail", "/Groupware",
                                      "org.kde.kmail.groupware",
                                      "triggerSync" );
  message << QString( "Todo" );
  QDBusConnection::sessionBus().send( message );
}

bool TodoPlugin::createDBUSInterface( const QString &serviceType )
{
  if ( serviceType == "DBUS/Organizer" || serviceType == "DBUS/Calendar" ) {
    if ( part() ) {
      return true;
    }
  }
  return false;
}

bool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )
{
  return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||
         KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );
}

bool TodoPlugin::isRunningStandalone()
{
  return mUniqueAppWatcher->isRunningStandalone();
}

void TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KPIM::KVCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KPIM::KVCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18n( "Meeting" ), QString(), QStringList(), attendees );
    return;
  }

  if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {
    KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );
    if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {
      KCal::Journal::List journals = cal.journals();
      if ( !journals.isEmpty() ) {
        event->accept();
        KCal::Journal *j = journals.first();
        interface()->openTodoEditor(
          i18n( "Note: %1", j->summary() ), j->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry( core(),
                          i18n( "Drops of multiple mails are not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18n( "From: %1\nTo: %2\nSubject: %3", mail.from(), mail.to(), mail.subject() );
      QString uri = KDEPIMPROTOCOL_EMAIL +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18n( "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  KMessageBox::sorry( core(), i18n( "Cannot handle drop events of type '%1'.", event->format() ) );
}

#include "todoplugin.moc"
<commit_msg>Take incidences, no journals. This way we are able to read the drop event, and create the TODO entry.<commit_after>/*
  This file is part of Kontact.

  Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

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

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

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "todoplugin.h"
#include "todosummarywidget.h"
#include "korg_uniqueapp.h"
#include "calendarinterface.h"

#include <kontactinterfaces/core.h>

#include <libkdepim/maillistdrag.h>
#include <libkdepim/kdepimprotocols.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/kpimprefs.h>

#include <kcal/calendarlocal.h>
#include <kcal/icaldrag.h>

#include <kaction.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <ktemporaryfile.h>

#include <QWidget>
#include <QDropEvent>
#include <QtDBus/QtDBus>

EXPORT_KONTACT_PLUGIN( TodoPlugin, todo )

TodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )
  : Kontact::Plugin( core, core, "korganizer" ), mIface( 0 )
{
  setComponentData( KontactPluginFactory::componentData() );
  KIconLoader::global()->addAppDir( "korganizer" );
  KIconLoader::global()->addAppDir( "kdepim" );

  KAction *action =
    new KAction( KIcon( "task-new" ), i18n( "New To-do..." ), this );
  actionCollection()->addAction( "new_todo", action );
  action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );
  connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );
  insertNewAction( action );

  KAction *syncAction =
    new KAction( KIcon( "view-refresh" ), i18n( "Sync To-do List" ), this );
  connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );
  insertSyncAction( syncAction );

  mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
    new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}

TodoPlugin::~TodoPlugin()
{
}

Kontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )
{
  return new TodoSummaryWidget( this, parent );
}

KParts::ReadOnlyPart *TodoPlugin::createPart()
{
  KParts::ReadOnlyPart *part = loadPart();

  if ( !part ) {
    return 0;
  }

  mIface = new OrgKdeKorganizerCalendarInterface(
    "org.kde.korganizer", "/Calendar", QDBusConnection::sessionBus(), this );

  return part;
}

void TodoPlugin::select()
{
  interface()->showTodoView();
}

QStringList TodoPlugin::invisibleToolbarActions() const
{
  QStringList invisible;
  invisible += "new_event";
  invisible += "new_todo";
  invisible += "new_journal";

  invisible += "view_day";
  invisible += "view_list";
  invisible += "view_workweek";
  invisible += "view_week";
  invisible += "view_nextx";
  invisible += "view_month";
  invisible += "view_journal";
  return invisible;
}

OrgKdeKorganizerCalendarInterface *TodoPlugin::interface()
{
  if ( !mIface ) {
    part();
  }
  Q_ASSERT( mIface );
  return mIface;
}

void TodoPlugin::slotNewTodo()
{
  interface()->openTodoEditor( "" );
}

void TodoPlugin::slotSyncTodos()
{
  QDBusMessage message =
      QDBusMessage::createMethodCall( "org.kde.kmail", "/Groupware",
                                      "org.kde.kmail.groupware",
                                      "triggerSync" );
  message << QString( "Todo" );
  QDBusConnection::sessionBus().send( message );
}

bool TodoPlugin::createDBUSInterface( const QString &serviceType )
{
  if ( serviceType == "DBUS/Organizer" || serviceType == "DBUS/Calendar" ) {
    if ( part() ) {
      return true;
    }
  }
  return false;
}

bool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )
{
  return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||
         KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );
}

bool TodoPlugin::isRunningStandalone()
{
  return mUniqueAppWatcher->isRunningStandalone();
}

void TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KPIM::KVCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KPIM::KVCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18n( "Meeting" ), QString(), QStringList(), attendees );
    return;
  }

  if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {
    KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );
    if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {
      KCal::Incidence::List incidences = cal.incidences();
      Q_ASSERT(incidences.count());
      if ( !incidences.isEmpty() ) {
        event->accept();
        KCal::Incidence *i = incidences.first();
        interface()->openTodoEditor(
          i18n( "Note: %1", i->summary() ), i->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry( core(),
                          i18n( "Drops of multiple mails are not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18n( "From: %1\nTo: %2\nSubject: %3", mail.from(), mail.to(), mail.subject() );
      QString uri = KDEPIMPROTOCOL_EMAIL +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18n( "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  KMessageBox::sorry( core(), i18n( "Cannot handle drop events of type '%1'.", event->format() ) );
}

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


<commit_before>#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include <portal.h>

#include "sock_fd.h"
#include "sock_utils.h"

static struct portal p_fd = iport;
static int fd[16];
static unsigned char *buffer[16];
static unsigned long buffer_len[16];
static int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

extern "C" {

  void init_pareff(){

    pthread_t tid;

    struct channel* rc;
    struct channel* wc;

    fprintf(stderr, "BsimDma::init_pareff()\n");

    rc = &(p_fd.read);
    snprintf(rc->path, sizeof(rc->path), "fd_sock_rc");

    wc = &(p_fd.write);
    snprintf(wc->path, sizeof(wc->path), "fd_sock_wc");

    if(pthread_create(&tid, NULL,  init_socket, (void*)rc)){
      fprintf(stderr, "error creating init thread\n");
      //exit(1);
    }

    if(pthread_create(&tid, NULL,  init_socket, (void*)wc)){
      fprintf(stderr, "error creating init thread\n");
      //exit(1);
    }

  }

  void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    *(unsigned int *)&buffer[pref-1][offset] = data;
  }

  unsigned int read_pareff32(unsigned long pref, unsigned long offset){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];
    //fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx)=%08x\n", pref, offset,rv);
    return rv;
  }

  void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \n", pref, offset, pref-1, buffer_len[pref-1]);
    *(unsigned long long *)&buffer[pref-1][offset] = data;
    //fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\n", pref, offset, data);
  }

  unsigned long long read_pareff64(unsigned long pref, unsigned long offset){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];
    //fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx)=%016llx\n", pref, offset,rv);
    return rv;
  }

  unsigned long pareff(unsigned long pref, unsigned long size){
    //fprintf(stderr, "BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\n", pref, size, size_accum[pref-1]);
    assert(pref < 16);
    size_accum[pref-1] += size;
    if(size == 0){
      sock_fd_read(p_fd.write.s2, &(fd[pref-1]));
      buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);
      buffer_len[pref-1] = size_accum[pref-1]/sizeof(unsigned char);
      return buffer[pref-1];
    } else {
      return 0;
    }
  }

}
<commit_msg>fixing build break.  someone must have tweaked the compile flags<commit_after>#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include <portal.h>

#include "sock_fd.h"
#include "sock_utils.h"

static struct portal p_fd = iport;
static int fd[16];
static unsigned char *buffer[16];
static unsigned long buffer_len[16];
static int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

extern "C" {

  void init_pareff(){

    pthread_t tid;

    struct channel* rc;
    struct channel* wc;

    fprintf(stderr, "BsimDma::init_pareff()\n");

    rc = &(p_fd.read);
    snprintf(rc->path, sizeof(rc->path), "fd_sock_rc");

    wc = &(p_fd.write);
    snprintf(wc->path, sizeof(wc->path), "fd_sock_wc");

    if(pthread_create(&tid, NULL,  init_socket, (void*)rc)){
      fprintf(stderr, "error creating init thread\n");
      //exit(1);
    }

    if(pthread_create(&tid, NULL,  init_socket, (void*)wc)){
      fprintf(stderr, "error creating init thread\n");
      //exit(1);
    }

  }

  void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    *(unsigned int *)&buffer[pref-1][offset] = data;
  }

  unsigned int read_pareff32(unsigned long pref, unsigned long offset){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];
    //fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx)=%08x\n", pref, offset,rv);
    return rv;
  }

  void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \n", pref, offset, pref-1, buffer_len[pref-1]);
    *(unsigned long long *)&buffer[pref-1][offset] = data;
    //fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\n", pref, offset, data);
  }

  unsigned long long read_pareff64(unsigned long pref, unsigned long offset){
    if(buffer_len[pref-1] <= offset)
      fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
    unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];
    //fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx)=%016llx\n", pref, offset,rv);
    return rv;
  }

  unsigned long pareff(unsigned long pref, unsigned long size){
    //fprintf(stderr, "BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\n", pref, size, size_accum[pref-1]);
    assert(pref < 16);
    size_accum[pref-1] += size;
    if(size == 0){
      sock_fd_read(p_fd.write.s2, &(fd[pref-1]));
      buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);
      buffer_len[pref-1] = size_accum[pref-1]/sizeof(unsigned char);
      return (unsigned long)buffer[pref-1];
    } else {
      return 0;
    }
  }

}
<|endoftext|>


<commit_before>#include "pixelboost/script/luaManager.h"

extern "C"
{
#include "pixelboost/external/lua/lua.h"
#include "pixelboost/external/lua/lauxlib.h"
#include "pixelboost/external/lua/lualib.h"
}

using namespace pixelboost;

LuaManager::LuaManager()
{
    _State = luaL_newstate();
    luaL_openlibs(_State);
}

LuaManager::~LuaManager()
{
    lua_close(_State);
}

void LuaManager::Open(const std::string& filename)
{
    if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))
    {
        printf("Can't open file: %s", lua_tostring(_State, -1));
    }
}
<commit_msg>Use provided lua.hpp<commit_after>#include "pixelboost/script/luaManager.h"
#include "pixelboost/external/lua/lua.hpp"

using namespace pixelboost;

LuaManager::LuaManager()
{
    _State = luaL_newstate();
    luaL_openlibs(_State);
}

LuaManager::~LuaManager()
{
    lua_close(_State);
}

void LuaManager::Open(const std::string& filename)
{
    if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))
    {
        printf("Can't open file: %s", lua_tostring(_State, -1));
    }
}
<|endoftext|>