text:
//
// Copyright (C) 2003-2021 Greg Landrum and other RDKit contributors
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include "QueryOps.h"
#include <algorithm>
#include <RDGeneral/types.h>
#include <GraphMol/QueryAtom.h>
#include <boost/range/iterator_range.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/algorithm/string.hpp>

namespace RDKit {

// common general queries

int queryIsAtomBridgehead(Atom const *at) {
  // at least three ring bonds, at least one ring bond in a ring which shares at
  // least two bonds with another ring involving this atom
  //
  // We can't just go with "at least three ring bonds shared between multiple
  // rings" because of structures like CC12CCN(CC1)C2 where there are only two
  // SSSRs
  PRECONDITION(at, "no atom");
  if (at->getDegree() < 3) {
    return 0;
  }
  const auto &mol = at->getOwningMol();
  const auto ri = mol.getRingInfo();
  if (!ri || !ri->isInitialized()) {
    return 0;
  }
  // track which bonds involve this atom
  boost::dynamic_bitset<> atomRingBonds(mol.getNumBonds());
  for (const auto &nbri : boost::make_iterator_range(mol.getAtomBonds(at))) {
    const auto &bnd = mol[nbri];
    if (ri->numBondRings(bnd->getIdx())) {
      atomRingBonds.set(bnd->getIdx());
    }
  }
  if (atomRingBonds.count() < 3) {
    return 0;
  }

  boost::dynamic_bitset<> bondsInRing(mol.getNumBonds());
  for (unsigned int i = 0; i < ri->bondRings().size(); ++i) {
    bondsInRing.reset();
    bool atomInRingI = false;

    for (const auto bidx : ri->bondRings()[i]) {
      bondsInRing.set(bidx);
      if (atomRingBonds[bidx]) {
        atomInRingI = true;
      }
    }
    if (!atomInRingI) {
      continue;
    }
    for (unsigned int j = i + 1; j < ri->bondRings().size(); ++j) {
      unsigned int overlap = 0;
      bool atomInRingJ = false;
      for (const auto bidx : ri->bondRings()[j]) {
        if (atomRingBonds[bidx]) {
          atomInRingJ = true;
        }
        if (bondsInRing[bidx]) {
          ++overlap;
        }
        if (overlap >= 2 && atomInRingJ) {
          // we have two rings containing the atom which share at least two
          // bonds:
          return 1;
        }
      }
    }
  }
  return 0;
}

//! returns a Query for matching atoms with a particular number of ring bonds
ATOM_EQUALS_QUERY *makeAtomRingBondCountQuery(int what) {
  ATOM_EQUALS_QUERY *res = new AtomRingQuery(what);
  res->setDescription("AtomRingBondCount");
  res->setDataFunc(queryAtomRingBondCount);
  return res;
};

ATOM_EQUALS_QUERY *makeAtomInRingOfSizeQuery(int tgt) {
  RANGE_CHECK(3, tgt, 20);
  auto *res = new ATOM_EQUALS_QUERY;
  res->setVal(tgt);
  switch (tgt) {
    case 3:
      res->setDataFunc(queryAtomIsInRingOfSize<3>);
      break;
    case 4:
      res->setDataFunc(queryAtomIsInRingOfSize<4>);
      break;
    case 5:
      res->setDataFunc(queryAtomIsInRingOfSize<5>);
      break;
    case 6:
      res->setDataFunc(queryAtomIsInRingOfSize<6>);
      break;
    case 7:
      res->setDataFunc(queryAtomIsInRingOfSize<7>);
      break;
    case 8:
      res->setDataFunc(queryAtomIsInRingOfSize<8>);
      break;
    case 9:
      res->setDataFunc(queryAtomIsInRingOfSize<9>);
      break;
    case 10:
      res->setDataFunc(queryAtomIsInRingOfSize<10>);
      break;
    case 11:
      res->setDataFunc(queryAtomIsInRingOfSize<11>);
      break;
    case 12:
      res->setDataFunc(queryAtomIsInRingOfSize<12>);
      break;
    case 13:
      res->setDataFunc(queryAtomIsInRingOfSize<13>);
      break;
    case 14:
      res->setDataFunc(queryAtomIsInRingOfSize<14>);
      break;
    case 15:
      res->setDataFunc(queryAtomIsInRingOfSize<15>);
      break;
    case 16:
      res->setDataFunc(queryAtomIsInRingOfSize<16>);
      break;
    case 17:
      res->setDataFunc(queryAtomIsInRingOfSize<17>);
      break;
    case 18:
      res->setDataFunc(queryAtomIsInRingOfSize<18>);
      break;
    case 19:
      res->setDataFunc(queryAtomIsInRingOfSize<19>);
      break;
    case 20:
      res->setDataFunc(queryAtomIsInRingOfSize<20>);
      break;
  }

  res->setDescription("AtomRingSize");
  return res;
}

BOND_EQUALS_QUERY *makeBondInRingOfSizeQuery(int tgt) {
  RANGE_CHECK(3, tgt, 20);
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(tgt);
  switch (tgt) {
    case 3:
      res->setDataFunc(queryBondIsInRingOfSize<3>);
      break;
    case 4:
      res->setDataFunc(queryBondIsInRingOfSize<4>);
      break;
    case 5:
      res->setDataFunc(queryBondIsInRingOfSize<5>);
      break;
    case 6:
      res->setDataFunc(queryBondIsInRingOfSize<6>);
      break;
    case 7:
      res->setDataFunc(queryBondIsInRingOfSize<7>);
      break;
    case 8:
      res->setDataFunc(queryBondIsInRingOfSize<8>);
      break;
    case 9:
      res->setDataFunc(queryBondIsInRingOfSize<9>);
      break;
    case 10:
      res->setDataFunc(queryBondIsInRingOfSize<10>);
      break;
    case 11:
      res->setDataFunc(queryBondIsInRingOfSize<11>);
      break;
    case 12:
      res->setDataFunc(queryBondIsInRingOfSize<12>);
      break;
    case 13:
      res->setDataFunc(queryBondIsInRingOfSize<13>);
      break;
    case 14:
      res->setDataFunc(queryBondIsInRingOfSize<14>);
      break;
    case 15:
      res->setDataFunc(queryBondIsInRingOfSize<15>);
      break;
    case 16:
      res->setDataFunc(queryBondIsInRingOfSize<16>);
      break;
    case 17:
      res->setDataFunc(queryBondIsInRingOfSize<17>);
      break;
    case 18:
      res->setDataFunc(queryBondIsInRingOfSize<18>);
      break;
    case 19:
      res->setDataFunc(queryBondIsInRingOfSize<19>);
      break;
    case 20:
      res->setDataFunc(queryBondIsInRingOfSize<20>);
      break;
  }
  res->setDescription("BondRingSize");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomMinRingSizeQuery(int tgt) {
  auto *res = new ATOM_EQUALS_QUERY;
  res->setVal(tgt);
  res->setDataFunc(queryAtomMinRingSize);
  res->setDescription("AtomMinRingSize");
  return res;
}
BOND_EQUALS_QUERY *makeBondMinRingSizeQuery(int tgt) {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(tgt);
  res->setDataFunc(queryBondMinRingSize);
  res->setDescription("BondMinRingSize");
  return res;
}

unsigned int queryAtomBondProduct(Atom const *at) {
  ROMol::OEDGE_ITER beg, end;
  boost::tie(beg, end) = at->getOwningMol().getAtomBonds(at);
  unsigned int prod = 1;
  while (beg != end) {
    prod *= static_cast<unsigned int>(
        firstThousandPrimes[at->getOwningMol()[*beg]->getBondType()]);
    ++beg;
  }
  return prod;
}
unsigned int queryAtomAllBondProduct(Atom const *at) {
  ROMol::OEDGE_ITER beg, end;

  boost::tie(beg, end) = at->getOwningMol().getAtomBonds(at);
  unsigned int prod = 1;
  while (beg != end) {
    prod *= static_cast<unsigned int>(
        firstThousandPrimes[at->getOwningMol()[*beg]->getBondType()]);
    ++beg;
  }
  for (unsigned int i = 0; i < at->getTotalNumHs(); i++) {
    prod *= static_cast<unsigned int>(firstThousandPrimes[Bond::SINGLE]);
  }
  return prod;
}

ATOM_EQUALS_QUERY *makeAtomImplicitValenceQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomImplicitValence);
  res->setDescription("AtomImplicitValence");
  return res;
}
ATOM_EQUALS_QUERY *makeAtomExplicitValenceQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomExplicitValence);
  res->setDescription("AtomExplicitValence");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomTotalValenceQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomTotalValence);
  res->setDescription("AtomTotalValence");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomNumQuery(int what) {
  return makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomNum,
                                                "AtomAtomicNum");
}

