text:
#include <iostream>

#define BOOST_TEST_MODULE MertForestRescore
#include <boost/test/unit_test.hpp>

#include "Hypergraph.h"

using namespace std;
using namespace MosesTuning;

BOOST_AUTO_TEST_CASE(prune)
{
  Vocab vocab;
  WordVec words;
  string wordStrings[] =
  {"<s>", "</s>", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"};
  for (size_t i = 0; i < 13; ++i) {
    words.push_back(&(vocab.FindOrAdd((wordStrings[i]))));
  }

  const string f1 = "foo";
  const string f2 = "bar";
  Graph graph(vocab);
  graph.SetCounts(5,8);

  Edge* e0 = graph.NewEdge();
  e0->AddWord(words[0]);

  Vertex* v0 = graph.NewVertex();
  v0->AddEdge(e0);

  Edge* e1 = graph.NewEdge();
  e1->AddWord(NULL);
  e1->AddChild(0);
  e1->AddWord(words[2]);
  e1->AddWord(words[3]);
  e1->AddFeature(f1,1);
  e1->AddFeature(f2,1);
  Edge* e5 = graph.NewEdge();
  e5->AddWord(NULL);
  e5->AddChild(0);
  e5->AddWord(words[9]);
  e5->AddWord(words[10]);
  e5->AddFeature(f1,2);
  e5->AddFeature(f2,-2);

  Vertex* v1 = graph.NewVertex();
  v1->AddEdge(e1);
  v1->AddEdge(e5);
  v1->SetSourceCovered(1);

  Edge* e2 = graph.NewEdge();
  e2->AddWord(NULL);
  e2->AddChild(1);
  e2->AddWord(words[4]);
  e2->AddWord(words[5]);
  e2->AddFeature(f2,3);

  Vertex* v2 = graph.NewVertex();
  v2->AddEdge(e2);
  v2->SetSourceCovered(3);

  Edge* e3 = graph.NewEdge();
  e3->AddWord(NULL);
  e3->AddChild(2);
  e3->AddWord(words[6]);
  e3->AddWord(words[7]);
  e3->AddWord(words[8]);
  e3->AddFeature(f1,1);
  Edge* e6 = graph.NewEdge();
  e6->AddWord(NULL);
  e6->AddChild(2);
  e6->AddWord(words[9]);
  e6->AddWord(words[12]);
  e6->AddFeature(f2,1);
  Edge* e7 = graph.NewEdge();
  e7->AddWord(NULL);
  e7->AddChild(1);
  e7->AddWord(words[11]);
  e7->AddWord(words[12]);
  e7->AddFeature(f1,2);
  e7->AddFeature(f2,3);

  Vertex* v3 = graph.NewVertex();
  v3->AddEdge(e3);
  v3->AddEdge(e6);
  v3->AddEdge(e7);
  v3->SetSourceCovered(5);

  Edge* e4 = graph.NewEdge();
  e4->AddWord(NULL);
  e4->AddChild(3);
  e4->AddWord(words[1]);

  Vertex* v4 = graph.NewVertex();
  v4->AddEdge(e4);
  v4->SetSourceCovered(6);

  SparseVector weights;
  weights.set(f1,2);
  weights.set(f2,1);

  Graph pruned(vocab);
  graph.Prune(&pruned, weights, 5);

  BOOST_CHECK_EQUAL(5, pruned.EdgeSize());
  BOOST_CHECK_EQUAL(4, pruned.VertexSize());

  //edges retained should be best path (<s> ab jk </s>) and hi
  BOOST_CHECK_EQUAL(1, pruned.GetVertex(0).GetIncoming().size());
  BOOST_CHECK_EQUAL(2, pruned.GetVertex(1).GetIncoming().size());
  BOOST_CHECK_EQUAL(1, pruned.GetVertex(2).GetIncoming().size());
  BOOST_CHECK_EQUAL(1, pruned.GetVertex(3).GetIncoming().size());

  const Edge* edge;

  edge =  pruned.GetVertex(0).GetIncoming()[0];
  BOOST_CHECK_EQUAL(1, edge->Words().size());
  BOOST_CHECK_EQUAL(words[0], edge->Words()[0]);

  edge =  pruned.GetVertex(1).GetIncoming()[0];
  BOOST_CHECK_EQUAL(3, edge->Words().size());
  BOOST_CHECK_EQUAL((Vocab::Entry*)NULL, edge->Words()[0]);
  BOOST_CHECK_EQUAL(words[2]->first, edge->Words()[1]->first);
  BOOST_CHECK_EQUAL(words[3]->first, edge->Words()[2]->first);

  edge =  pruned.GetVertex(1).GetIncoming()[1];
  BOOST_CHECK_EQUAL(3, edge->Words().size());
  BOOST_CHECK_EQUAL((Vocab::Entry*)NULL, edge->Words()[0]);
  BOOST_CHECK_EQUAL(words[9]->first, edge->Words()[1]->first);
  BOOST_CHECK_EQUAL(words[10]->first, edge->Words()[2]->first);

  edge =  pruned.GetVertex(2).GetIncoming()[0];
  BOOST_CHECK_EQUAL(3, edge->Words().size());
  BOOST_CHECK_EQUAL((Vocab::Entry*)NULL, edge->Words()[0]);
  BOOST_CHECK_EQUAL(words[11]->first, edge->Words()[1]->first);
  BOOST_CHECK_EQUAL(words[12]->first, edge->Words()[2]->first);

  edge =  pruned.GetVertex(3).GetIncoming()[0];
  BOOST_CHECK_EQUAL(2, edge->Words().size());
  BOOST_CHECK_EQUAL((Vocab::Entry*)NULL, edge->Words()[0]);
  BOOST_CHECK_EQUAL(words[1]->first, edge->Words()[1]->first);

//  BOOST_CHECK_EQUAL(words[0], pruned.GetVertex(0).GetIncoming()[0].Words()[0]);

}

max_stars_repo_name: ugermann/MMT

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#include "Framework/TestingFramework.hpp"

#include <boost/functional/hash.hpp>
#include <cstddef>
#include <numeric>
#include <unordered_map>
#include <utility>
#include <vector>

#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/Index.hpp"
#include "DataStructures/SliceIterator.hpp"
#include "DataStructures/Variables.hpp"
#include "Domain/Structure/Direction.hpp"
#include "Domain/Structure/DirectionMap.hpp"
#include "Domain/Structure/Element.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "Domain/Structure/Neighbors.hpp"
#include "Evolution/DgSubcell/CorrectPackagedData.hpp"
#include "Evolution/DgSubcell/Mesh.hpp"
#include "Evolution/DgSubcell/Projection.hpp"
#include "Evolution/DiscontinuousGalerkin/MortarData.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "NumericalAlgorithms/Spectral/Spectral.hpp"
#include "Time/Slab.hpp"
#include "Time/Time.hpp"
#include "Time/TimeStepId.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"

namespace {
struct Var1 : db::SimpleTag {
  using type = Scalar<DataVector>;
};

template <size_t Dim>
struct Var2 : db::SimpleTag {
  using type = tnsr::i<DataVector, Dim, Frame::Inertial>;
};

template <size_t Dim>
void test() {
  CAPTURE(Dim);
  using Vars = Variables<tmpl::list<Var1, Var2<Dim>>>;
  const Mesh<Dim> volume_dg_mesh{5, Spectral::Basis::Legendre,
                                 Spectral::Quadrature::GaussLobatto};
  const Mesh<Dim> volume_subcell_mesh =
      evolution::dg::subcell::fd::mesh(volume_dg_mesh);
  DirectionMap<Dim, Neighbors<Dim>> neighbors{};
  for (size_t i = 0; i < 2 * Dim; ++i) {
    neighbors[gsl::at(Direction<Dim>::all_directions(), i)] =
        Neighbors<Dim>{{ElementId<Dim>{i + 1, {}}}, {}};
  }
  const Element<Dim> element{ElementId<Dim>{0, {}}, neighbors};
  const TimeStepId time_step_id{true, 1, Time{Slab{1.1, 4.4}, {3, 10}}};

  CAPTURE(volume_dg_mesh);
  CAPTURE(volume_subcell_mesh);
  for (size_t direction_to_check = 0; direction_to_check < Dim;
       ++direction_to_check) {
    CAPTURE(direction_to_check);
    Index<Dim> volume_face_extents = volume_subcell_mesh.extents();
    ++volume_face_extents[direction_to_check];
    Vars lower_packaged_data{volume_face_extents.product()};
    Vars upper_packaged_data{volume_face_extents.product()};
    const size_t number_of_independent_components = Variables<
        tmpl::list<Var1, Var2<Dim>>>::number_of_independent_components;
    const auto set_volume_data = [&lower_packaged_data,
                                  &upper_packaged_data]() {
      std::iota(lower_packaged_data.data(),
                lower_packaged_data.data() + lower_packaged_data.size(), 1.0);
      std::iota(upper_packaged_data.data(),
                upper_packaged_data.data() + upper_packaged_data.size(),
                1.0 + upper_packaged_data.size());
    };
    set_volume_data();
    // Save a copy of the lower/upper data so we can compare points in the
    // volume/away from the interfaces.
    const Vars interior_lower_packaged_data = lower_packaged_data;
    const Vars interior_upper_packaged_data = upper_packaged_data;

    std::unordered_map<std::pair<Direction<Dim>, ElementId<Dim>>,
                       evolution::dg::MortarData<Dim>,
                       boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>
        mortar_data{};
    const Direction<Dim> upper{direction_to_check, Side::Upper};
    const Direction<Dim> lower{direction_to_check, Side::Lower};
    const std::pair upper_neighbor{upper,
                                   *element.neighbors().at(upper).begin()};
    const std::pair lower_neighbor{lower,
                                   *element.neighbors().at(lower).begin()};
    evolution::dg::MortarData<Dim>& upper_mortar_data =
        mortar_data[upper_neighbor] = {};
    evolution::dg::MortarData<Dim>& lower_mortar_data =
        mortar_data[lower_neighbor] = {};

    const Mesh<Dim - 1> dg_face_mesh =
        volume_dg_mesh.slice_away(direction_to_check);
    std::vector<double> upper_neighbor_data(
        number_of_independent_components *
        dg_face_mesh.number_of_grid_points());
    std::iota(upper_neighbor_data.begin(), upper_neighbor_data.end(),
              1.0 + 2.0 * upper_packaged_data.size());
    std::vector<double> lower_neighbor_data(
        number_of_independent_components *
        dg_face_mesh.number_of_grid_points());
    std::iota(
        lower_neighbor_data.begin(), lower_neighbor_data.end(),
        1.0 + 2.0 * upper_packaged_data.size() + upper_neighbor_data.size());

    upper_mortar_data.insert_neighbor_mortar_data(time_step_id, dg_face_mesh,
                                                  upper_neighbor_data);
    lower_mortar_data.insert_neighbor_mortar_data(time_step_id, dg_face_mesh,
                                                  lower_neighbor_data);

    // Check with only remote data
    evolution::dg::subcell::correct_package_data<false>(
        make_not_null(&lower_packaged_data),
        make_not_null(&upper_packaged_data), direction_to_check, element,
        volume_subcell_mesh, mortar_data);

    const size_t volume_grid_points = volume_face_extents.product();
    const size_t slice_grid_points =
        volume_face_extents.slice_away(direction_to_check).product();
    const Mesh<Dim - 1> subcell_face_mesh =
        volume_subcell_mesh.slice_away(direction_to_check);
    const auto perform_face_check = [&dg_face_mesh, direction_to_check,
                                     slice_grid_points, &subcell_face_mesh,
                                     &volume_face_extents, volume_grid_points](
                                        const auto& face_dg_data,
                                        const auto& volume_packaged_data,
                                        const size_t subcell_index) {
      Vars face_vars_data{dg_face_mesh.number_of_grid_points()};
      std::copy(face_dg_data.begin(), face_dg_data.end(),
                face_vars_data.data());
      if constexpr (Dim > 1) {
        face_vars_data = evolution::dg::subcell::fd::project(
            face_vars_data, dg_face_mesh, subcell_face_mesh.extents());
      } else {
        (void)subcell_face_mesh;
      }
      for (SliceIterator si(volume_face_extents, direction_to_check,
                            subcell_index);
           si; ++si) {
        CAPTURE(si.volume_offset());
        CAPTURE(si.slice_offset());
        for (size_t i = 0; i < number_of_independent_components; ++i) {
          CAPTURE(i);
          CHECK(volume_packaged_data
                    .data()[i * volume_grid_points + si.volume_offset()] ==
                approx(face_vars_data
                           .data()[i * slice_grid_points + si.slice_offset()]));
        }
      }
    };
    const auto perform_interior_check =
        [direction_to_check, &volume_face_extents, volume_grid_points](
            const auto& expected_volume_packaged_data,
            const auto& volume_packaged_data, const size_t start_index,
            const size_t one_past_end_index) {
          for (size_t slice_index = start_index;
               slice_index < one_past_end_index; ++slice_index) {
            for (SliceIterator si(volume_face_extents, direction_to_check,
                                  slice_index);
                 si; ++si) {
              for (size_t i = 0; i < number_of_independent_components; ++i) {
                CHECK(volume_packaged_data.data()[i * volume_grid_points +
                                                  si.volume_offset()] ==
                      approx(expected_volume_packaged_data
                                 .data()[i * volume_grid_points +
                                         si.volume_offset()]));
              }
            }
          }
        };

    perform_face_check(upper_neighbor_data, upper_packaged_data,
                       volume_face_extents[direction_to_check] - 1);
    perform_face_check(lower_neighbor_data, lower_packaged_data, 0);
    perform_interior_check(interior_upper_packaged_data, upper_packaged_data, 0,
                           volume_face_extents[direction_to_check] - 1);
    perform_interior_check(interior_lower_packaged_data, lower_packaged_data, 1,
                           volume_face_extents[direction_to_check]);

    // Reset volume data and then check that we can project both local and
    // remote data (note the `true` template parameter to
    // `correct_package_data`)
    set_volume_data();

    std::vector<double> upper_local_data(number_of_independent_components *
                                         dg_face_mesh.number_of_grid_points());
    std::iota(upper_local_data.begin(), upper_local_data.end(), 1.0e6);
    std::vector<double> lower_local_data(number_of_independent_components *
                                         dg_face_mesh.number_of_grid_points());
    std::iota(lower_local_data.begin(), lower_local_data.end(), 1.0e7);
    upper_mortar_data.insert_local_mortar_data(time_step_id, dg_face_mesh,
                                               upper_local_data);
    lower_mortar_data.insert_local_mortar_data(time_step_id, dg_face_mesh,
                                               lower_local_data);

    evolution::dg::subcell::correct_package_data<true>(
        make_not_null(&lower_packaged_data),
        make_not_null(&upper_packaged_data), direction_to_check, element,
        volume_subcell_mesh, mortar_data);

    perform_face_check(upper_neighbor_data, upper_packaged_data,
                       volume_face_extents[direction_to_check] - 1);
    perform_face_check(lower_neighbor_data, lower_packaged_data, 0);
    perform_face_check(upper_local_data, lower_packaged_data,
                       volume_face_extents[direction_to_check] - 1);
    perform_face_check(lower_local_data, upper_packaged_data, 0);

    perform_interior_check(interior_upper_packaged_data, upper_packaged_data, 1,
                           volume_face_extents[direction_to_check] - 1);
    perform_interior_check(interior_lower_packaged_data, lower_packaged_data, 1,
                           volume_face_extents[direction_to_check] - 1);

    // Check that if the local data is in the map but not requested to be
    // overwritten then we don't overwrite it.
    set_volume_data();

    evolution::dg::subcell::correct_package_data<false>(
        make_not_null(&lower_packaged_data),
        make_not_null(&upper_packaged_data), direction_to_check, element,
        volume_subcell_mesh, mortar_data);

    perform_face_check(upper_neighbor_data, upper_packaged_data,
                       volume_face_extents[direction_to_check] - 1);
    perform_face_check(lower_neighbor_data, lower_packaged_data, 0);

    perform_interior_check(interior_upper_packaged_data, upper_packaged_data, 0,
                           volume_face_extents[direction_to_check] - 1);
    perform_interior_check(interior_lower_packaged_data, lower_packaged_data, 1,
                           volume_face_extents[direction_to_check]);
  }
}
}  // namespace

SPECTRE_TEST_CASE("Unit.Evolution.Subcell.CorrectPackagedData",
                  "[Evolution][Unit]") {
  test<1>();
  test<2>();
  test<3>();
}

ext: cpp

max_stars_repo_name: nilsvu/spectre

max_issues_repo_name: GitHimanshuc/spectre


text:
/*
 * Copyright 2009-2021 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.
 *
 */

// Standard includes
#include <cassert>
#include <memory>
#include <regex>
#include <stdexcept>
#include <unordered_set>

// Third party includes
#include <boost/lexical_cast.hpp>

// VOTCA includes
#include <votca/tools/rangeparser.h>

// Local VOTCA includes
#include "votca/csg/boundarycondition.h"
#include "votca/csg/interaction.h"
#include "votca/csg/molecule.h"
#include "votca/csg/openbox.h"
#include "votca/csg/topology.h"

namespace votca {
namespace csg {

using namespace std;

bool is_digits(const std::string &str) {
  return str.find_first_not_of("0123456789") == std::string::npos;
}

Topology::~Topology() { Cleanup(); }

void Topology::Cleanup() {
  // cleanup beads
  beads_.clear();

  // cleanup molecules
  molecules_.clear();

  // cleanup residues
  residues_.clear();

  // cleanup interactions
  {
    for (InteractionContainer::iterator i = interactions_.begin();
         i < interactions_.end(); ++i) {
      delete (*i);
    }
    interactions_.clear();
  }
  // cleanup  bc_ object
  bc_ = std::make_unique<OpenBox>();
}

/// \todo implement checking, only used in xml topology reader
void Topology::CreateMoleculesByRange(string name, Index first, Index nbeads,
                                      Index nmolecules) {
  Molecule *mol = CreateMolecule(name);
  Index beadcount = 0;
  Index res_offset = 0;

  for (auto &bead_ : beads_) {
    // xml numbering starts with 1
    if (--first > 0) {
      continue;
    }
    // This is not 100% correct, but let's assume for now that the resnr do
    // increase
    if (beadcount == 0) {
      res_offset = bead_.getResnr();
    }
    stringstream bname;
    bname << bead_.getResnr() - res_offset + 1 << ":"
          << getResidue(bead_.getResnr()).getName() << ":" << bead_.getName();
    mol->AddBead(&bead_, bname.str());
    if (++beadcount == nbeads) {
      if (--nmolecules <= 0) {
        break;
      }
      mol = CreateMolecule(name);
      beadcount = 0;
    }
  }
}

void Topology::CopyTopologyData(Topology *top) {

  bc_->setBox(top->getBox());
  time_ = top->time_;
  step_ = top->step_;

  // cleanup old data
  Cleanup();

  // copy all residues
  for (const auto &residue_ : top->residues_) {
    CreateResidue(residue_.getName());
  }

  // create all beads
  for (const auto &bi : top->beads_) {
    string type = bi.getType();
    CreateBead(bi.getSymmetry(), bi.getName(), type, bi.getResnr(),
               bi.getMass(), bi.getQ(), bi.getC6(), bi.getC12());
  }

  // copy all molecules
  for (const auto &molecule_ : top->molecules_) {
    Molecule *mi = CreateMolecule(molecule_.getName());
    for (Index i = 0; i < molecule_.BeadCount(); i++) {
      Index beadid = molecule_.getBead(i)->getId();
      mi->AddBead(&beads_[beadid], molecule_.getBeadName(i));
    }
  }
}

Index Topology::getBeadTypeId(string type) const {
  assert(beadtypes_.count(type));
  return beadtypes_.at(type);
}

void Topology::RenameMolecules(string range, string name) {
  tools::RangeParser rp;
  rp.Parse(range);
  for (Index i : rp) {
    if (i > Index(molecules_.size())) {
      throw runtime_error(
          string("RenameMolecules: num molecules smaller than"));
    }
    getMolecule(i - 1)->setName(name);
  }
}

void Topology::RenameBeadType(string name, string newname) {

  for (auto &bead : beads_) {
    string type = bead.getType();
    if (tools::wildcmp(name, type)) {
      bead.setType(newname);
    }
  }
}

void Topology::SetBeadTypeMass(string name, double value) {
  for (auto &bead : beads_) {
    string type = bead.getType();
    if (tools::wildcmp(name, type)) {
      bead.setMass(value);
    }
  }
}

void Topology::CheckMoleculeNaming(void) {
  map<string, Index> nbeads;

  for (const auto &mol : molecules_) {
    map<string, Index>::iterator entry = nbeads.find(mol.getName());
    if (entry != nbeads.end()) {
      if (entry->second != mol.BeadCount()) {
        throw runtime_error(
            "There are molecules which have the same name but different number "
            "of bead "
            "please check the section manual topology handling in the votca "
            "manual");
      }
      continue;
    }
    nbeads[mol.getName()] = mol.BeadCount();
  }
}

void Topology::AddBondedInteraction(Interaction *ic) {
  map<string, Index>::iterator iter = interaction_groups_.find(ic->getGroup());
  if (iter != interaction_groups_.end()) {
    ic->setGroupId(iter->second);
  } else {
    Index i = interaction_groups_.size();
    interaction_groups_[ic->getGroup()] = i;
    ic->setGroupId(i);
  }
  interactions_.push_back(ic);
  interactions_by_group_[ic->getGroup()].push_back(ic);
}

std::vector<Interaction *> Topology::InteractionsInGroup(const string &group) {
  map<string, vector<Interaction *>>::iterator iter =
      interactions_by_group_.find(group);
  if (iter == interactions_by_group_.end()) {
    return vector<Interaction *>();
  }
  return iter->second;
}

bool Topology::BeadTypeExist(string type) const {
  return beadtypes_.count(type);
}

void Topology::RegisterBeadType(string type) {
  unordered_set<Index> ids;
  for (pair<const string, Index> type_and_id : beadtypes_) {
    ids.insert(type_and_id.second);
  }

  Index id = 0;
  // If the type is also a number use it as the id as well provided it is not
  // already taken
  if (is_digits(type)) {
    id = boost::lexical_cast<Index>(type);
    assert(!ids.count(id) &&
           "The type passed in is a number and has already"
           " been registered. It is likely that you are passing in numbers as "
           "bead types as well as strings, choose one or the other do not mix "
           "between using numbers and strings ");
  }

  while (ids.count(id)) {
    ++id;
  }
  beadtypes_[type] = id;
}

Eigen::Vector3d Topology::BCShortestConnection(
    const Eigen::Vector3d &r_i, const Eigen::Vector3d &r_j) const {
  return bc_->BCShortestConnection(r_i, r_j);
}

Eigen::Vector3d Topology::getDist(Index bead1, Index bead2) const {
  return BCShortestConnection(getBead(bead1)->getPos(),
                              getBead(bead2)->getPos());
}

double Topology::BoxVolume() const { return bc_->BoxVolume(); }

void Topology::RebuildExclusions() { exclusions_.CreateExclusions(this); }

BoundaryCondition::eBoxtype Topology::autoDetectBoxType(
    const Eigen::Matrix3d &box) const {
  // set the box type to OpenBox in case "box" is the zero matrix,
  // to OrthorhombicBox in case "box" is a diagonal matrix,
  // or to TriclinicBox otherwise
  if (box.isApproxToConstant(0)) {
    return BoundaryCondition::typeOpen;
  } else if ((box - Eigen::Matrix3d(box.diagonal().asDiagonal()))
                 .isApproxToConstant(0)) {
    return BoundaryCondition::typeOrthorhombic;
  } else {
    return BoundaryCondition::typeTriclinic;
  }
  return BoundaryCondition::typeOpen;
}

double Topology::ShortestBoxSize() const {
  return bc_->getShortestBoxDimension();
}

void Topology::setCutoff(double cutoff){
  cutoff_ = cutoff;
}

double Topology::getCutoff(){
  return cutoff_;
}

void Topology::setDielectric(double epsilon_r){
  epsilon_r_ = epsilon_r;
}

double Topology::getDielectic(){
  return epsilon_r_;
}

}  // namespace csg
}  // namespace votca

ext: cc

max_stars_repo_name: vklip/votca

max_issues_repo_name: vklip/votca

max_forks_repo_name: vklip/votca


text:
// Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

#include <lxml/lxml.h>
#include <mxml/EventFactory.h>
#include <mxml/JumpFactory.h>
#include <mxml/LoopFactory.h>
#include <mxml/parsing/ScoreHandler.h>

#include <boost/test/unit_test.hpp>
#include <fstream>
#include <unistd.h>

using namespace mxml;
using namespace mxml::parsing;

static const char* kLoopsFileName = "loops.xml";
static const char* kRepeatsFileName = "repeats.xml";

BOOST_AUTO_TEST_CASE(loops) {
    ScoreHandler handler;
    std::ifstream is(kLoopsFileName);
    lxml::parse(is, kLoopsFileName, handler);

    const dom::Score& score = *handler.result();
    LoopFactory loopFactory(score);
    auto loops = loopFactory.build();

    BOOST_CHECK_EQUAL(loops.size(), 2);

    // First loop starts at measure 1 and ends at measure 3 (measures 1 and 2 are repeated)
    BOOST_CHECK_EQUAL(loops[0].begin(), 1);
    BOOST_CHECK_EQUAL(loops[0].end(), 3);
    BOOST_CHECK_EQUAL(loops[0].count(), 1);
    BOOST_CHECK(!loops[0].isSkipped(0, 1));
    BOOST_CHECK(!loops[0].isSkipped(0, 2));

    // The second loops has endings. The order should be 3, 4, 3, 5
    BOOST_CHECK_EQUAL(loops[1].begin(), 3);
    BOOST_CHECK_EQUAL(loops[1].end(), 5);
    BOOST_CHECK_EQUAL(loops[1].count(), 1);
    BOOST_CHECK(loops[1].isSkipped(0, 5));
    BOOST_CHECK(loops[1].isSkipped(1, 4));
}

BOOST_AUTO_TEST_CASE(repeats) {
    ScoreHandler handler;
    std::ifstream is(kRepeatsFileName);
    lxml::parse(is, kRepeatsFileName, handler);

    const dom::Score& score = *handler.result();
    JumpFactory jumpFactory(score);
    auto jumps = jumpFactory.build();

    BOOST_CHECK_EQUAL(jumps.size(), 2);

    // To coda jump from measure 2 to 4
    BOOST_CHECK_EQUAL(jumps[0].from, 2);
    BOOST_CHECK_EQUAL(jumps[0].to, 4);

    // Dal segno jump from measure 5 to 0
    BOOST_CHECK_EQUAL(jumps[1].from, 5);
    BOOST_CHECK_EQUAL(jumps[1].to, 0);
}


text:
#pragma once

#include <functional>
#include <ostream>
#include <string>

#include <boost/assert.hpp>
#include <boost/config.hpp>

#include "blackhole/detail/config/nullptr.hpp"
#include "blackhole/detail/support/char.hpp"

#include "streambuf.hpp"

namespace blackhole {

namespace aux {

template<typename Char, class Traits = std::char_traits<Char>, class Allocator = std::allocator<Char> >
class attachable_basic_ostringstream : public std::basic_ostream<Char, Traits> {
public:
    typedef Char char_type;
    typedef Traits traits_type;
    typedef Allocator allocator_type;
    typedef basic_ostringstreambuf<Char, Traits, Allocator> streambuf_type;
    typedef typename streambuf_type::string_type string_type;

    typedef std::basic_ostream<Char, Traits> ostream_type;
    typedef typename ostream_type::int_type int_type;
    typedef typename ostream_type::pos_type pos_type;
    typedef typename ostream_type::off_type off_type;

private:
    typedef std::ios_base&(*ios_base_manip)(std::ios_base&);
    typedef std::basic_ios<char_type, traits_type>&(*basic_ios_manip)(std::basic_ios<char_type, traits_type>&);
    typedef ostream_type&(*stream_manip)(ostream_type&);

    streambuf_type streambuf;

public:
    //!@note: According to the 27.7.3.2/4 `std::basic_ostream` dtor does not perform any
    //!       operations on rdbuf(), so it can be in broken state. However there is no mention
    //!       about `std::basic_ostream` ctor behaviour on passing non-initialized `streambuf`
    //!       member pointer.
    //!       I am pretty sure it's safe, because `std::ostringstream` does the same way.
    attachable_basic_ostringstream() :
        ostream_type(&streambuf)
    {
        initialize();
    }

    explicit attachable_basic_ostringstream(string_type& string) :
        ostream_type(&streambuf),
        streambuf(std::ref(string))
    {
        initialize();
    }

    attachable_basic_ostringstream(const attachable_basic_ostringstream & other) = delete;
    attachable_basic_ostringstream& operator=(const attachable_basic_ostringstream& other) = delete;

    ~attachable_basic_ostringstream() {
        if (streambuf.storage()) {
            this->flush();
        }
    }

    void attach(string_type& string) {
        streambuf.attach(string);
        ostream_type::clear(ostream_type::goodbit);
    }

    void detach() {
        streambuf.detach();
        ostream_type::clear(ostream_type::badbit);
    }

    const string_type& str() {
        this->flush();

        string_type* storage = streambuf.storage();
        BOOST_ASSERT(storage != nullptr);

        return *storage;
    }

    attachable_basic_ostringstream& flush() {
        ostream_type::flush();
        return *this;
    }

    attachable_basic_ostringstream& seekp(pos_type pos) {
        ostream_type::seekp(pos);
        return *this;
    }

    attachable_basic_ostringstream& seekp(off_type off, std::ios_base::seekdir dir) {
        ostream_type::seekp(off, dir);
        return *this;
    }

    streambuf_type* rdbuf() {
        return &streambuf;
    }

    attachable_basic_ostringstream& put(char_type c) {
        ostream_type::put(c);
        return *this;
    }

    template<typename T>
    typename std::enable_if<supported_char<T>::value, T>::type put(T c) {
        write(boost::addressof(c), 1);
        return *this;
    }

    attachable_basic_ostringstream& write(const char_type* p, std::streamsize size) {
        ostream_type::write(p, size);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(ios_base_manip manip) {
        ostream_type::operator<<(manip);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(basic_ios_manip manip) {
        ostream_type::operator<<(manip);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(stream_manip manip) {
        ostream_type::operator<<(manip);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(char c) {
        put(c);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(const char* p) {
        write(p, static_cast<std::streamsize>(std::char_traits<char>::length(p)));
        return *this;
    }

    attachable_basic_ostringstream& operator<<(bool value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(signed char value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(unsigned char value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(short value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(unsigned short value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(int value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(unsigned int value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(long value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(unsigned long value) {
        ostream_type::operator<<(value);
        return *this;
    }

#if !defined(BOOST_NO_LONG_LONG)
    attachable_basic_ostringstream& operator<<(long long value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(unsigned long long value) {
        ostream_type::operator<<(value);
        return *this;
    }
#endif

    attachable_basic_ostringstream& operator<<(float value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(double value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(long double value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(const void* value) {
        ostream_type::operator<<(value);
        return *this;
    }

    attachable_basic_ostringstream& operator<<(std::basic_streambuf<char_type, traits_type>* buf) {
        ostream_type::operator<<(buf);
        return *this;
    }

    template<class T, class OtherTraits, class OtherAllocator >
    typename std::enable_if<supported_char<T>::value, attachable_basic_ostringstream&>::type
    operator<<(const std::basic_string<T, OtherTraits, OtherAllocator>& str) {
        write(str.c_str(), static_cast<std::streamsize>(str.size()));
        return *this;
    }

private:
    void initialize() {
        ostream_type::clear(streambuf.storage() ? ostream_type::goodbit : ostream_type::badbit);
        ostream_type::flags(ostream_type::dec | ostream_type::skipws | ostream_type::boolalpha);
        ostream_type::width(0);
        ostream_type::precision(6);
        ostream_type::fill(static_cast<char_type>(' '));
    }
};

typedef attachable_basic_ostringstream<char> attachable_ostringstream;

} // namespace aux

} // namespace blackhole

ext: hpp

max_stars_repo_name: bioothod/blackhole

max_issues_repo_name: bioothod/blackhole

max_forks_repo_name: bioothod/blackhole


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_IS_NEGATIVE_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_IS_NEGATIVE_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-predicates
    Function object implementing is_negative capabilities

    Returns @ref True if x is negative else @ref False.

    This function differs from @ref is_ltz for floating point arguments,
    because @ref Mzero is negative but not less than zero, and @ref Mzero is
    not positive and not greater than zero, It's probably @ref is_ltz that
    you want.

    @par Semantic:

    @code
    auto r = is_negative(x);
    @endcode

    is similar to:

    @code
    if x is of signed type
      auto r = bitofsign(x) == 1;
    else
      auto r = False;
    @endcode

    @par Note:

    @ref Mzero is the floating point 'minus zero',
    i.e. all bits are @ref Zero but the sign bit.
    Such a value is treated as @ref Zero by IEEE standards.

    behaviour of is_negative on @ref Nan entry is undefined.

    @par Alias

    signbit

    @see is_positive,  Mzero, bitofsign

  **/
  as_logical_t<Value> is_negative(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/is_negative.hpp>
#include <boost/simd/function/simd/is_negative.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#ifndef CONFIG_H
#define CONFIG_H

//#define BOOST_LIB_DIAGNOSTIC
#include <iostream>
#include <map>
#include <assert.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include "ProjectProperty/include/ProjectProperty.hpp"
#include "ProjectProperty/include/ConfigEntry.hpp"

class Config
{
public:
	Config();

	~Config();

	static Config* getInstance();

	static void setInstance(Config* newInst);

	static void getConfigFile(const std::string _directoryName);

	static void LoadProfiles();

	static void loadConfig();

	bool loadFromFile();

	static int getInt(const std::string& id);

	static bool getBool(const std::string& id);

	static std::string getString(const std::string& id);

	static float getFloat(const std::string& id);

	static bool getFloatMinMax(const std::string& id, std::pair<float, float>& minmax);

	static bool getIntMinMax(const std::string& id, std::pair<int, int>& minmax);

	void clear();

	static Config* m_inst;

	static std::map<std::string, ConfigEntry > m_values;

	static std::vector<std::string> profilesToLoad;

	static std::string DirectoryName;

private:
	static boost::mutex Mutex;

	template<class T> T get(const std::string& id) const;

	template<class T> bool getMinMax(const std::string& id, std::pair<T, T>& minmax) const;

	std::string m_fileName;

};

template<> inline float Config::get(const std::string& id) const
{
	boost::mutex::scoped_lock lock(Mutex);
	std::map<std::string, ConfigEntry >::const_iterator it = m_values.find(id);
	if (it == m_values.end())
	{
		LOGEROR("Config: ERROR Config value '" << id << "' not found! Exiting!");
	}
	assert(it != m_values.end());

	ConfigEntry::eType t = it->second.getType();

	if (t != ConfigEntry::TYPE_FLOAT)
	{
		std::cerr << "Config: ERROR Config value '" << id << "' has wrong type! Exiting!" << std::endl;
	}
	assert(t == ConfigEntry::TYPE_FLOAT);
	float value = it->second.getFloat();
	return value;
}

template<>inline int Config::get(const std::string& id) const
{
	boost::mutex::scoped_lock lock(Mutex);
	std::map<std::string, ConfigEntry>::const_iterator it = m_values.find(id);
	if (it == m_values.end())
	{
		std::cerr << "Config: ERROR Config value '" << id << "' not found! Exiting!" << std::endl;
	}
	assert(it != m_values.end());

	ConfigEntry::eType t = it->second.getType();
	if (t != ConfigEntry::TYPE_INT)
	{
		std::cerr << "Config: ERROR Config value '" << id << "' has wrong type! Exiting!" << std::endl;
	}
	int value = it->second.getInt();
	assert(t == ConfigEntry::TYPE_INT);
	return value;
}

template<>inline const char* Config::get(const std::string& id) const
{
	boost::mutex::scoped_lock lock(Mutex);
	std::map<std::string, ConfigEntry>::const_iterator it = m_values.find(id);
	if (it == m_values.end())
	{
		std::cerr << "Config: ERROR Config value '" << id << "' not found! Exiting!" << std::endl;
	}
	assert(it != m_values.end());

    ConfigEntry::eType t = it->second.getType();
	if (t != ConfigEntry::TYPE_STRING)
	{
		std::cerr << "Config: ERROR Config value '" << id << "' has wrong type! Exiting!" << std::endl;
	}
	assert(t == ConfigEntry::TYPE_STRING);
	const char* value = it->second.getString();
	return value;
}

template<>inline std::string Config::get(const std::string& id) const
{
	return get<const char*>(id);
}

template<class T> bool Config::getMinMax(const std::string& id, std::pair<T, T>& minmax) const
{
	std::map<std::string, ConfigEntry>::const_iterator it = m_values.find(id);
	if (it == m_values.end())
	{
		std::cerr << "Config: ERROR Config value '" << id << "' not found! Exiting!" << std::endl;
	}
	assert(it != m_values.end());

	ConfigEntry::eType t = it->second.getType();
	if (t == ConfigEntry::TYPE_INT)
	{
		int mi = it->second.getIntMin();
		int ma = it->second.getIntMax();
		if (mi == ma) return false;
		minmax = std::make_pair(mi, ma);
		return true;
	}
	else if (t == ConfigEntry::TYPE_FLOAT)
	{
		float mi = it->second.getFloatMin();
		float ma = it->second.getFloatMax();
		if (mi == ma) return false;
		minmax = std::make_pair(mi, ma);
		return true;
	}
	return false;
}

#endif

max_stars_repo_name: ParoRahul/ImageDetection

max_issues_repo_name: ParoRahul/ImageDetection

max_forks_repo_name: ParoRahul/ImageDetection


text:
#include <NTL/ZZXFactoring.h>

NTL_CLIENT

long compare(const ZZX& a, const ZZX& b)
{
   if (deg(a) < deg(b))
      return 0;

   if (deg(a) > deg(b))
      return 1;

   long n = a.rep.length();
   long i;

   for (i = 0; i < n; i++) {
      if (a.rep[i] < b.rep[i]) return 0;
      if (a.rep[i] > b.rep[i]) return 1;
   }

   return 0;
}

void sort(vec_pair_ZZX_long& v)
{
   long n = v.length();
   long i, j;

   for (i = 0; i < n-1; i++)
      for (j = 0; j < n-1-i; j++)
         if (compare(v[j].a, v[j+1].a)) {
            swap(v[j].a, v[j+1].a);
            swap(v[j].b, v[j+1].b);
         }
}

int main(int argc, char **argv)
{
   ZZX f1, f;

   if (argc > 1)
      ZZXFac_MaxPrune = atoi(argv[1]);

   cin >> f;

   vec_pair_ZZX_long factors;
   ZZ c;

   double t;

   t = GetTime();
   factor(c, factors, f, 0);
   t = GetTime()-t;

   cerr << "total time: " << t << "\n";

   mul(f1, factors);
   mul(f1, f1, c);

   if (f != f1)
      Error("FACTORIZATION INCORRECT!!!");

   sort(factors);

   cout << c << "\n";
   cout << factors << "\n";

   return 0;
}

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


text:
// ---------------------------------------------------------------------------|
// Boost Test Framework
// ---------------------------------------------------------------------------|
#include <boost/test/unit_test.hpp>

// ---------------------------------------------------------------------------|
// Yuma Test Harness includes
// ---------------------------------------------------------------------------|
#include "test/support/fixtures/simple-container-module-fixture.h"
#include "test/support/misc-util/log-utils.h"
#include "test/support/nc-query-util/nc-query-test-engine.h"

// ---------------------------------------------------------------------------|
namespace YumaTest {

BOOST_FIXTURE_TEST_SUITE( discard_changes_tests, SimpleContainerModuleFixture )

BOOST_AUTO_TEST_CASE( slt_discard_new_container )
{
    DisplayTestDescrption(
            "Demonstrate discard-changes operation on uncomitted "
            "container creation.",
            "Procedure: \n"
            "\t 1 - Create the top level container for the module\n"
            "\t 2 - Populate the list with 3 key-value pairs\n"
            "\t 3 - Check all values are in the candidate\n"
            "\t 4 - Check all values are not in the running\n"
            "\t 5 - Discard the changes\n"
            "\t 6 - Check all values are not in the candidate\n"
            "\t 7 - Check all values are not in the running\n"
            "\t 8 - Commit the operation\n"
            "\t 9 - Check all values are not in the candidate\n"
            "\t10 - Check all values are not in the running\n"
            );

    // RAII Vector of database locks
    vector< unique_ptr< NCDbScopedLock > > locks = getFullLock( primarySession_ );

    createMainContainer( primarySession_ );

    // set some values
    populateDatabase( 3 );
    // check the entries exist
    checkEntries( primarySession_ );

    // discard entries
    discardChangesOperation( primarySession_ );
    // check the entries no longer exist
    checkEntries( primarySession_ );

    commitChanges( primarySession_ );
    checkEntries( primarySession_ );

}

BOOST_AUTO_TEST_CASE( slt_discard_list_additions )
{
    DisplayTestDescrption(
            "Demonstrate discard-changes operation on uncomitted "
            "list addition.",
            "Procedure: \n"
            "\t 1 - Create the top level container for the module\n"
            "\t 2 - Populate the list with 3 key-value pairs\n"
            "\t 3 - Check all values are in the candidate\n"
            "\t 4 - Check all values are not in the running\n"
            "\t 5 - Commit the operation\n"
            "\t 6 - Check all values are in the running\n"
            "\t 7 - Check all values are in the candidate\n"
            "\t 8 - Populate the list with 2 additional key-value pairs\n"
            "\t 9 - Check all values are in the candidate\n"
            "\t10 - Check additional values are not in the running\n"
            "\t11 - Discard the changes\n"
            "\t12 - Check additional values are not in the candidate\n"
            "\t13 - Check additional values are not in the running\n"
            "\t14 - Delete all entries from the candidate\n"
            "\t15 - Check all values are not in the candidate\n"
            "\t16 - Check all values are in the running\n"
            "\t17 - Commit the operation\n"
            "\t18 - Check all values are not in the candidate\n"
            "\t19 - Check all values are not in the running\n"
            );

    // RAII Vector of database locks
    vector< unique_ptr< NCDbScopedLock > > locks = getFullLock( primarySession_ );

    createMainContainer( primarySession_ );

    // set some values
    populateDatabase( 3 );
    // check the entries exist
    checkEntries( primarySession_ );

    commitChanges( primarySession_ );
    checkEntries( primarySession_ );

    // set some more values
    addEntryValuePair( primarySession_, "entryKey4", "entryVal4" );
    addEntryValuePair( primarySession_, "entryKey5", "entryVal5" );
    // check the entries exist
    checkEntries( primarySession_ );

    // discard new entries
    discardChangesOperation( primarySession_ );
    // check the new entries were discarded
    checkEntries( primarySession_ );

    // remove all entries
    deleteMainContainer( primarySession_ );
    checkEntries( primarySession_ );

    commitChanges( primarySession_ );
    checkEntries( primarySession_ );

}

BOOST_AUTO_TEST_CASE( slt_discard_list_edits )
{
    DisplayTestDescrption(
            "Demonstrate discard-changes operation on uncomitted "
            "list edits.",
            "Procedure: \n"
            "\t 1 - Create the top level container for the module\n"
            "\t 2 - Populate the list with 3 key-value pairs\n"
            "\t 3 - Check all values are in the candidate\n"
            "\t 4 - Check all values are not in the running\n"
            "\t 5 - Commit the operation\n"
            "\t 6 - Check all values are in the running\n"
            "\t 7 - Check all values are in the candidate\n"
            "\t 8 - Modify 2 of the key-value pairs\n"
            "\t 9 - Check modified values are in the candidate\n"
            "\t10 - Check modified values are not in the running\n"
            "\t11 - Discard the changes\n"
            "\t12 - Check edited values are not in the candidate\n"
            "\t13 - Check edited values are not in the running\n"
            "\t14 - Delete all entries from the candidate\n"
            "\t15 - Check all values are not in the candidate\n"
            "\t16 - Check all values are in the running\n"
            "\t17 - Commit the operation\n"
            "\t18 - Check all values are not in the candidate\n"
            "\t19 - Check all values are not in the running\n"
            );

    // RAII Vector of database locks
    vector< unique_ptr< NCDbScopedLock > > locks = getFullLock( primarySession_ );

    createMainContainer( primarySession_ );

    // set some values
    populateDatabase( 3 );
    // check the entries exist
    checkEntries( primarySession_ );

    commitChanges( primarySession_ );
    checkEntries( primarySession_ );

    // modify some values
    editEntryValue( primarySession_, "entryKey1", "newVal1" );
    editEntryValue( primarySession_, "entryKey3", "newVal3" );

    // discard modifications
    discardChangesOperation( primarySession_ );
    // check the edits were discarded
    checkEntries( primarySession_ );

    // remove all entries
    deleteMainContainer( primarySession_ );
    checkEntries( primarySession_ );

    commitChanges( primarySession_ );
    checkEntries( primarySession_ );

}

// ---------------------------------------------------------------------------|
BOOST_AUTO_TEST_SUITE_END()

} // namespace YumaTest


text:
#ifndef MEMORY_NETWORK
#define MEMORY_NETWORK

#include <Eigen/Dense>
#include <map>
#include <set>
#include <string>
#include <random>
#include <chrono>
#include <thread>
#include <functional>

typedef Eigen::MatrixXd MemoryMatrix;
typedef Eigen::VectorXd MemoryVector;

typedef std::function<void(std::chrono::duration<long int, std::micro>,
                           const MemoryVector&)> LoggingFunction;

class MemoryNetwork
{

public:

    /** Creates a new associative memory network, initially empty.
     *
     * Call `add_unit` to add new units to the network. `size` returns the
     * current size of the network.
     *
     * Call `start` to start the network. Note that new units can be added at
     * any time, including when the network is running.
     *
     */
    MemoryNetwork(LoggingFunction activations_log_fn = nullptr, // user-defined callback used to store activation history
                  LoggingFunction external_activations_log_fn = nullptr, // user-defined callback used to store external activation history
                  double Dg = 0.2,     // activation decay (per ms)
                  double Lg = 0.01,    // learning rate (per ms)
                  double Eg = 0.6,     // external influence
                  double Ig = 0.3,     // internal influence
                  double Amax = 1.0,   // maximum activation
                  double Amin = -0.2,  // minimum activation
                  double Arest = -0.1, // rest activation
                  double Winit = 0.0); // initial weights

    void reset();

    /** Activate one unit at a specific level, for a specific duration.
     */
    void activate_unit(size_t id,
                    double level = 1.0,
                    std::chrono::microseconds duration = std::chrono::milliseconds(200));

    /** Activate one unit at a specific level, for a specific duration.
     *
     * Raises a `range_error` exception is the unit does not exist.
     */
    void activate_unit(const std::string& name,
                    double level = 1.0,
                    std::chrono::microseconds duration = std::chrono::milliseconds(200));

    /** Returns the list of all unit names, ordered by their internal IDs.
     *
     * The order is guaranteed to remain the same from one call to the other,
     * even after calling `reset` or `stop`.
     */
    std::vector<std::string> units_names() const {return _units_names;}

    /**
     * Adds a new unit to the network.
     *
     * Returns the internal ID of the newly created unit.
     *
     * Raises a `runtime_error` if the name is already in used.
     */
    size_t add_unit(const std::string& name);

    /** Returns true if the network already has a unit named `name`, false
     * otherwise.
     */
    bool has_unit(const std::string& name) const;

    /** Returns the internal ID of a unit.
     *
     * Raises a `range_error` exception is the unit does not exist.
     */
    size_t unit_id(const std::string& name) const;

    MemoryVector activations() const {return _activations;}
    MemoryMatrix weights() const {return _weights;}

    size_t size() const {return _size;}
    int frequency() const {return _frequency;}

    /** Slow down the memory update mechanism (typically, for debugging) up to
     * 'freq' updated per seconds
     *
     * The update frequency is set to max_freq.  Calling slowdown with
     * max_freq=0 removes any previously set limit.
     */
    void max_frequency(double freq);
    std::chrono::microseconds internal_period() const {return _min_period;}

    /** Changes between physical time and simulated time.
     *
     * By default, the network uses real, physical time.
     */
    void use_physical_time(bool use) {_use_physical_time = use;}

    /** Returns true if using real physical time, false if using simulated time.
     */
    bool is_using_physical_time() const {return _use_physical_time;}

    /** Returns the elapsed time since the network started.
     *
     * If the network has not started yet, returns 0.
     */
    std::chrono::microseconds elapsed_time() const;

    /** Configure the network parameters.
     * Possible parameter names are:
     *  - Dg: decay rate
     *  - Lg: learning rate
     *  - Eg: external influence
     *  - Ig: internal influence
     *  - Amax: maximum activation
     *  - Amin: minimum activation
     *  - Arest: rest activation
     *  - Winit: initial weights
     */
    void set_parameter(const std::string& name, double value);

    /* Returns the current value of a network parameter.
     * See `set_parameter` documentation for the list of parameters.
     *
     * Throws a `range_error` exception if the parameter does not exist.
     */
    double get_parameter(const std::string& name) const;

    /** Starts the memory system
     *
     * Note that the current weights and activations are *not* reset: as such,
     * one may call stop() then start() to pause/unpause the network.
     * Call reset() to actually reset the network to its initial empty
     * state.
     */
    void start();
    void stop();
    bool isrunning() const {return _is_running;}

    void record(bool enabled) {_is_recording=enabled;}
    bool isrecording() {return _is_recording;}
    void save_record();

    double Dg;
    double Lg;
    double Eg;
    double Ig;
    double Amax;
    double Amin;
    double Arest;
    double Winit;

private:
    MemoryVector rest_activations; // constant

    std::vector<std::string> _units_names;

    MemoryVector external_activations;
    MemoryVector external_activations_decay;
    MemoryVector internal_activations;
    MemoryVector net_activations;
    MemoryVector _activations;
    MemoryMatrix _weights;

    LoggingFunction _log_activation;
    LoggingFunction _log_external_activation;

    std::random_device rd;
    std::default_random_engine gen;

    void compute_internal_activations();

    void run();
    void step();

    size_t _size = 0;

    /** Conservatively increment the size the network. Conserves the current
     * weights, activations.
     *
     * *Needs to be called from the network update thread!*
     */
    void incrementsize();

    std::thread _network_thread;

    bool _is_running = false;

    bool _is_recording = false;
    std::map<size_t, std::vector<std::tuple<float, std::chrono::microseconds, std::chrono::microseconds>>> _activations_history;

    void printout();

    std::chrono::microseconds _min_period = std::chrono::microseconds::zero();
    bool _use_physical_time = true;

    int _frequency = 0;
    int _steps_since_last_frequency_update = 0;

    std::chrono::high_resolution_clock::time_point _start_time;
    std::chrono::high_resolution_clock::time_point _last_timestamp;
    std::chrono::high_resolution_clock::time_point _last_freq_computation;

    // only used when _use_physical_time = false
    std::chrono::microseconds _elapsed_time;
};

#endif

max_stars_repo_name: severin-lemaignan/memory-view

max_issues_repo_name: severin-lemaignan/memory-view

max_forks_repo_name: severin-lemaignan/memory-view


text:
#include <gumbo.h>

#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <string>

#include "Manager.hpp"

using namespace boost::program_options;

int main(int argc, char** argv) {
  std::string url;
  uint32_t depth;
  uint32_t network_threads;
  uint32_t parser_threads;
  std::string output;

  options_description desc("General options");
  std::string task_type;
  desc.add_options()
      ("url", value(&url), "url to download")
      ("depth", value(&depth), "recursion depth")
      ("network_threads", value(&network_threads), "network_threads")
      ("parser_threads", value(&parser_threads), "parser_threads")
      ("output", value(&output), "output file");
  variables_map vm;
  try {
    parsed_options parsed = command_line_parser(argc, argv).options(desc).allow_unregistered().run();
    store(parsed, vm);
    std::cout << vm["url"].as<std::string>() << std::endl << vm["depth"].as<uint32_t>() << std::endl << vm["network_threads"].as<uint32_t>() << std::endl << vm["parser_threads"].as<uint32_t>() << std::endl << vm["output"].as<std::string>() << std::endl;
  }
  catch(std::exception& ex) {
    std::cout << desc << std::endl;
  }
  /*
  uint32_t x = 4;
  uint32_t z = 4;
  uint32_t y = 4;

  Manager man(x, y, z);
  */
}


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        :
// Author      : Avi
// Revision    : $Revision: #10 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include "Defs.hpp"
#include "Suite.hpp"
#include "Family.hpp"
#include "Task.hpp"
#include "Jobs.hpp"
#include "JobsParam.hpp"
#include "PrintStyle.hpp"

#include <boost/test/unit_test.hpp>
#include <iostream>

using namespace std;
using namespace ecf;

BOOST_AUTO_TEST_SUITE( NodeTestSuite )

BOOST_AUTO_TEST_CASE( test_ECFLOW_247 )
{
   cout << "ANode:: ...test_ECFLOW_247  \n";

   defs_ptr defs = Defs::create();
   suite_ptr s1 = defs->add_suite("s1");
   family_ptr f1 = s1->add_family("f1");
   f1->add_complete("f1/t1 == complete");
   task_ptr t1 = f1->add_task("t1");
   task_ptr t2 = f1->add_task("t2");
   task_ptr t3 = f1->add_task("t3");
   task_ptr t4 = f1->add_task("t4");

   PrintStyle style( PrintStyle::MIGRATE);
   {
      defs->beginAll();
      t1->set_state(NState::COMPLETE);
      //cout << defs;

      t4->set_state(NState::ABORTED);
      t4->flag().set(ecf::Flag::FORCE_ABORT); // stopped bu user mimic, otherwise it be be queued

      Jobs jobs(defs);
      JobsParam jobsParam;
      jobs.generate(jobsParam);
      //cout << defs;

      BOOST_CHECK_MESSAGE(f1->state() == NState::ABORTED,"The complete for family should not evaluate if child is aborted");
   }
   {
      defs->requeue();
      t1->set_state(NState::COMPLETE);
      //cout << defs;

      t4->set_state(NState::ACTIVE);

      Jobs jobs(defs);
      JobsParam jobsParam;
      jobs.generate(jobsParam);

      //cout << defs;
      BOOST_CHECK_MESSAGE(f1->state() == NState::ACTIVE,"The complete for family should not evaluate if child is active");
   }

   {
      defs->requeue();
      t1->set_state(NState::COMPLETE);

      Jobs jobs(defs);
      JobsParam jobsParam;
      jobs.generate(jobsParam);

      t4->set_state(NState::SUBMITTED);

      BOOST_CHECK_MESSAGE(f1->state() == NState::SUBMITTED,"The complete for family should not evaluate if child is submitted");
      //cout << defs;
   }

   {
      defs->requeue();
      t1->set_state(NState::COMPLETE);
      //cout << defs;

      Jobs jobs(defs);
      JobsParam jobsParam;
      jobs.generate(jobsParam);

      BOOST_CHECK_MESSAGE(f1->state() == NState::COMPLETE,"The complete for family should not evaluate if child is submitted");
      //cout << defs;
   }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ecmwf/ecflow

max_issues_repo_name: CoollRock/ecflow

max_forks_repo_name: CoollRock/ecflow


text:
/*!
 * @file
 * Contains unit tests for `boost::mpl11::detail::dependent`.
 */

#include <boost/mpl11/detail/dependent.hpp>

#include <boost/mpl11/detail/std_is_same.hpp>

using namespace boost::mpl11;
using detail::dependent;
using detail::std_is_same;

template <typename T>
struct never_instantiated {
    static_assert(dependent<T>::value(false), "");
    using would_fail = typename dependent<T>::template
                       type<int>::because_int_has_no_such_member_type;
};

struct x; struct y;
struct foo;
static_assert(std_is_same<dependent<>::type<foo>, foo>::value, "");
static_assert(std_is_same<dependent<x>::type<foo>, foo>::value, "");
static_assert(std_is_same<dependent<x, y>::type<foo>, foo>::value, "");

static_assert(dependent<>::value(2) == 2, "");
static_assert(dependent<x>::value(0) == 0, "");
static_assert(dependent<x, y>::value(1) == 1, "");

int main() { }


text:
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPBGLCollectGraph.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkDataSetAttributes.h"
#include "vtkDistributedGraphHelper.h"
#include "vtkDirectedGraph.h"
#include "vtkDoubleArray.h"
#include "vtkGraph.h"
#include "vtkIdTypeArray.h"
#include "vtkOutEdgeIterator.h"
#include "vtkMath.h"
#include "vtkPBGLCollectGraph.h"
#include "vtkPBGLRMATGraphSource.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkVertexListIterator.h"

#include <functional>
#include <string>

#include <boost/mpi/collectives.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/timer.hpp>
#include <boost/lexical_cast.hpp>

#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

bool HasPrintableAttributes(vtkDataSetAttributes *attrs)
{
  int numArrays = attrs->GetNumberOfArrays();
  for (int arrayIndex = 0; arrayIndex < numArrays; ++arrayIndex)
  {
    vtkAbstractArray *array = attrs->GetAbstractArray(arrayIndex);
    const char* name = attrs->GetArrayName(arrayIndex);
    if (name && *name)
    {
      return true;
    }
  }
  return false;
}

void PrintAttributes(vtkDataSetAttributes *attrs, vtkIdType index)
{
  bool printedAttr = false;
  int numArrays = attrs->GetNumberOfArrays();
  for (int arrayIndex = 0; arrayIndex < numArrays; ++arrayIndex)
  {
    vtkAbstractArray *array = attrs->GetAbstractArray(arrayIndex);
    const char *name = attrs->GetArrayName(arrayIndex);
    if (name && *name)
    {
      if (!printedAttr)
      {
        cerr << " [";
        printedAttr = true;
      }
      else
      {
        cerr << ", ";
      }

      cerr << name << " = \"" << array->GetVariantValue(index).ToString()
           << "\"";
    }
  }

  if (printedAttr)
  {
    cerr << "]";
  }
}

void PrintGraph(vtkGraph *graph)
{
  bool isDirected = vtkDirectedGraph::SafeDownCast(graph) != 0;
  if (isDirected)
  {
    cerr << "digraph G {" << endl;
  }
  else
  {
    cerr << "graph G {" << endl;
  }

  vtkDataSetAttributes *vertexData = graph->GetVertexData();
  vtkDataSetAttributes *edgeData = graph->GetEdgeData();
  bool hasVertexAttributes = HasPrintableAttributes(vertexData);
  bool hasEdgeAttributes = HasPrintableAttributes(edgeData);
  vtkSmartPointer<vtkVertexListIterator> vertices
    = vtkSmartPointer<vtkVertexListIterator>::New();
  graph->GetVertices(vertices);
  while (vertices->HasNext())
  {
    vtkIdType u = vertices->Next();

    if (hasVertexAttributes)
    {
      // Print vertex attributes
      cerr << "  " << u;
      PrintAttributes(vertexData, u);
      cerr << ";" << endl;
    }

    vtkSmartPointer<vtkOutEdgeIterator> outEdges
      = vtkSmartPointer<vtkOutEdgeIterator>::New();

    graph->GetOutEdges(u, outEdges);
    while (outEdges->HasNext())
    {
      // Print edge
      vtkOutEdgeType e = outEdges->Next();
      if (isDirected)
      {
        cerr << "  " << u << " -> " << e.Target;
      }
      else
      {
        cerr << "  " << u << " -- " << e.Target;
      }

      // Print edge attributes
      if (hasEdgeAttributes)
      {
        // Print edge attributes
        PrintAttributes(edgeData, e.Id);
      }
      cerr << ";" << endl;
    }
  }

  cerr << "}" << endl;
}

int TestPBGLCollectGraph(int argc, char* argv[])
{
  boost::mpi::environment env(argc, argv);
  boost::mpi::communicator world;

  vtkIdType wantVertices = 128;
  vtkIdType wantEdges = 512;
  double A = 0.45;
  double B = 0.15;
  double C = 0.15;
  double D = 0.25;

  int errors = 0;

  if (argc > 6)
  {
    wantVertices = boost::lexical_cast<vtkIdType>(argv[1]);
    wantEdges = boost::lexical_cast<vtkIdType>(argv[2]);
    A = boost::lexical_cast<double>(argv[3]);
    B = boost::lexical_cast<double>(argv[4]);
    C = boost::lexical_cast<double>(argv[5]);
    D = boost::lexical_cast<double>(argv[6]);
  }

  // Set up a random graph source
  VTK_CREATE(vtkPBGLRMATGraphSource, source);
  source->SetNumberOfVertices(wantVertices);
  wantVertices = source->GetNumberOfVertices();
  source->SetNumberOfEdges(wantEdges);
  source->SetProbabilities(A, B, C, D);

  // Set up the graph collector
  VTK_CREATE(vtkPBGLCollectGraph, collect);
  collect->SetInputConnection(0, source->GetOutputPort());

  // Build a distributed graph and collect the results.
  collect->Update();

  vtkGraph* output = vtkGraph::SafeDownCast(collect->GetOutput());
  if (world.rank() == 0)
  {
    if (output->GetNumberOfVertices() != source->GetNumberOfVertices())
    {
      cerr << "Output graph has the wrong number of vertices." << endl;
      ++errors;
    }

    if (output->GetNumberOfEdges() != source->GetNumberOfEdges())
    {
      cerr << "Output graph has the wrong number of edges." << endl;
      ++errors;
    }

    PrintGraph(output);
  }

  return 0;
}

ext: cxx


text:
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020 - 2021 Pionix GmbH and Contributors to EVerest
#ifndef EXCEPTIONS_HPP
#define EXCEPTIONS_HPP

#include <boost/exception/exception.hpp>
#include <everest/metamacros.hpp>
#include <sstream>
#include <stdexcept>
#include <string>

namespace Everest {
///
/// \brief base class for all everest logic exceptions
class EverestBaseError : public boost::exception {
public:
    ///
    /// \brief base constructor for all everest exceptions, inherited from boost::exception
    EverestBaseError() {
    }
};

///
/// \brief base class for all everest logic exceptions
class EverestBaseLogicError : public EverestBaseError, public std::logic_error {
public:
    ///
    /// \brief base constructor for all everest exceptions, inherited from std::logic_error
    explicit EverestBaseLogicError(const std::string& what) : std::logic_error(what) {
    }
};

///
/// \brief base class for all everest runtime exceptions
class EverestBaseRuntimeError : public EverestBaseError, public std::runtime_error {
public:
    ///
    /// \brief base constructor for all everest exceptions, inherited from std::runtime_error
    explicit EverestBaseRuntimeError(const std::string& what) : std::runtime_error(what) {
    }
};

///
/// \brief represents an internal error, like a missing configuration file
class EverestInternalError : public EverestBaseRuntimeError {
public:
    using EverestBaseRuntimeError::EverestBaseRuntimeError;
};

///
/// \brief represents a configuration error, like a malformed configuration entry
class EverestConfigError : public EverestBaseLogicError {
    using EverestBaseLogicError::EverestBaseLogicError;
};

///
/// \brief represents a API error, like tring to call a non-existing command
class EverestApiError : public EverestBaseLogicError {
public:
    using EverestBaseLogicError::EverestBaseLogicError;
};

///
/// \brief represents a timeout error, like tring to call a not answering command
class EverestTimeoutError : public EverestBaseRuntimeError {
public:
    using EverestBaseRuntimeError::EverestBaseRuntimeError;
};

} // namespace Everest

#define EVEXCEPTION(ex, ...)                                                                                \
    ex((static_cast<const std::ostringstream&>(metamacro_foreach(_EVEXCEPTION_INTERNALS, <<, __VA_ARGS__))).str())
#define _EVEXCEPTION_INTERNALS(index, arg) metamacro_if_eq(0, index)(std::ostringstream() << arg)(arg)

#endif // EXCEPTIONS_HPP

max_stars_repo_name: EVerest/liblog

max_issues_repo_name: EVerest/liblog

max_forks_repo_name: EVerest/liblog


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#include <boost/filesystem.hpp>

#include <osquery/tables.h>
#include <osquery/filesystem.h>

namespace osquery {
namespace tables {

QueryData genFile(QueryContext& context) {
  QueryData results;

  auto paths = context.constraints["path"].getAll(EQUALS);
  for (const auto& path_string : paths) {
    boost::filesystem::path path = path_string;

    Row r;
    r["path"] = path.string();
    r["filename"] = path.filename().string();
    r["is_file"] = INTEGER(boost::filesystem::is_regular_file(path));
    r["is_dir"] = INTEGER(boost::filesystem::is_directory(path));
    r["is_link"] = INTEGER(boost::filesystem::is_symlink(path));

    results.push_back(r);
  }

  return results;
}
}
}

max_stars_repo_name: Anubisss/osquery

max_issues_repo_name: Anubisss/osquery

max_forks_repo_name: Anubisss/osquery