ATOM_EQUALS_QUERY *makeAtomTypeQuery(int num, int aromatic) {
  return makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(makeAtomType(num, aromatic),
                                                queryAtomType, "AtomType");
}
ATOM_EQUALS_QUERY *makeAtomExplicitDegreeQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomExplicitDegree);
  res->setDescription("AtomExplicitDegree");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomTotalDegreeQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomTotalDegree);
  res->setDescription("AtomTotalDegree");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHeavyAtomDegreeQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomHeavyAtomDegree);
  res->setDescription("AtomHeavyAtomDegree");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHCountQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomHCount);
  res->setDescription("AtomHCount");
  return res;
}
ATOM_EQUALS_QUERY *makeAtomImplicitHCountQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomImplicitHCount);
  res->setDescription("AtomImplicitHCount");
  return res;
}
ATOM_EQUALS_QUERY *makeAtomHasImplicitHQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomHasImplicitH);
  res->setDescription("AtomHasImplicitH");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomAromaticQuery() {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomAromatic);
  res->setDescription("AtomIsAromatic");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomAliphaticQuery() {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomAliphatic);
  res->setDescription("AtomIsAliphatic");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomUnsaturatedQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomUnsaturated);
  res->setDescription("AtomUnsaturated");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomMassQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(
      massIntegerConversionFactor * what, queryAtomMass);
  res->setDescription("AtomMass");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomIsotopeQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomIsotope);
  res->setDescription("AtomIsotope");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomFormalChargeQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomFormalCharge);
  res->setDescription("AtomFormalCharge");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomNegativeFormalChargeQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(
      what, queryAtomNegativeFormalCharge);
  res->setDescription("AtomNegativeFormalCharge");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHybridizationQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomHybridization);
  res->setDescription("AtomHybridization");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomNumRadicalElectronsQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(
      what, queryAtomNumRadicalElectrons);
  res->setDescription("AtomNumRadicalElectrons");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHasChiralTagQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomHasChiralTag);
  res->setDescription("AtomHasChiralTag");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomMissingChiralTagQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomMissingChiralTag);
  res->setDescription("AtomMissingChiralTag");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomInRingQuery() {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryIsAtomInRing);
  res->setDescription("AtomInRing");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomIsBridgeheadQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryIsAtomBridgehead);
  res->setDescription("AtomIsBridgehead");
  return res;
}

ATOM_OR_QUERY *makeQAtomQuery() {
  auto *res = new ATOM_OR_QUERY;
  res->setDescription("AtomOr");
  res->setTypeLabel("Q");
  res->setNegation(true);
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(6)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(1)));
  return res;
}
ATOM_EQUALS_QUERY *makeQHAtomQuery() {
  ATOM_EQUALS_QUERY *res = makeAtomNumQuery(6);
  res->setNegation(true);
  res->setTypeLabel("QH");
  return res;
}
ATOM_EQUALS_QUERY *makeAAtomQuery() {
  ATOM_EQUALS_QUERY *res = makeAtomNumQuery(1);
  res->setNegation(true);
  res->setTypeLabel("A");
  return res;
}
ATOM_NULL_QUERY *makeAHAtomQuery() {
  auto *res = makeAtomNullQuery();
  res->setTypeLabel("AH");
  return res;
}

ATOM_OR_QUERY *makeXAtomQuery() {
  auto *res = new ATOM_OR_QUERY;
  res->setDescription("AtomOr");
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(9)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(17)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(35)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(53)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(85)));
  res->setTypeLabel("X");

  return res;
}
ATOM_OR_QUERY *makeXHAtomQuery() {
  ATOM_OR_QUERY *res = makeXAtomQuery();
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(1)));
  res->setTypeLabel("XH");
  return res;
}

ATOM_OR_QUERY *makeMAtomQuery() {
  // using the definition from Marvin Sketch, which produces the following
  // SMARTS:
  // !#1!#2!#5!#6!#7!#8!#9!#10!#14!#15!#16!#17!#18!#33!#34!#35!#36!#52!#53!#54!#85!#86
  // it's easier to define what isn't a metal than what is. :-)
  ATOM_OR_QUERY *res = makeMHAtomQuery();
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(1)));
  res->setTypeLabel("M");

  return res;
}
ATOM_OR_QUERY *makeMHAtomQuery() {
  // using the definition from Marvin Sketch, which produces the following
  // SMARTS:
  // !#2!#5!#6!#7!#8!#9!#10!#14!#15!#16!#17!#18!#33!#34!#35!#36!#52!#53!#54!#85!#86
  // it's easier to define what isn't a metal than what is. :-)
  auto *res = new ATOM_OR_QUERY;
  res->setDescription("AtomOr");
  res->setNegation(true);
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(2)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(5)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(6)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(7)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(8)));
  res->addChild(
      Queries::Query<int, Atom const *, true>::CHILD_TYPE(makeAtomNumQuery(9)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(10)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(14)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(15)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(16)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(17)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(18)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(33)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(34)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(35)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(36)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(52)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(53)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(54)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(85)));
  res->addChild(Queries::Query<int, Atom const *, true>::CHILD_TYPE(
      makeAtomNumQuery(86)));
  res->setTypeLabel("MH");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomInNRingsQuery(int what) {
  ATOM_EQUALS_QUERY *res;
  res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryIsAtomInNRings);
  res->setDescription("AtomInNRings");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHasRingBondQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomHasRingBond);
  res->setDescription("AtomHasRingBond");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomNumHeteroatomNbrsQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomNumHeteroatomNbrs);
  res->setDescription("AtomNumHeteroatomNeighbors");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHasHeteroatomNbrsQuery() {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(true, queryAtomHasHeteroatomNbrs);
  res->setDescription("AtomHasHeteroatomNeighbors");
  return res;
}
ATOM_EQUALS_QUERY *makeAtomNumAliphaticHeteroatomNbrsQuery(int what) {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(
      what, queryAtomNumAliphaticHeteroatomNbrs);
  res->setDescription("AtomNumAliphaticHeteroatomNeighbors");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomHasAliphaticHeteroatomNbrsQuery() {
  auto *res = makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(
      true, queryAtomHasAliphaticHeteroatomNbrs);
  res->setDescription("AtomHasAliphaticHeteroatomNeighbors");
  return res;
}

ATOM_EQUALS_QUERY *makeAtomNonHydrogenDegreeQuery(int what) {
  auto *res =
      makeAtomSimpleQuery<ATOM_EQUALS_QUERY>(what, queryAtomNonHydrogenDegree);
  res->setDescription("AtomNonHydrogenDegree");
  return res;
}

BOND_EQUALS_QUERY *makeBondOrderEqualsQuery(Bond::BondType what) {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(what);
  res->setDataFunc(queryBondOrder);
  res->setDescription("BondOrder");
  return res;
}

RDKIT_GRAPHMOL_EXPORT BOND_EQUALS_QUERY *makeSingleOrAromaticBondQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryBondIsSingleOrAromatic);
  res->setDescription("SingleOrAromaticBond");
  return res;
};

RDKIT_GRAPHMOL_EXPORT BOND_EQUALS_QUERY *makeDoubleOrAromaticBondQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryBondIsDoubleOrAromatic);
  res->setDescription("DoubleOrAromaticBond");
  return res;
};

RDKIT_GRAPHMOL_EXPORT BOND_EQUALS_QUERY *makeSingleOrDoubleBondQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryBondIsSingleOrDouble);
  res->setDescription("SingleOrDoubleBond");
  return res;
};

RDKIT_GRAPHMOL_EXPORT BOND_EQUALS_QUERY *
makeSingleOrDoubleOrAromaticBondQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryBondIsSingleOrDoubleOrAromatic);
  res->setDescription("SingleOrDoubleOrAromaticBond");
  return res;
};

namespace QueryOps {
const std::vector<std::string> bondOrderQueryFunctions{
    std::string("BondOrder"), std::string("SingleOrAromaticBond"),
    std::string("DoubleOrAromaticBond"), std::string("SingleOrDoubleBond"),
    std::string("SingleOrDoubleOrAromaticBond")};
RDKIT_GRAPHMOL_EXPORT bool hasBondTypeQuery(
    const Queries::Query<int, Bond const *, true> &qry) {
  const auto df = qry.getDescription();
  // is this a bond order query?
  if (std::find(bondOrderQueryFunctions.begin(), bondOrderQueryFunctions.end(),
                df) != bondOrderQueryFunctions.end()) {
    return true;
  }
  for (const auto &child :
       boost::make_iterator_range(qry.beginChildren(), qry.endChildren())) {
    if (hasBondTypeQuery(*child)) {
      return true;
    }
  }
  return false;
}

namespace {
bool hasComplexBondTypeQueryHelper(
    const Queries::Query<int, Bond const *, true> &qry, bool seenBondOrder) {
  const auto df = qry.getDescription();
  bool isBondOrder = (df == "BondOrder");
  // is this a bond order query?
  if (std::find(bondOrderQueryFunctions.begin(), bondOrderQueryFunctions.end(),
                df) != bondOrderQueryFunctions.end()) {
    if (seenBondOrder || !isBondOrder || qry.getNegation()) {
      return true;
    }
  }
  for (const auto &child :
       boost::make_iterator_range(qry.beginChildren(), qry.endChildren())) {
    if (hasComplexBondTypeQueryHelper(*child, seenBondOrder | isBondOrder)) {
      return true;
    }
    if (child->getDescription() == "BondOrder") {
      seenBondOrder = true;
    }
  }
  return false;
}
}  // namespace

RDKIT_GRAPHMOL_EXPORT bool hasComplexBondTypeQuery(
    const Queries::Query<int, Bond const *, true> &qry) {
  return hasComplexBondTypeQueryHelper(qry, false);
}
}  // namespace QueryOps

BOND_EQUALS_QUERY *makeBondDirEqualsQuery(Bond::BondDir what) {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(what);
  res->setDataFunc(queryBondDir);
  res->setDescription("BondDir");
  return res;
}

BOND_EQUALS_QUERY *makeBondHasStereoQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryBondHasStereo);
  res->setDescription("BondStereo");
  return res;
}

BOND_EQUALS_QUERY *makeBondIsInRingQuery() {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(true);
  res->setDataFunc(queryIsBondInRing);
  res->setDescription("BondInRing");
  return res;
}

BOND_EQUALS_QUERY *makeBondInNRingsQuery(int what) {
  auto *res = new BOND_EQUALS_QUERY;
  res->setVal(what);
  res->setDataFunc(queryIsBondInNRings);
  res->setDescription("BondInNRings");
  return res;
}

BOND_NULL_QUERY *makeBondNullQuery() {
  auto *res = new BOND_NULL_QUERY;
  res->setDataFunc(nullDataFun);
  res->setMatchFunc(nullQueryFun);
  res->setDescription("BondNull");
  return res;
}

ATOM_NULL_QUERY *makeAtomNullQuery() {
  auto *res = new ATOM_NULL_QUERY;
  res->setDataFunc(nullDataFun);
  res->setMatchFunc(nullQueryFun);
  res->setDescription("AtomNull");
  return res;
}

bool isComplexQuery(const Bond *b) {
  PRECONDITION(b, "bad bond");
  if (!b->hasQuery()) {
    return false;
  }
  // negated things are always complex:
  if (b->getQuery()->getNegation()) {
    return true;
  }
  std::string descr = b->getQuery()->getDescription();
  if (descr == "BondOrder" || descr == "SingleOrAromaticBond") {
    return false;
  }
  if (descr == "BondAnd" || descr == "BondXor") {
    return true;
  }
  if (descr == "BondOr") {
    // detect the types of queries that appear for unspecified bonds in
    // SMARTS:
    if (b->getQuery()->endChildren() - b->getQuery()->beginChildren() == 2) {
      for (auto child = b->getQuery()->beginChildren();
           child != b->getQuery()->endChildren(); ++child) {
        if ((*child)->getDescription() != "BondOrder" ||
            (*child)->getNegation()) {
          return true;
        }
        if (static_cast<BOND_EQUALS_QUERY *>(child->get())->getVal() !=
                Bond::SINGLE &&
            static_cast<BOND_EQUALS_QUERY *>(child->get())->getVal() !=
                Bond::AROMATIC) {
          return true;
        }
      }
      return false;
    }
  }

  return true;
}

namespace {
bool _complexQueryHelper(Atom::QUERYATOM_QUERY const *query, bool &hasAtNum) {
  if (!query) {
    return false;
  }
  if (query->getNegation()) {
    return true;
  }
  std::string descr = query->getDescription();
  // std::cerr<<" |"<<descr;
  if (descr == "AtomAtomicNum" || descr == "AtomType") {
    hasAtNum = true;
    return false;
  }
  if (descr == "AtomOr" || descr == "AtomXor") {
    return true;
  }
  if (descr == "AtomAnd") {
    auto childIt = query->beginChildren();
    while (childIt != query->endChildren()) {
      if (_complexQueryHelper(childIt->get(), hasAtNum)) {
        return true;
      }
      ++childIt;
    }
  }
  return false;
}

template <typename T>
bool _atomListQueryHelper(const T query) {
  PRECONDITION(query, "no query");
  if (query->getNegation()) {
    return false;
  }
  if (query->getDescription() == "AtomAtomicNum" ||
      query->getDescription() == "AtomType") {
    return true;
  }
  if (query->getDescription() == "AtomOr") {
    for (const auto &child : boost::make_iterator_range(query->beginChildren(),
                                                        query->endChildren())) {
      if (!_atomListQueryHelper(child)) {
        return false;
      }
    }
  }
  return true;
}
}  // namespace
bool isAtomListQuery(const Atom *a) {
  PRECONDITION(a, "bad atom");
  if (!a->hasQuery()) {
    return false;
  }
  if (a->getQuery()->getDescription() == "AtomOr") {
    for (const auto &child : boost::make_iterator_range(
             a->getQuery()->beginChildren(), a->getQuery()->endChildren())) {
      if (!_atomListQueryHelper(child)) {
        return false;
      }
    }
    return true;
  }
  return false;
}

void getAtomListQueryVals(const Atom::QUERYATOM_QUERY *q,
                          std::vector<int> &vals) {
  // list queries are series of nested ors of AtomAtomicNum queries
  PRECONDITION(q, "bad query");
  auto descr = q->getDescription();
  PRECONDITION(descr == "AtomOr", "bad query");
  if (descr == "AtomOr") {
    for (const auto &child :
         boost::make_iterator_range(q->beginChildren(), q->endChildren())) {
      auto descr = child->getDescription();
      if (child->getNegation() ||
          (descr != "AtomOr" && descr != "AtomAtomicNum" &&
           descr != "AtomType")) {
        throw ValueErrorException("bad query type1");
      }
      // we don't allow negation of any children of the query:
      if (descr == "AtomOr") {
        getAtomListQueryVals(child.get(), vals);
      } else if (descr == "AtomAtomicNum") {
        vals.push_back(static_cast<ATOM_EQUALS_QUERY *>(child.get())->getVal());
      } else if (descr == "AtomType") {
        auto v = static_cast<ATOM_EQUALS_QUERY *>(child.get())->getVal();
        // aromatic AtomType queries add 1000 to the atomic number;
        // correct for that:
        if (v >= 1000) {
          v -= 1000;
        }
        vals.push_back(v);
      }
    }
  }
}

bool isComplexQuery(const Atom *a) {
  PRECONDITION(a, "bad atom");
  if (!a->hasQuery()) {
    return false;
  }
  // std::cerr<<"\n"<<a->getIdx();
  // negated things are always complex:
  if (a->getQuery()->getNegation()) {
    return true;
  }
  std::string descr = a->getQuery()->getDescription();
  // std::cerr<<" "<<descr;
  if (descr == "AtomNull" || descr == "AtomAtomicNum" || descr == "AtomType") {
    return false;
  }
  if (descr == "AtomOr" || descr == "AtomXor") {
    return true;
  }
  if (descr == "AtomAnd") {
    bool hasAtNum = false;
    if (_complexQueryHelper(a->getQuery(), hasAtNum)) {
      return true;
    }
    if (hasAtNum) {
      return false;
    } else {
      return true;
    }
  }

  return true;
}
bool isAtomAromatic(const Atom *a) {
  PRECONDITION(a, "bad atom");
  bool res = false;
  if (!a->hasQuery()) {
    res = a->getIsAromatic();
  } else {
    std::string descr = a->getQuery()->getDescription();
    if (descr == "AtomAtomicNum") {
      res = a->getIsAromatic();
    } else if (descr == "AtomIsAromatic") {
      res = true;
      if (a->getQuery()->getNegation()) {
        res = !res;
      }
    } else if (descr == "AtomIsAliphatic") {
      res = false;
      if (a->getQuery()->getNegation()) {
        res = !res;
      }
    } else if (descr == "AtomType") {
      res = getAtomTypeIsAromatic(
          static_cast<ATOM_EQUALS_QUERY *>(a->getQuery())->getVal());
      if (a->getQuery()->getNegation()) {
        res = !res;
      }
    } else if (descr == "AtomAnd") {
      auto childIt = a->getQuery()->beginChildren();
      if ((*childIt)->getDescription() == "AtomAtomicNum") {
        if (a->getQuery()->getNegation()) {
          res = false;
        } else if ((*(childIt + 1))->getDescription() == "AtomIsAliphatic") {
          res = false;
        } else if ((*(childIt + 1))->getDescription() == "AtomIsAromatic") {
          res = true;
        }
      }
    }
  }
  return res;
}

namespace QueryOps {
namespace {
void completeQueryAndChildren(ATOM_EQUALS_QUERY *query, Atom *tgt,
                              unsigned int magicVal) {
  PRECONDITION(query, "no query");
  PRECONDITION(tgt, "no atom");
  if (static_cast<unsigned int>(query->getVal()) == magicVal) {
    int tgtVal = query->getDataFunc()(tgt);
    query->setVal(tgtVal);
  }
  for (auto childIt = query->beginChildren(); childIt != query->endChildren();
       ++childIt) {
    completeQueryAndChildren((ATOM_EQUALS_QUERY *)(childIt->get()), tgt,
                             magicVal);
  }
}
}  // namespace
void completeMolQueries(RWMol *mol, unsigned int magicVal) {
  PRECONDITION(mol, "bad molecule");
  for (auto atom : mol->atoms()) {
    if (atom->hasQuery()) {
      auto *query = static_cast<ATOM_EQUALS_QUERY *>(atom->getQuery());
      completeQueryAndChildren(query, atom, magicVal);
    }
  }
}

Atom *replaceAtomWithQueryAtom(RWMol *mol, Atom *atom) {
  PRECONDITION(mol, "bad molecule");
  PRECONDITION(atom, "bad atom");
  if (atom->hasQuery()) {
    return atom;
  }

  QueryAtom qa(*atom);
  unsigned int idx = atom->getIdx();

  if (atom->hasProp(common_properties::_hasMassQuery)) {
    qa.expandQuery(makeAtomMassQuery(static_cast<int>(atom->getMass())));
  }
  mol->replaceAtom(idx, &qa);
  return mol->getAtomWithIdx(idx);
}

void finalizeQueryFromDescription(
    Queries::Query<int, Atom const *, true> *query, Atom const *) {
  std::string descr = query->getDescription();

  if (boost::starts_with(descr, "range_")) {
    descr = descr.substr(6);
  } else if (boost::starts_with(descr, "less_")) {
    descr = descr.substr(5);
  } else if (boost::starts_with(descr, "greater_")) {
    descr = descr.substr(8);
  }

  Queries::Query<int, Atom const *, true> *tmpQuery;
  if (descr == "AtomRingBondCount") {
    query->setDataFunc(queryAtomRingBondCount);
  } else if (descr == "AtomHasRingBond") {
    query->setDataFunc(queryAtomHasRingBond);
  } else if (descr == "AtomRingSize") {
    tmpQuery = makeAtomInRingOfSizeQuery(
        static_cast<ATOM_EQUALS_QUERY *>(query)->getVal());
    query->setDataFunc(tmpQuery->getDataFunc());
    delete tmpQuery;
  } else if (descr == "AtomMinRingSize") {
    query->setDataFunc(queryAtomMinRingSize);
  } else if (descr == "AtomImplicitValence") {
    query->setDataFunc(queryAtomImplicitValence);
  } else if (descr == "AtomTotalValence") {
    query->setDataFunc(queryAtomTotalValence);
  } else if (descr == "AtomAtomicNum") {
    query->setDataFunc(queryAtomNum);
  } else if (descr == "AtomExplicitDegree") {
    query->setDataFunc(queryAtomExplicitDegree);
  } else if (descr == "AtomTotalDegree") {
    query->setDataFunc(queryAtomTotalDegree);
  } else if (descr == "AtomHeavyAtomDegree") {
    query->setDataFunc(queryAtomHeavyAtomDegree);
  } else if (descr == "AtomHCount") {
    query->setDataFunc(queryAtomHCount);
  } else if (descr == "AtomImplicitHCount") {
    query->setDataFunc(queryAtomImplicitHCount);
  } else if (descr == "AtomHasImplicitH") {
    query->setDataFunc(queryAtomHasImplicitH);
  } else if (descr == "AtomIsAromatic") {
    query->setDataFunc(queryAtomAromatic);
  } else if (descr == "AtomIsAliphatic") {
    query->setDataFunc(queryAtomAliphatic);
  } else if (descr == "AtomUnsaturated") {
    query->setDataFunc(queryAtomUnsaturated);
  } else if (descr == "AtomMass") {
    query->setDataFunc(queryAtomMass);
  } else if (descr == "AtomIsotope") {
    query->setDataFunc(queryAtomIsotope);
  } else if (descr == "AtomFormalCharge") {
    query->setDataFunc(queryAtomFormalCharge);
  } else if (descr == "AtomNegativeFormalCharge") {
    query->setDataFunc(queryAtomNegativeFormalCharge);
  } else if (descr == "AtomHybridization") {
    query->setDataFunc(queryAtomHybridization);
  } else if (descr == "AtomInRing") {
    query->setDataFunc(queryIsAtomInRing);
  } else if (descr == "AtomInNRings") {
    query->setDataFunc(queryIsAtomInNRings);
  } else if (descr == "AtomHasHeteroatomNeighbors") {
    query->setDataFunc(queryAtomHasHeteroatomNbrs);
  } else if (descr == "AtomNumHeteroatomNeighbors") {
    query->setDataFunc(queryAtomNumHeteroatomNbrs);
  } else if (descr == "AtomNonHydrogenDegree") {
    query->setDataFunc(queryAtomNonHydrogenDegree);
  } else if (descr == "AtomHasAliphaticHeteroatomNeighbors") {
    query->setDataFunc(queryAtomHasAliphaticHeteroatomNbrs);
  } else if (descr == "AtomNumAliphaticHeteroatomNeighbors") {
    query->setDataFunc(queryAtomNumAliphaticHeteroatomNbrs);
  } else if (descr == "AtomNull") {
    query->setDataFunc(nullDataFun);
    query->setMatchFunc(nullQueryFun);
  } else if (descr == "AtomType") {
    query->setDataFunc(queryAtomType);
  } else if (descr == "AtomInNRings" || descr == "RecursiveStructure") {
    // don't need to do anything here because the classes
    // automatically have everything set
  } else if (descr == "AtomAnd" || descr == "AtomOr" || descr == "AtomXor") {
    // don't need to do anything here because the classes
    // automatically have everything set
  } else {
    throw ValueErrorException("Do not know how to finalize query: '" + descr +
                              "'");
  }
}

void finalizeQueryFromDescription(
    Queries::Query<int, Bond const *, true> *query, Bond const *) {
  std::string descr = query->getDescription();
  Queries::Query<int, Bond const *, true> *tmpQuery;
  if (descr == "BondRingSize") {
    tmpQuery = makeBondInRingOfSizeQuery(
        static_cast<BOND_EQUALS_QUERY *>(query)->getVal());
    query->setDataFunc(tmpQuery->getDataFunc());
    delete tmpQuery;
  } else if (descr == "BondMinRingSize") {
    query->setDataFunc(queryBondMinRingSize);
  } else if (descr == "BondOrder") {
    query->setDataFunc(queryBondOrder);
  } else if (descr == "BondDir") {
    query->setDataFunc(queryBondDir);
  } else if (descr == "BondInRing") {
    query->setDataFunc(queryIsBondInRing);
  } else if (descr == "BondInNRings") {
    query->setDataFunc(queryIsBondInNRings);
  } else if (descr == "SingleOrAromaticBond") {
    query->setDataFunc(queryBondIsSingleOrAromatic);
  } else if (descr == "SingleOrDoubleBond") {
    query->setDataFunc(queryBondIsSingleOrDouble);
  } else if (descr == "DoubleOrAromaticBond") {
    query->setDataFunc(queryBondIsDoubleOrAromatic);
  } else if (descr == "SingleOrDoubleOrAromaticBond") {
    query->setDataFunc(queryBondIsSingleOrDoubleOrAromatic);
  } else if (descr == "BondNull") {
    query->setDataFunc(nullDataFun);
    query->setMatchFunc(nullQueryFun);
  } else if (descr == "BondAnd" || descr == "BondOr" || descr == "BondXor") {
    // don't need to do anything here because the classes
    // automatically have everything set
  } else {
    throw ValueErrorException("Do not know how to finalize query: '" + descr +
                              "'");
  }
}

}  // namespace QueryOps
};  // namespace RDKit

max_stars_repo_name: kazuyaujihara/rdkit

max_issues_repo_name: kazuyaujihara/rdkit

max_forks_repo_name: kazuyaujihara/rdkit


text:
#include "io_utils.h"

#include <Eigen/Dense>
#include <fstream>

Eigen::MatrixXd bayesmix::read_eigen_matrix(const std::string &filename,
                                            const char delim /* = ','*/) {
  // Initialize objects
  unsigned int cols = 0, rows = 0;
  double buffer[MAXBUFSIZE];
  std::ifstream filestream(filename);
  if (!filestream.is_open()) {
    std::string err = "File " + filename + " does not exist";
    throw std::invalid_argument(err);
  }

  // Loop over file lines
  std::string line, entry;
  while (getline(filestream, line, '\n')) {
    unsigned int temp = 0;
    std::stringstream linestream(line);
    while (getline(linestream, entry, delim)) {
      // Place read values into the buffer array
      std::stringstream entrystream(entry);
      entrystream >> buffer[cols * rows + temp++];
    }
    if (temp == 0) {
      continue;
    }
    if (cols == 0) {
      cols = temp;
    }
    rows++;
  }

  filestream.close();

  // Fill an Eigen Matrix with values from the buffer array
  Eigen::MatrixXd mat(rows, cols);
  for (size_t i = 0; i < rows; i++) {
    for (size_t j = 0; j < cols; j++) {
      mat(i, j) = buffer[cols * i + j];
    }
  }
  return mat;
};

void bayesmix::write_matrix_to_file(const Eigen::MatrixXd &mat,
                                    const std::string &filename,
                                    const char delim /*= ','*/) {
  using namespace Eigen;
  std::string del;
  del = delim;
  const IOFormat CSVFormat(StreamPrecision, DontAlignCols, del, "\n");
  std::ofstream file(filename.c_str());
  file << mat.format(CSVFormat);
}

ext: cc

max_stars_repo_name: edoardopalli/bayesmix

max_issues_repo_name: edoardopalli/bayesmix

max_forks_repo_name: edoardopalli/bayesmix


text:
#ifndef ASLAM_BACKEND_GAUSS_NEWTON_TRUST_REGION_POLICY_HPP
#define ASLAM_BACKEND_GAUSS_NEWTON_TRUST_REGION_POLICY_HPP

#include <aslam/backend/TrustRegionPolicy.hpp>
#include <aslam/backend/LinearSystemSolver.hpp>
#include <boost/shared_ptr.hpp>

namespace aslam {
    namespace backend {

        class GaussNewtonTrustRegionPolicy : public TrustRegionPolicy
        {
        public:
            GaussNewtonTrustRegionPolicy();
            virtual ~GaussNewtonTrustRegionPolicy();

            /// \brief called by the optimizer when an optimization is starting
            virtual void optimizationStartingImplementation(double J);

            // Returns true if the solution was successful
          virtual bool solveSystemImplementation(double J, bool previousIterationFailed, int nThreads, Eigen::VectorXd& outDx);

            /// \brief should the optimizer revert on failure? You should probably return true
            bool revertOnFailure();

            /// \brief print the current state to a stream (no newlines).
            virtual std::ostream & printState(std::ostream & out) const;
          virtual std::string name() const { return "gauss_newton"; }
          virtual bool requiresAugmentedDiagonal() const;

        };

    } // namespace backend
} // namespace aslam

#endif /* ASLAM_BACKEND_GAUSS_NEWTON_TRUST_REGION_POLICY_HPP */

ext: hpp

max_stars_repo_name: PushyamiKaveti/kalibr

max_issues_repo_name: PushyamiKaveti/kalibr

max_forks_repo_name: PushyamiKaveti/kalibr


text:
#define BOOST_TEST_MODULE WayOut1Section2Tests

#include <boost/test/unit_test.hpp>
#include "test_common.h"

BOOST_AUTO_TEST_CASE(Section2Level01)
{
    const char * indata = 1 + R"(
_..._
_X_._
.VXHX
_X_._
_..._
)";
    const char * outdata = 1 + R"(
_..._
_._._
.X.X.
_._._
_..._
)";
    test(indata, {outdata});
}

BOOST_AUTO_TEST_CASE(Section2Level05)
{
    const char * indata = 1 + R"(
XX.X..
XX._X.
.X_._X
X_._..
X._X.X
.X.X..
)";
    const char * outdata = 1 + R"(
X...XX
..._..
.X_._X
X_._..
.._..X
..XXX.
)";
    test(indata, {outdata});
}

BOOST_AUTO_TEST_CASE(Section2Level20)
{
    const char * indata = 1 + R"(
XHX..X___
hV_.v._X_
X__X_.___
...vXh.X.
Hh_._.__X
...V.h..V
___X_X._.
hv_._h__X
Xh_HX.VXV
)";
    const char * outdata = 1 + R"(
X.X.X.___
.X_.X._X_
X__._.___
.XXX.XX..
X._._.__.
...X..XXX
___._X._X
XX_._X__.
X._X...X.
)";
    test(indata, {outdata});
}

ext: cpp


text:
#include <pch.hpp>
#include <xrn/Ecs/Entity.hpp>
#include <xrn/Ecs/Component.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop
BOOST_AUTO_TEST_SUITE(Engine)
BOOST_AUTO_TEST_SUITE(Core)
BOOST_AUTO_TEST_SUITE(Ecs)
BOOST_AUTO_TEST_SUITE(Entity)
BOOST_AUTO_TEST_SUITE(Referenre)

// ------------------------------------------------------------------ Component
BOOST_AUTO_TEST_SUITE(Component)

BOOST_AUTO_TEST_CASE(addNhas)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ components, entity };
    ref.addComponent<::xrn::ecs::component::test::ComponentA>();

    BOOST_TEST(entity.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(!entity.hasComponent<::xrn::ecs::component::test::ComponentB>());
    BOOST_TEST(!ref.hasComponent<::xrn::ecs::component::test::ComponentB>());
}

BOOST_AUTO_TEST_CASE(addNhas2)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ entity, components };
    ref.addComponents(::xrn::ecs::component::test::ComponentB{});

    BOOST_TEST(!entity.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(!ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(entity.hasComponent<::xrn::ecs::component::test::ComponentB>());
    BOOST_TEST(ref.hasComponent<::xrn::ecs::component::test::ComponentB>());
}

BOOST_AUTO_TEST_CASE(removeNhas)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ components, entity };

    ref.addComponent<::xrn::ecs::component::test::ComponentA>();
    BOOST_TEST(entity.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(components.contains<::xrn::ecs::component::test::ComponentA>(entity.getId()));
    BOOST_TEST(components.contains<::xrn::ecs::component::test::ComponentA>(ref.getId()));

    ref.removeComponent<::xrn::ecs::component::test::ComponentA>();
    BOOST_TEST(!entity.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(!ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(!components.contains<::xrn::ecs::component::test::ComponentA>(entity.getId()));
    BOOST_TEST(!components.contains<::xrn::ecs::component::test::ComponentA>(ref.getId()));

    ref.addComponents<::xrn::ecs::component::test::ComponentA, ::xrn::ecs::component::test::ComponentB>();
    BOOST_TEST(ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(ref.hasComponent<::xrn::ecs::component::test::ComponentB>());
    ref.removeComponents();
    BOOST_TEST(!ref.hasComponent<::xrn::ecs::component::test::ComponentA>());
    BOOST_TEST(!ref.hasComponent<::xrn::ecs::component::test::ComponentB>());

    ref.addAbilities<::xrn::ecs::component::test::AbilityA, ::xrn::ecs::component::test::AbilityB>();
    BOOST_TEST(ref.hasAbility<::xrn::ecs::component::test::AbilityA>());
    BOOST_TEST(ref.hasAbility<::xrn::ecs::component::test::AbilityB>());
    ref.removeAbilities();
    BOOST_TEST(!ref.hasAbility<::xrn::ecs::component::test::AbilityA>());
    BOOST_TEST(!ref.hasAbility<::xrn::ecs::component::test::AbilityB>());

    ref.add<
        ::xrn::ecs::component::test::ComponentA,
        ::xrn::ecs::component::test::ComponentB,
        ::xrn::ecs::component::test::AbilityA,
        ::xrn::ecs::component::test::AbilityB
    >();
    BOOST_TEST((ref.has<
        ::xrn::ecs::component::test::ComponentA,
        ::xrn::ecs::component::test::ComponentB,
        ::xrn::ecs::component::test::AbilityA,
        ::xrn::ecs::component::test::AbilityB
    >()));
    ref.removeAbilitiesAndComponents();
    BOOST_TEST((!ref.has<
        ::xrn::ecs::component::test::ComponentA,
        ::xrn::ecs::component::test::ComponentB,
        ::xrn::ecs::component::test::AbilityA,
        ::xrn::ecs::component::test::AbilityB
    >()));
}

BOOST_AUTO_TEST_SUITE_END()
// ------------------------------------------------------------------ Signature
BOOST_AUTO_TEST_SUITE(Signature)

BOOST_AUTO_TEST_CASE(single)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ components, entity };

    ref.addComponent<::xrn::ecs::component::test::ComponentA>();
    auto signature{ ::xrn::ecs::Signature::generate<::xrn::ecs::component::test::ComponentA>() };

    BOOST_TEST((entity.getSignature() == signature));
    BOOST_TEST((ref.getSignature() == signature));
    BOOST_TEST((ref.getSignature() == entity.getSignature()));
    BOOST_TEST((&ref.getSignature() == &entity.getSignature()));
}

BOOST_AUTO_TEST_SUITE_END()
// ------------------------------------------------------------------ Signature
BOOST_AUTO_TEST_SUITE(Id)

BOOST_AUTO_TEST_CASE(incrementation)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{components, entity};

    BOOST_TEST(entity.getId() == ref.getId());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_CASE(others)
{
    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ components, entity };
    const ::xrn::ecs::entity::Reference constNonConstRef{ components, entity };
    const ::xrn::ecs::entity::Reference constMutableRef{ components, entity };
    ::xrn::ecs::entity::ConstReference constRef{ ref };
    const ::xrn::ecs::entity::Entity& entityRef = ref; // operator=() avoids copy for some reasons lmao

    BOOST_TEST(&entity == &static_cast<const ::xrn::ecs::entity::Entity&>(ref));
    BOOST_TEST(entity.getId() == constMutableRef.getId());
    BOOST_TEST(&constRef.get() == &ref.get());
    BOOST_TEST(&constRef.get() == &entity);
    BOOST_TEST(&constRef.get() == &entityRef);
    BOOST_TEST(&constNonConstRef.get() == &entityRef);
}

BOOST_AUTO_TEST_CASE(example)
{
    using namespace ::xrn::ecs::component::test;

    ::xrn::ecs::component::Container components;
    ::xrn::ecs::entity::Entity entity;
    ::xrn::ecs::entity::Reference ref{ components, entity };

    BOOST_TEST(!entity.hasComponent<ComponentA>());
    BOOST_TEST(!ref.hasComponent<ComponentA>());
    BOOST_TEST(!entity.hasComponent<ComponentB>());
    BOOST_TEST(!ref.hasComponent<ComponentB>());
    ref.addComponents<ComponentA, ComponentB>();
    BOOST_TEST((entity.hasComponents<ComponentA, ComponentB>()));
    BOOST_TEST((ref.hasComponents<ComponentA, ComponentB>()));
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DiantArts/xrnEcs

max_issues_repo_name: DiantArts/xrnEcs

max_forks_repo_name: DiantArts/xrnEcs


text:
#ifndef SHIFT_PARSER_JSON_HASH_HPP
#define SHIFT_PARSER_JSON_HASH_HPP

#include <shift/core/boost_disable_warnings.hpp>
#include <boost/functional/hash/hash.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/parser/json/json.hpp"

namespace std
{
template <>
struct hash<shift::parser::json::object>
{
  inline std::size_t operator()(
    const shift::parser::json::object& object) const;
};

template <>
struct hash<shift::parser::json::array>
{
  inline std::size_t operator()(const shift::parser::json::array& array) const;
};

template <>
struct hash<shift::parser::json::value>
{
  inline std::size_t operator()(const shift::parser::json::value& value) const;
};

inline std::size_t hash<shift::parser::json::object>::operator()(
  const shift::parser::json::object& object) const
{
  auto result = std::hash<std::size_t>{}(object.size());
  for (const auto& value : object)
  {
    boost::hash_combine(result, std::hash<std::string>{}(value.first));
    boost::hash_combine(result,
                        std::hash<shift::parser::json::value>{}(value.second));
  }
  return result;
}

inline std::size_t hash<shift::parser::json::array>::operator()(
  const shift::parser::json::array& array) const
{
  auto result = std::hash<std::size_t>{}(array.size());
  for (const auto& value : array)
    boost::hash_combine(result, std::hash<shift::parser::json::value>{}(value));
  return result;
}

inline std::size_t hash<shift::parser::json::value>::operator()(
  const shift::parser::json::value& value) const
{
  if (shift::parser::json::get_if<std::nullptr_t>(&value) != nullptr)
    return 0;
  else if (auto* bool_value = shift::parser::json::get_if<bool>(&value);
           bool_value != nullptr)
  {
    return std::hash<bool>{}(*bool_value);
  }
  else if (auto* double_value = shift::parser::json::get_if<double>(&value);
           double_value != nullptr)
  {
    return std::hash<double>{}(*double_value);
  }
  else if (auto* int_value = shift::parser::json::get_if<std::int64_t>(&value);
           int_value != nullptr)
  {
    return std::hash<std::int64_t>{}(*int_value);
  }
  else if (auto* string_value =
             shift::parser::json::get_if<std::string>(&value);
           string_value != nullptr)
  {
    return std::hash<std::string>{}(*string_value);
  }
  else if (auto* object_value =
             shift::parser::json::get_if<shift::parser::json::object>(&value);
           object_value != nullptr)
  {
    return std::hash<shift::parser::json::object>{}(*object_value);
  }
  else if (auto* array_value =
             shift::parser::json::get_if<shift::parser::json::array>(&value);
           array_value != nullptr)
  {
    return std::hash<shift::parser::json::array>{}(*array_value);
  }
  else
  {
    BOOST_ASSERT(false);
    return 0;
  }
}
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
/*
 * MIT License
 *
 * Copyright (c) 2015 Alexis LE GOADEC
 *
 * 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.
 *
 */

/**
 * Définition de l'algorithme décidant la connexité d'un hypergraphe.
 */
#ifndef ALGORITHM_INCLUDE_CONNECTED_HH_
#define ALGORITHM_INCLUDE_CONNECTED_HH_

#include "../model/HypergrapheAbstrait.hh"
#include "../model/AlgorithmeAbstrait.hh"

#include <boost/shared_ptr.hpp>
#include <stack>
#include <vector>

/**
 * Algorithme décidant la connexité d'un hypergraphe.
 */
class Connected : public AlgorithmeAbstrait {

public:

	/**
	 * Constructeur.
	 * @param boost::shared_ptr<HypergrapheAbstrait> Pointeur partagé vers l'hypergraphe.
	 */
	Connected(boost::shared_ptr<HypergrapheAbstrait>&);

	/**
	 * Obtenir la structure de résultats.
	 */
	RStructure getResult() const;

	/**
	 * Destructeur.
	 */
	~Connected();

protected:

	/**
	 * Fonction de lancement de l'algorithme.
	 */
	void runAlgorithme();

	/**
	 * Exploration verticale d'un chemin de la matrice.
	 * @param Vecteur des visités.
	 * @param Pile des "à visiter".
	 * @param Identifiant de la ligne.
	 */
	void exploreVertical(std::vector<unsigned int>&, std::stack<unsigned int>&, unsigned int);

	/**
	 * Exploration horizontale d'un chemin dans la matrice.
	 * @param Vecteur des visités.
	 * @param Pile des "à visiter".
	 * @param Identifiant de la colonne.
	 */
	void exploreHorizontal(std::vector<unsigned int>&, std::stack<unsigned int>&, unsigned int);

	/**
	 * Vérifier si un hyper-vertex a déjà été visité.
	 * @param Vecteur des hyper-vertex visités.
	 * @param Identifiant à vérifier.
	 * @return True si déjà visité, False sinon.
	 */
	bool isVertexVisited(std::vector<unsigned int>&, unsigned int) const;

	/**
	 * Vérifier si une hyper-arête a déjà été visitée.
	 * @param Vecteur des hyper-arêtes visités.
	 * @param Identifiant à vérifier.
	 * @return True si déjà visité, False sinon.
	 */
	bool isEdgeVisited(std::vector<unsigned int>&, unsigned int) const;

/*

	bool isPath(HyperVertex&, HyperVertex&) const;

	bool isVisited(std::vector<HyperEdge>&, const HyperEdge&) const;

*/

protected:

	/**
	 * Pointeur partagé vers l'hypergraphe.
	 */
	boost::shared_ptr<HypergrapheAbstrait>
	_ptrHypergrapheAbstrait;

	/**
	 * Structure de résultat.
	 */
	RStructure _result;

};

#endif /* ALGORITHM_INCLUDE_CONNECTED_HH_ */

ext: hh

max_stars_repo_name: ehzawad/HyperGraphLib

max_issues_repo_name: ehzawad/HyperGraphLib

max_forks_repo_name: ehzawad/HyperGraphLib


text:
// Copyright (C) 2009 Anthony Williams
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_THREAD_USES_MOVE

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

void do_nothing(boost::thread::id* my_id)
{
    *my_id=boost::this_thread::get_id();
}

boost::thread make_thread_move_return(boost::thread::id* the_id)
{
    boost::thread t(do_nothing,the_id);
    return boost::move(t);
}

void test_move_from_function_move_return()
{
    boost::thread::id the_id;
    boost::thread x=make_thread_move_return(&the_id);
    boost::thread::id x_id=x.get_id();
    x.join();
    BOOST_CHECK_EQUAL(the_id,x_id);
}

boost::unit_test::test_suite* init_unit_test_suite(int, char*[])
{
    boost::unit_test::test_suite* test =
        BOOST_TEST_SUITE("Boost.Threads: thread move test suite");

    test->add(BOOST_TEST_CASE(test_move_from_function_move_return));
    return test;
}

void remove_unused_warning()
{

  //../../../boost/test/results_collector.hpp:40:13: warning: unused function 'first_failed_assertion' [-Wunused-function]
  //(void)boost::unit_test::first_failed_assertion;

  //../../../boost/test/tools/floating_point_comparison.hpp:304:25: warning: unused variable 'check_is_close' [-Wunused-variable]
  //../../../boost/test/tools/floating_point_comparison.hpp:326:25: warning: unused variable 'check_is_small' [-Wunused-variable]
  (void)boost::test_tools::check_is_close;
  (void)boost::test_tools::check_is_small;

}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/// Berenger Bramas (berenger.bramas@inria.fr)
///
/// This file implements parallel sort with the STL
/// and is used to compare with our SVE arm sort.
///
/// Need:
/// module load boost/1.73.0/arm-21.0
///
/// Compile with:
/// g++ -march=armv8.2-a+sve -DNDEBUG -O3 boostparallel.cpp -o boostparallel.cpp.exe -fopenmp

#include <vector>
#include <algorithm>

#include <iostream>
#include <algorithm>
#include <chrono>
#include <cassert>
#include <stdexcept>
#include <climits>
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <string.h>
#include <array>
#include <vector>
#include <fstream>

#include <iostream>
#include <memory>
#include <cstdlib>

#include <boost/sort/sort.hpp>

class dtimer {
    using double_second_time = std::chrono::duration<double, std::ratio<1, 1>>;

    std::chrono::high_resolution_clock::time_point
    m_start;  ///< m_start time (start)
    std::chrono::high_resolution_clock::time_point m_end;  ///< stop time (stop)
    std::chrono::nanoseconds m_cumulate;  ///< the m_cumulate time

public:
    /// Constructor
    dtimer() { start(); }

    /// Copy constructor
    dtimer(const dtimer& other) = delete;
    /// Copies an other timer
    dtimer& operator=(const dtimer& other) = delete;
    /// Move constructor
    dtimer(dtimer&& other) = delete;
    /// Copies an other timer
    dtimer& operator=(dtimer&& other) = delete;

    /** Rest all the values, and apply start */
    void reset() {
        m_start = std::chrono::high_resolution_clock::time_point();
        m_end = std::chrono::high_resolution_clock::time_point();
        m_cumulate = std::chrono::nanoseconds();
        start();
    }

    /** Start the timer */
    void start() {
        m_start = std::chrono::high_resolution_clock::now();
    }

    /** Stop the current timer */
    void stop() {
        m_end = std::chrono::high_resolution_clock::now();
        m_cumulate += std::chrono::duration_cast<std::chrono::nanoseconds>(m_end - m_start);
    }

    /** Return the elapsed time between start and stop (in second) */
    double getElapsed() const {
        return std::chrono::duration_cast<double_second_time>(
                    std::chrono::duration_cast<std::chrono::nanoseconds>(m_end - m_start)).count();
    }

    /** Return the total counted time */
    double getCumulated() const {
        return std::chrono::duration_cast<double_second_time>(m_cumulate).count();
    }

    /** End the current counter (stop) and return the elapsed time */
    double stopAndGetElapsed() {
        stop();
        return getElapsed();
    }
};

template <class NumType>
void createRandVecInc(NumType array[], const int size, const NumType starValue = 0){
    if(size){
        array[0] = starValue + rand()/(RAND_MAX/5);
        for(int idx = 1 ; idx < size ; ++idx){
            array[idx] = (rand()/(RAND_MAX/5)) + array[idx-1];
        }
    }
}

template <class NumType>
void createRandVec(NumType array[], const size_t size){
    for(size_t idx = 0 ; idx < size ; ++idx){
        array[idx] = NumType(drand48()*double(size));
    }
}

// To ensure vec is used and to kill extra optimization
template <class NumType>
void useVec(NumType array[], const size_t size){
    double all = 0;
    for(size_t idx = 0 ; idx < size ; ++idx){
        all += double(array[idx]) * 0.000000000001;
    }
    // This will never happen!
    if(all == std::numeric_limits<double>::max()){
        std::cout << "The impossible happens!!" << std::endl;
        exit(99);
    }
}

template <class NumType>
void useVec(std::pair<NumType,NumType> array[], const size_t size){
    double all = 0;
    for(size_t idx = 0 ; idx < size ; ++idx){
        all += double(array[idx].first) * 0.000000000001;
    }
    // This will never happen!
    if(all == std::numeric_limits<double>::max()){
        std::cout << "The impossible happens!!" << std::endl;
        exit(99);
    }
}

std::vector<int> GetNbThreadsToTest(){
    std::vector<int> nbThreads;
    const int maxThreads = 48;
    for(int idx = 1 ; idx <= maxThreads ; idx *= 2){
        nbThreads.push_back(idx);
    }
    if(((maxThreads-1)&maxThreads) != 0){
        nbThreads.push_back(maxThreads);
    }
    return nbThreads;
}

const size_t GlobalMaxSize = 3L*1024L*1024L*1024L;

template <class NumType>
void timeAllOmp(std::ostream& fres){
    const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;262144*8;//
    const int NbLoops = 5;

    const auto nbThreadsToTest = GetNbThreadsToTest();

    int nbSize=0;
    for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8){
        nbSize += 1;
    }

    const bool full = false;
    const int nbAlgo = 1;

    std::vector<double> allTimes(3*nbAlgo*nbThreadsToTest.size()*nbSize);

    auto access = [&](int idxSize, int idxThread, int idxType, int res) -> int{
        assert(idxSize < nbSize);
        assert(idxType < nbAlgo);
        assert(res < 3);
        assert(idxThread < nbThreadsToTest.size());
        assert((((idxSize*nbThreadsToTest.size())+idxThread)*nbAlgo+idxType)*3+res < allTimes.size());
        return (((idxSize*nbThreadsToTest.size())+idxThread)*nbAlgo+idxType)*3+res;
    };

    for(int idxThread = 0; idxThread < nbThreadsToTest.size() ; ++idxThread){

        const int nbThreads = nbThreadsToTest[idxThread];
        std::cout << "nb threads " << nbThreads << std::endl;

        int idxSize = 0;
        for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8 , idxSize += 1){
            std::unique_ptr<NumType[]> array(new NumType[currentSize]);

            std::cout << "currentSize " << currentSize << std::endl;

            for(int idxType = 0 ; idxType < nbAlgo ; ++idxType){
                allTimes[access(idxSize, idxThread, idxType, 0)] = std::numeric_limits<double>::max();
                allTimes[access(idxSize, idxThread, idxType, 1)] = std::numeric_limits<double>::min();
                allTimes[access(idxSize, idxThread, idxType, 2)] = 0;
            }

            for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
                std::cout << "  idxLoop " << idxLoop << std::endl;

                int idxType = 0;
                {
                    srand48((long int)(idxLoop));
                    createRandVec(array.get(), currentSize);
                    dtimer timer;
                    boost::sort::block_indirect_sort(&array[0], &array[currentSize],nbThreads);
                    timer.stop();
                    std::cout << "    stdsort " << timer.getElapsed() << std::endl;
                    useVec(array.get(), currentSize);
                    allTimes[access(idxSize, idxThread, idxType, 0)] = std::min(allTimes[access(idxSize, idxThread, idxType, 0)], timer.getElapsed());
                    allTimes[access(idxSize, idxThread, idxType, 1)] = std::max(allTimes[access(idxSize, idxThread, idxType, 1)], timer.getElapsed());
                    allTimes[access(idxSize, idxThread, idxType, 2)] += timer.getElapsed()/double(NbLoops);
                    idxType += 1;
                }
            }
        }
    }

    const char* labels[1] = {"block_indirect_sort"};

    fres << "#size";

    for(const int nbThreads : nbThreadsToTest){
        for(int idxlabel = 0 ; idxlabel < nbAlgo ; ++idxlabel){
            fres << "\t" << labels[idxlabel] << nbThreads << "min";
            fres << "\t" << labels[idxlabel] << nbThreads << "max";
            fres << "\t" << labels[idxlabel] << nbThreads << "avg";
            fres << "\t" << labels[idxlabel] << nbThreads << "avgnlogn";
            fres << "\t" << labels[idxlabel] << nbThreads << "eff";
        }
    }
    fres << "\n";

    int idxSize = 0;
    for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8 , idxSize += 1){
        fres << currentSize;
        for(int idxThread = 0; idxThread < nbThreadsToTest.size() ; ++idxThread){
            for(int idxlabel = 0 ; idxlabel < nbAlgo ; ++idxlabel){
                for(int idxres = 0 ; idxres < 3 ; ++idxres){
                    fres << "\t" << allTimes[access(idxSize, idxThread, idxlabel, idxres)];
                }
                fres << "\t" << (allTimes[access(idxSize, idxThread, idxlabel, 2)]
                                /(currentSize*std::log(currentSize)));
                fres << "\t" << (allTimes[access(idxSize, 0, idxlabel, 2)])
                                /(allTimes[access(idxSize, idxThread, idxlabel, 2)]);
            }
        }
        fres << "\n";
    }
}

int main(){
    {
        std::ofstream fres("std-res-int-openmp.data");
        timeAllOmp<int>(fres);
    }
    {
        std::ofstream fres("std-res-double-openmp.data");
        timeAllOmp<double>(fres);
    }

    return 0;
}

max_stars_repo_name: berenger-eu/arm-sve-sort

max_issues_repo_name: berenger-eu/arm-sve-sort

max_forks_repo_name: berenger-eu/arm-sve-sort


text:
#include <boost/test/unit_test.hpp>

#include "Hasher.h"

BOOST_AUTO_TEST_SUITE(HasherTest)

BOOST_AUTO_TEST_CASE(UpdateDoesNotCommuteWithConcat)
{
	Hasher h;
	Hasher g;
	h.update(1);
	h.update(2);
	g.update(12);

	BOOST_CHECK(h.digest() != g.digest());
}

BOOST_AUTO_TEST_CASE(CopyProducesIdentical)
{
	Hasher h;
	h.update(1);
	Hasher g = h;

	BOOST_CHECK(h.digest() == g.digest());

	h.update(2);
	g.update(2);

	BOOST_CHECK(h.digest() == g.digest());
}

BOOST_AUTO_TEST_CASE(DigestIsIdempotent)
{
	Hasher h;
	h.update(1);

	BOOST_CHECK(h.digest() == h.digest());
}

BOOST_AUTO_TEST_CASE(CopyProducesDisjoint)
{
	Hasher h;
	h.update(1);
	Hasher g = h;

	auto digest1 = h.digest();
	g.update(2);
	auto digest2 = h.digest();

	BOOST_CHECK(digest1 == digest2);
}

BOOST_AUTO_TEST_CASE(CopyProducesDisjointReverse)
{
	Hasher h;
	h.update(1);
	Hasher g = h;

	auto digest1 = g.digest();
	h.update(2);
	auto digest2 = g.digest();

	BOOST_CHECK(digest1 == digest2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: hdc-arizona/MediatedCubes

max_issues_repo_name: hdc-arizona/MediatedCubes

max_forks_repo_name: hdc-arizona/MediatedCubes


text:
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdio.h>

#include <chrono>
#include <thread>

#include <boost/asio.hpp>

/***********************************************************************************************************************
 * Definition
 **********************************************************************************************************************/

// You can also send the packets to some other machine. Right now, functionality only exists for sending them to local host.
#define FLIGHTGEAR_UDP_PORT 5500 // this is also defined in the FlightGear startup script. If you change it here, you'll have to change it there too

#define HOST "127.0.0.1"

#define TIME_BETWEEN_PACKETS_MS 40  // FlightGear is set to refresh every 33 ms (configurable in the launch script for FlightGear), anything slower than that should be fine to use. Anything faster, and it will drop packets.

#define DEBUG false

/***********************************************************************************************************************
 * Prototypes
 **********************************************************************************************************************/

static int getNumDatapoints(void);
static void fillPackets(char** packets, int numPackets);
static void sendPacketsToFlightGear(char** packets, int numPackets);

/***********************************************************************************************************************
 * Code
 **********************************************************************************************************************/

int main(void)
{

    int numDataPoints = getNumDatapoints();

    char **packets = new char*[numDataPoints];

    if (packets == NULL)
    {
        std::cerr << "System Out of memory, failed to create packet array" << std::endl;
        return -1;
    }

    for(int i = 0; i < numDataPoints; i++)
    {
        packets[i] = new char[100];

        if (packets[i] == NULL)
        {
            std::cerr << "System Out of memory, failed to create packet array" << std::endl;
            return -1;
        }
    }

    fillPackets(packets, numDataPoints);

    sendPacketsToFlightGear(packets, numDataPoints);

    return 0;
}

static int getNumDatapoints(void)
{
    std::ifstream dataFile;
    std::string line, previousLine;
    std::string returnChar ("\n");
    int i = -1;

    dataFile.open("SimulationBuild/SensorOutputs/roll.txt");

    do
    {
        getline(dataFile, line);
        i++;
    }
    while (!line.empty());

    dataFile.close();

    return i;
}

static void fillPackets(char** packets, int numPackets)
{
    std::ifstream rollFile;
    std::string rollLine;
    std::ifstream pitchFile;
    std::string pitchLine;
    std::ifstream yawFile;
    std::string yawLine;

    std::ifstream latFile;
    std::string latLine;
    std::ifstream longFile;
    std::string longLine;
    std::ifstream altitudeFile;
    std::string altitudeLine;

    rollFile.open("SimulationBuild/SensorOutputs/roll.txt");
    pitchFile.open("SimulationBuild/SensorOutputs/pitch.txt");
    yawFile.open("SimulationBuild/SensorOutputs/yaw.txt");
    latFile.open("SimulationBuild/SensorOutputs/latitude.txt");
    longFile.open("SimulationBuild/SensorOutputs/longitude.txt");
    altitudeFile.open("SimulationBuild/SensorOutputs/altitude.txt");

    for(int i = 0; i < numPackets; i++)
    {
        getline(rollFile, rollLine);
        getline(pitchFile, pitchLine);
        getline(yawFile, yawLine);
        getline(latFile, latLine);
        getline(longFile, longLine);
        getline(altitudeFile, altitudeLine);

        // This packet format was defined inside the flight gear protocol file: Simulink-Sim/FlightGear/WargFGPacketStructure.xml If you haven't yet, copy that file into FlightGear's protocols folder
        sprintf(packets[i], "%.2f,%.6f,%.6f,%.2f,%.2f,%.2f,\n", std::stof(altitudeLine), std::stof(latLine), std::stof(longLine), std::stof(rollLine), std::stof(pitchLine), std::stof(yawLine));

		if(DEBUG) std::cout << "read: " << packets[i] << std::endl;
    }

    rollFile.close();
    pitchFile.close();
    yawFile.close();
    latFile.close();
    longFile.close();
    altitudeFile.close();
}

static void sendPacketsToFlightGear(char** packets, int numPackets)
{
	boost::asio::io_service io_service;
	boost::asio::ip::udp::socket socket(io_service);

	boost::asio::ip::address add = boost::asio::ip::address::from_string(HOST);

	boost::asio::ip::udp::endpoint remote(add, FLIGHTGEAR_UDP_PORT);

	socket.open(boost::asio::ip::udp::v4());

    for(int i = 0; i < numPackets; i++)
    {
		socket.send_to(boost::asio::buffer(packets[i], std::strlen(packets[i])), remote);
		if(DEBUG) std::cout << "sent: " << packets[i] << "to: " << HOST << ":" << FLIGHTGEAR_UDP_PORT << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(TIME_BETWEEN_PACKETS_MS));
    }
}

max_stars_repo_name: AadityaChaudhary/Simulink-Sim

max_issues_repo_name: AadityaChaudhary/Simulink-Sim

max_forks_repo_name: AadityaChaudhary/Simulink-Sim