text:
namespace RDKit {
namespace MMFF {
using namespace ForceFields::MMFF;

namespace Tools {
// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addBonds(const ROMol &mol, MMFFMolProperties *mmffMolProperties,
              ForceFields::ForceField *field) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  double totalBondStretchEnergy = 0.0;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "B O N D   S T R E T C H I N G\n\n"
                 "------ATOMS------   ATOM TYPES   FF     BOND     IDEAL       "
                 "                 FORCE\n"
                 "  I        J          I    J   CLASS   LENGTH   LENGTH    "
                 "DIFF.    ENERGY   CONSTANT\n"
                 "-------------------------------------------------------------"
                 "------------------------" << std::endl;
    }
  }
  for (ROMol::ConstBondIterator bi = mol.beginBonds(); bi != mol.endBonds();
       ++bi) {
    unsigned int idx1 = (*bi)->getBeginAtomIdx();
    unsigned int idx2 = (*bi)->getEndAtomIdx();
    unsigned int bondType;
    MMFFBond mmffBondParams;
    if (mmffMolProperties->getMMFFBondStretchParams(mol, idx1, idx2, bondType,
                                                    mmffBondParams)) {
      BondStretchContrib *contrib = new BondStretchContrib(field, idx1, idx2, &mmffBondParams);
      field->contribs().push_back(ForceFields::ContribPtr(contrib));
      if (mmffMolProperties->getMMFFVerbosity()) {
        unsigned int iAtomType = mmffMolProperties->getMMFFAtomType(idx1);
        unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(idx2);
        const Atom *iAtom = (*bi)->getBeginAtom();
        const Atom *jAtom = (*bi)->getEndAtom();
        const double dist = field->distance(idx1, idx2);
        const double bondStretchEnergy = MMFF::Utils::calcBondStretchEnergy(
            mmffBondParams.r0, mmffBondParams.kb, dist);
        if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
          oStream << std::left << std::setw(2) << iAtom->getSymbol() << " #"
                  << std::setw(5) << idx1 + 1 << std::setw(2)
                  << jAtom->getSymbol() << " #" << std::setw(5) << idx2 + 1
                  << std::right << std::setw(5) << iAtomType << std::setw(5)
                  << jAtomType << std::setw(6) << bondType << "  " << std::fixed
                  << std::setprecision(3) << std::setw(9) << dist
                  << std::setw(9) << mmffBondParams.r0 << std::setw(9)
                  << dist - mmffBondParams.r0 << std::setw(10)
                  << bondStretchEnergy << std::setw(10) << mmffBondParams.kb
                  << std::endl;
        }
        totalBondStretchEnergy += bondStretchEnergy;
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL BOND STRETCH ENERGY      =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalBondStretchEnergy
            << std::endl;
  }
}

unsigned int twoBitCellPos(unsigned int nAtoms, int i, int j) {
  if (j < i) std::swap(i, j);

  return i * (nAtoms - 1) + i * (1 - i) / 2 + j;
}

void setTwoBitCell(boost::shared_array<boost::uint8_t> &res, unsigned int pos,
                   boost::uint8_t value) {
  unsigned int twoBitPos = pos / 4;
  unsigned int shift = 2 * (pos % 4);
  boost::uint8_t twoBitMask = 3 << shift;
  res[twoBitPos] = ((res[twoBitPos] & (~twoBitMask)) | (value << shift));
}

boost::uint8_t getTwoBitCell(boost::shared_array<boost::uint8_t> &res,
                             unsigned int pos) {
  unsigned int twoBitPos = pos / 4;
  unsigned int shift = 2 * (pos % 4);
  boost::uint8_t twoBitMask = 3 << shift;

  return ((res[twoBitPos] & twoBitMask) >> shift);
}

// ------------------------------------------------------------------------
//
// the two-bit matrix returned by this contains:
//   0: if atoms i and j are directly connected
//   1: if atoms i and j are connected via an atom
//   2: if atoms i and j are in a 1,4 relationship
//   3: otherwise
//
//  NOTE: the caller is responsible for calling delete []
//  on the result
//
// ------------------------------------------------------------------------
boost::shared_array<boost::uint8_t> buildNeighborMatrix(const ROMol &mol) {
  const boost::uint8_t RELATION_1_X_INIT = RELATION_1_X
    | (RELATION_1_X << 2) | (RELATION_1_X << 4) | (RELATION_1_X << 6);
  unsigned int nAtoms = mol.getNumAtoms();
  unsigned nTwoBitCells = (nAtoms * (nAtoms + 1) - 1) / 8 + 1;
  boost::shared_array<boost::uint8_t> res(new boost::uint8_t[nTwoBitCells]);
  std::memset(res.get(), RELATION_1_X_INIT, nTwoBitCells);
  for (ROMol::ConstBondIterator bondi = mol.beginBonds(); bondi != mol.endBonds(); ++bondi) {
    setTwoBitCell(res, twoBitCellPos(nAtoms, (*bondi)->getBeginAtomIdx(),
                  (*bondi)->getEndAtomIdx()), RELATION_1_2);
    unsigned int bondiBeginAtomIdx = (*bondi)->getBeginAtomIdx();
    unsigned int bondiEndAtomIdx = (*bondi)->getEndAtomIdx();
    for (ROMol::ConstBondIterator bondj = bondi; ++bondj != mol.endBonds();) {
      int idx1 = -1;
      int idx3 = -1;
      unsigned int bondjBeginAtomIdx = (*bondj)->getBeginAtomIdx();
      unsigned int bondjEndAtomIdx = (*bondj)->getEndAtomIdx();
      if (bondiBeginAtomIdx == bondjBeginAtomIdx) {
        idx1 = bondiEndAtomIdx;
        idx3 = bondjEndAtomIdx;
      } else if (bondiBeginAtomIdx == bondjEndAtomIdx) {
        idx1 = bondiEndAtomIdx;
        idx3 = bondjBeginAtomIdx;
      } else if (bondiEndAtomIdx == bondjBeginAtomIdx) {
        idx1 = bondiBeginAtomIdx;
        idx3 = bondjEndAtomIdx;
      } else if (bondiEndAtomIdx == bondjEndAtomIdx) {
        idx1 = bondiBeginAtomIdx;
        idx3 = bondjBeginAtomIdx;
      } else {
        // check if atoms i and j are in a 1,4-relationship
        if ((mol.getBondBetweenAtoms(bondiBeginAtomIdx,
                                     bondjBeginAtomIdx)) &&
            (getTwoBitCell(res, twoBitCellPos(nAtoms, bondiEndAtomIdx,
                                    bondjEndAtomIdx)) == RELATION_1_X)) {
          setTwoBitCell(
              res, twoBitCellPos(nAtoms, bondiEndAtomIdx, bondjEndAtomIdx),
              RELATION_1_4);
        } else if ((mol.getBondBetweenAtoms(bondiBeginAtomIdx,
                                            bondjEndAtomIdx)) &&
                   (getTwoBitCell(res, twoBitCellPos(nAtoms, bondiEndAtomIdx,
                                           bondjBeginAtomIdx)) ==
                    RELATION_1_X)) {
          setTwoBitCell(
              res, twoBitCellPos(nAtoms, bondiEndAtomIdx, bondjBeginAtomIdx),
              RELATION_1_4);
        } else if ((mol.getBondBetweenAtoms(bondiEndAtomIdx,
                                            bondjBeginAtomIdx)) &&
                   (getTwoBitCell(res, twoBitCellPos(nAtoms, bondiBeginAtomIdx,
                                           bondjEndAtomIdx)) ==
                    RELATION_1_X)) {
          setTwoBitCell(
              res, twoBitCellPos(nAtoms, bondiBeginAtomIdx, bondjEndAtomIdx),
              RELATION_1_4);
        } else if ((mol.getBondBetweenAtoms(bondiEndAtomIdx,
                                            bondjEndAtomIdx)) &&
                   (getTwoBitCell(res, twoBitCellPos(nAtoms, bondiBeginAtomIdx,
                                           bondjBeginAtomIdx)) ==
                    RELATION_1_X)) {
          setTwoBitCell(
              res, twoBitCellPos(nAtoms, bondiBeginAtomIdx, bondjBeginAtomIdx),
              RELATION_1_4);
        }
      }
      if (idx1 > -1) {
        setTwoBitCell(res, twoBitCellPos(nAtoms, idx1, idx3), RELATION_1_3);
      }
    }
  }
  return res;
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addAngles(const ROMol &mol, MMFFMolProperties *mmffMolProperties,
               ForceFields::ForceField *field) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  unsigned int idx[3];
  MMFFPropCollection *mmffProp = MMFFPropCollection::getMMFFProp();
  ROMol::ADJ_ITER nbr1Idx;
  ROMol::ADJ_ITER end1Nbrs;
  ROMol::ADJ_ITER nbr2Idx;
  ROMol::ADJ_ITER end2Nbrs;

  unsigned int nAtoms = mol.getNumAtoms();
  double totalAngleBendEnergy = 0.0;
  RDGeom::PointPtrVect points;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "A N G L E   B E N D I N G\n\n"
                 "-----------ATOMS-----------    ATOM TYPES      FF    VALENCE "
                 "   IDEAL                          FORCE\n"
                 "  I        J        K          I    J    K   CLASS    ANGLE  "
                 "   ANGLE      DIFF.    ENERGY   CONSTANT\n"
                 "-------------------------------------------------------------"
                 "-----------------------------------------" << std::endl;
    }
    points = field->positions();
  }
  for (idx[1] = 0; idx[1] < nAtoms; ++idx[1]) {
    const Atom *jAtom = mol.getAtomWithIdx(idx[1]);
    if (jAtom->getDegree() == 1) {
      continue;
    }
    unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(idx[1]);
    const MMFFProp *mmffPropParamsCentralAtom = (*mmffProp)(jAtomType);
    boost::tie(nbr1Idx, end1Nbrs) = mol.getAtomNeighbors(jAtom);
    for (; nbr1Idx != end1Nbrs; ++nbr1Idx) {
      const Atom *iAtom = mol[*nbr1Idx].get();
      idx[0] = iAtom->getIdx();
      boost::tie(nbr2Idx, end2Nbrs) = mol.getAtomNeighbors(jAtom);
      for (; nbr2Idx != end2Nbrs; ++nbr2Idx) {
        if (nbr2Idx < (nbr1Idx + 1)) {
          continue;
        }
        const Atom *kAtom = mol[*nbr2Idx].get();
        idx[2] = kAtom->getIdx();
        unsigned int angleType;
        MMFFAngle mmffAngleParams;
        if (mmffMolProperties->getMMFFAngleBendParams(
                mol, idx[0], idx[1], idx[2], angleType, mmffAngleParams)) {
          AngleBendContrib *contrib = new AngleBendContrib(
              field, idx[0], idx[1], idx[2],
              &mmffAngleParams, mmffPropParamsCentralAtom);
          field->contribs().push_back(ForceFields::ContribPtr(contrib));
          if (mmffMolProperties->getMMFFVerbosity()) {
            unsigned int iAtomType = mmffMolProperties->getMMFFAtomType(idx[0]);
            unsigned int kAtomType = mmffMolProperties->getMMFFAtomType(idx[2]);
            const RDGeom::Point3D p1((*(points[idx[0]]))[0],
                                     (*(points[idx[0]]))[1],
                                     (*(points[idx[0]]))[2]);
            const RDGeom::Point3D p2((*(points[idx[1]]))[0],
                                     (*(points[idx[1]]))[1],
                                     (*(points[idx[1]]))[2]);
            const RDGeom::Point3D p3((*(points[idx[2]]))[0],
                                     (*(points[idx[2]]))[1],
                                     (*(points[idx[2]]))[2]);
            const double cosTheta =
                MMFF::Utils::calcCosTheta(p1, p2, p3, field->distance(idx[0], idx[1]),
                                          field->distance(idx[1], idx[2]));
            const double theta = RAD2DEG * acos(cosTheta);
            const double angleBendEnergy = MMFF::Utils::calcAngleBendEnergy(
                mmffAngleParams.theta0, mmffAngleParams.ka,
                mmffPropParamsCentralAtom->linh, cosTheta);
            if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
              oStream << std::left << std::setw(2) << iAtom->getSymbol() << " #"
                      << std::setw(5) << idx[0] + 1 << std::setw(2)
                      << jAtom->getSymbol() << " #" << std::setw(5)
                      << idx[1] + 1 << std::setw(2) << kAtom->getSymbol()
                      << " #" << std::setw(5) << idx[2] + 1 << std::right
                      << std::setw(5) << iAtomType << std::setw(5) << jAtomType
                      << std::setw(5) << kAtomType << std::setw(6) << angleType
                      << "  " << std::fixed << std::setprecision(3)
                      << std::setw(10) << theta << std::setw(10)
                      << mmffAngleParams.theta0 << std::setw(10)
                      << theta - mmffAngleParams.theta0 << std::setw(10)
                      << angleBendEnergy << std::setw(10) << mmffAngleParams.ka
                      << std::endl;
            }
            totalAngleBendEnergy += angleBendEnergy;
          }
        }
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL ANGLE BEND ENERGY        =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalAngleBendEnergy
            << std::endl;
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addStretchBend(const ROMol &mol, MMFFMolProperties *mmffMolProperties,
                    ForceFields::ForceField *field) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  unsigned int idx[3];
  MMFFPropCollection *mmffProp = MMFFPropCollection::getMMFFProp();
  std::pair<bool, const MMFFStbn *> mmffStbnParams;
  ROMol::ADJ_ITER nbr1Idx;
  ROMol::ADJ_ITER end1Nbrs;
  ROMol::ADJ_ITER nbr2Idx;
  ROMol::ADJ_ITER end2Nbrs;

  unsigned int nAtoms = mol.getNumAtoms();
  double totalStretchBendEnergy = 0.0;
  RDGeom::PointPtrVect points;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "S T R E T C H   B E N D I N G\n\n"
                 "-----------ATOMS-----------    ATOM TYPES      FF    VALENCE "
                 "    DELTA     DELTA     DELTA               F CON\n"
                 "  I        J        K          I    J    K   CLASS    ANGLE  "
                 "    ANGLE     R(I,J)    R(J,K)   ENERGY    I-J (J-K)\n"
                 "-------------------------------------------------------------"
                 "-----------------------------------------------------"
              << std::endl;
    }
    points = field->positions();
  }
  for (idx[1] = 0; idx[1] < nAtoms; ++idx[1]) {
    const Atom *jAtom = mol.getAtomWithIdx(idx[1]);
    if (jAtom->getDegree() == 1) {
      continue;
    }
    unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(idx[1]);
    const MMFFProp *mmffPropParamsCentralAtom = (*mmffProp)(jAtomType);
    if (mmffPropParamsCentralAtom->linh) {
      continue;
    }
    boost::tie(nbr1Idx, end1Nbrs) = mol.getAtomNeighbors(jAtom);
    unsigned int i = 0;
    for (; nbr1Idx != end1Nbrs; ++nbr1Idx) {
      const Atom *iAtom = mol[*nbr1Idx].get();
      boost::tie(nbr2Idx, end2Nbrs) = mol.getAtomNeighbors(jAtom);
      unsigned int j = 0;
      for (; nbr2Idx != end2Nbrs; ++nbr2Idx) {
        const Atom *kAtom = mol[*nbr2Idx].get();
        if (j < (i + 1)) {
          ++j;
          continue;
        }
        idx[0] = iAtom->getIdx();
        idx[2] = kAtom->getIdx();
        unsigned int stretchBendType;
        MMFFStbn mmffStbnParams;
        MMFFBond mmffBondParams[2];
        MMFFAngle mmffAngleParams;
        if (mmffMolProperties->getMMFFStretchBendParams(
                mol, idx[0], idx[1], idx[2], stretchBendType, mmffStbnParams,
                mmffBondParams, mmffAngleParams)) {
          StretchBendContrib *contrib = new StretchBendContrib(
              field, idx[0], idx[1], idx[2], &mmffStbnParams, &mmffAngleParams,
              &mmffBondParams[0], &mmffBondParams[1]);
          field->contribs().push_back(ForceFields::ContribPtr(contrib));
          if (mmffMolProperties->getMMFFVerbosity()) {
            unsigned int iAtomType = mmffMolProperties->getMMFFAtomType(idx[0]);
            unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(idx[1]);
            unsigned int kAtomType = mmffMolProperties->getMMFFAtomType(idx[2]);
            const double dist1 = field->distance(idx[0], idx[1]);
            const double dist2 = field->distance(idx[1], idx[2]);
            const RDGeom::Point3D p1((*(points[idx[0]]))[0],
                                     (*(points[idx[0]]))[1],
                                     (*(points[idx[0]]))[2]);
            const RDGeom::Point3D p2((*(points[idx[1]]))[0],
                                     (*(points[idx[1]]))[1],
                                     (*(points[idx[1]]))[2]);
            const RDGeom::Point3D p3((*(points[idx[2]]))[0],
                                     (*(points[idx[2]]))[1],
                                     (*(points[idx[2]]))[2]);
            const double cosTheta =
                MMFF::Utils::calcCosTheta(p1, p2, p3, dist1, dist2);
            const double theta = RAD2DEG * acos(cosTheta);
            const std::pair<double, double> forceConstants =
                MMFF::Utils::calcStbnForceConstants(&mmffStbnParams);
            const std::pair<double, double> stretchBendEnergies =
                MMFF::Utils::calcStretchBendEnergy(
                    dist1 - mmffBondParams[0].r0, dist2 - mmffBondParams[1].r0,
                    theta - mmffAngleParams.theta0, forceConstants);
            if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
              if (!isDoubleZero(forceConstants.first)) {
                oStream << std::left << std::setw(2) << iAtom->getSymbol()
                        << " #" << std::setw(5) << idx[0] + 1 << std::setw(2)
                        << jAtom->getSymbol() << " #" << std::setw(5)
                        << idx[1] + 1 << std::setw(2) << kAtom->getSymbol()
                        << " #" << std::setw(5) << idx[2] + 1 << std::right
                        << std::setw(5) << iAtomType << std::setw(5)
                        << jAtomType << std::setw(5) << kAtomType
                        << std::setw(6) << stretchBendType << "  " << std::fixed
                        << std::setprecision(3) << std::setw(10) << theta
                        << std::setw(10) << theta - mmffAngleParams.theta0
                        << std::setw(10) << dist1 - mmffBondParams[0].r0
                        << std::setw(10) << dist2 - mmffBondParams[1].r0
                        << std::setw(10) << stretchBendEnergies.first
                        << std::setw(10) << mmffStbnParams.kbaIJK << std::endl;
              }
              if (!isDoubleZero(forceConstants.second)) {
                oStream << std::left << std::setw(2) << kAtom->getSymbol()
                        << " #" << std::setw(5) << idx[2] + 1 << std::setw(2)
                        << jAtom->getSymbol() << " #" << std::setw(5)
                        << idx[1] + 1 << std::setw(2) << iAtom->getSymbol()
                        << " #" << std::setw(5) << idx[0] + 1 << std::right
                        << std::setw(5) << kAtomType << std::setw(5)
                        << jAtomType << std::setw(5) << iAtomType
                        << std::setw(6) << stretchBendType << "  " << std::fixed
                        << std::setprecision(3) << std::setw(10) << theta
                        << std::setw(10) << theta - mmffAngleParams.theta0
                        << std::setw(10) << dist1 - mmffBondParams[0].r0
                        << std::setw(10) << dist2 - mmffBondParams[1].r0
                        << std::setw(10) << stretchBendEnergies.second
                        << std::setw(10) << mmffStbnParams.kbaKJI << std::endl;
              }
            }
            totalStretchBendEnergy +=
                (stretchBendEnergies.first + stretchBendEnergies.second);
          }
        }
        ++j;
      }
      ++i;
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL STRETCH-BEND ENERGY      =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalStretchBendEnergy
            << std::endl;
  }
}

void addOop(const ROMol &mol, MMFFMolProperties *mmffMolProperties,
            ForceFields::ForceField *field) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  unsigned int idx[4];
  unsigned int atomType[4];
  unsigned int n[4];
  const Atom *atom[4];
  ROMol::ADJ_ITER nbrIdx;
  ROMol::ADJ_ITER endNbrs;

  double totalOopBendEnergy = 0.0;
  RDGeom::PointPtrVect points;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "O U T - O F - P L A N E   B E N D I N G\n\n"
                 "--------------ATOMS---------------         ATOM TYPES        "
                 " OOP                FORCE\n"
                 "  I        J        K        L          I    J    K    L     "
                 "ANGLE    ENERGY   CONSTANT\n"
                 "-------------------------------------------------------------"
                 "-----------------------------" << std::endl;
    }
    points = field->positions();
  }
  for (idx[1] = 0; idx[1] < mol.getNumAtoms(); ++idx[1]) {
    atom[1] = mol.getAtomWithIdx(idx[1]);
    if (atom[1]->getDegree() != 3) {
      continue;
    }
    atomType[1] = mmffMolProperties->getMMFFAtomType(idx[1]);
    boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(atom[1]);
    unsigned int i = 0;
    for (; nbrIdx != endNbrs; ++nbrIdx) {
      atom[i] = mol[*nbrIdx].get();
      idx[i] = atom[i]->getIdx();
      atomType[i] = mmffMolProperties->getMMFFAtomType(idx[i]);
      if (!i) {
        ++i;
      }
      ++i;
    }
    MMFFOop mmffOopParams;
    // if no parameters could be found, we exclude this term (SURDOX02)
    if (!(mmffMolProperties->getMMFFOopBendParams(mol, idx[0], idx[1], idx[2],
                                                  idx[3], mmffOopParams))) {
      continue;
    }
    for (unsigned int i = 0; i < 3; ++i) {
      n[1] = 1;
      switch (i) {
        case 0:
          n[0] = 0;
          n[2] = 2;
          n[3] = 3;
          break;

        case 1:
          n[0] = 0;
          n[2] = 3;
          n[3] = 2;
          break;

        case 2:
          n[0] = 2;
          n[2] = 3;
          n[3] = 0;
          break;
      }
      OopBendContrib *contrib = new OopBendContrib(
          field, idx[n[0]], idx[n[1]], idx[n[2]], idx[n[3]], &mmffOopParams);
      field->contribs().push_back(ForceFields::ContribPtr(contrib));
      if (mmffMolProperties->getMMFFVerbosity()) {
        const RDGeom::Point3D p1((*(points[idx[n[0]]]))[0],
                                 (*(points[idx[n[0]]]))[1],
                                 (*(points[idx[n[0]]]))[2]);
        const RDGeom::Point3D p2((*(points[idx[n[1]]]))[0],
                                 (*(points[idx[n[1]]]))[1],
                                 (*(points[idx[n[1]]]))[2]);
        const RDGeom::Point3D p3((*(points[idx[n[2]]]))[0],
                                 (*(points[idx[n[2]]]))[1],
                                 (*(points[idx[n[2]]]))[2]);
        const RDGeom::Point3D p4((*(points[idx[n[3]]]))[0],
                                 (*(points[idx[n[3]]]))[1],
                                 (*(points[idx[n[3]]]))[2]);
        const double chi = MMFF::Utils::calcOopChi(p1, p2, p3, p4);
        const double oopBendEnergy =
            MMFF::Utils::calcOopBendEnergy(chi, mmffOopParams.koop);
        if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
          oStream << std::left << std::setw(2) << atom[0]->getSymbol() << " #"
                  << std::setw(5) << idx[n[0]] + 1 << std::setw(2)
                  << atom[1]->getSymbol() << " #" << std::setw(5)
                  << idx[n[1]] + 1 << std::setw(2) << atom[2]->getSymbol()
                  << " #" << std::setw(5) << idx[n[2]] + 1 << std::setw(2)
                  << atom[3]->getSymbol() << " #" << std::setw(5)
                  << idx[n[3]] + 1 << std::right << std::setw(5)
                  << atomType[n[0]] << std::setw(5) << atomType[n[1]]
                  << std::setw(5) << atomType[n[2]] << std::setw(5)
                  << atomType[n[3]] << std::fixed << std::setprecision(3)
                  << std::setw(10) << chi << std::setw(10) << oopBendEnergy
                  << std::setw(10) << mmffOopParams.koop << std::endl;
        }
        totalOopBendEnergy += oopBendEnergy;
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL OUT-OF-PLANE BEND ENERGY =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalOopBendEnergy
            << std::endl;
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
const std::string DefaultTorsionBondSmarts::ds_string = "[!$(*#*)&!D1]~[!$(*#*)&!D1]";
boost::scoped_ptr<const ROMol> DefaultTorsionBondSmarts::ds_instance;
#ifdef BOOST_THREAD_PROVIDES_ONCE_CXX11
boost::once_flag DefaultTorsionBondSmarts::ds_flag;
#else
boost::once_flag DefaultTorsionBondSmarts::ds_flag = BOOST_ONCE_INIT;
#endif

void DefaultTorsionBondSmarts::create() {
  ds_instance.reset(SmartsToMol(ds_string));
}

const ROMol *DefaultTorsionBondSmarts::query() {
#ifdef RDK_THREADSAFE_SSS
  boost::call_once(&create, ds_flag);
#else
  static bool created = false;
  if (!created) {
    created = true;
    create();
  }
#endif
  return ds_instance.get();
}

void addTorsions(const ROMol &mol, MMFFMolProperties *mmffMolProperties,
                 ForceFields::ForceField *field,
                 const std::string &torsionBondSmarts) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  ROMol::ADJ_ITER nbr1Idx;
  ROMol::ADJ_ITER end1Nbrs;
  ROMol::ADJ_ITER nbr2Idx;
  ROMol::ADJ_ITER end2Nbrs;
  double totalTorsionEnergy = 0.0;
  RDGeom::PointPtrVect points;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "T O R S I O N A L\n\n"
                 "--------------ATOMS---------------      ---ATOM TYPES---     "
                 "FF     TORSION              -----FORCE Params-----\n"
                 "  I        J        K        L          I    J    K    L   "
                 "CLASS     ANGLE    ENERGY       V1        V2        V3\n"
                 "-------------------------------------------------------------"
                 "-----------------------------------------------------"
              << std::endl;
    }
    points = field->positions();
  }
  std::vector<MatchVectType> matchVect;
  const ROMol *defaultQuery = DefaultTorsionBondSmarts::query();
  const ROMol *query = (torsionBondSmarts == DefaultTorsionBondSmarts::string())
                       ? defaultQuery : SmartsToMol(torsionBondSmarts);
  TEST_ASSERT(query);
  unsigned int nHits = SubstructMatch(mol, *query, matchVect);
  if (query != defaultQuery) delete query;

  for (unsigned int i = 0; i < nHits; ++i) {
    MatchVectType match = matchVect[i];
    TEST_ASSERT(match.size() == 2);
    int idx2 = match[0].second;
    int idx3 = match[1].second;
    const Bond *bond = mol.getBondBetweenAtoms(idx2, idx3);
    TEST_ASSERT(bond);
    const Atom *jAtom = mol.getAtomWithIdx(idx2);
    const Atom *kAtom = mol.getAtomWithIdx(idx3);
    if (((jAtom->getHybridization() == Atom::SP2) ||
         (jAtom->getHybridization() == Atom::SP3)) &&
        ((kAtom->getHybridization() == Atom::SP2) ||
         (kAtom->getHybridization() == Atom::SP3))) {
      ROMol::OEDGE_ITER beg1, end1;
      boost::tie(beg1, end1) = mol.getAtomBonds(jAtom);
      while (beg1 != end1) {
        const Bond *tBond1 = mol[*beg1].get();
        if (tBond1 != bond) {
          int idx1 = tBond1->getOtherAtomIdx(idx2);
          ROMol::OEDGE_ITER beg2, end2;
          boost::tie(beg2, end2) = mol.getAtomBonds(kAtom);
          while (beg2 != end2) {
            const Bond *tBond2 = mol[*beg2].get();
            if ((tBond2 != bond) && (tBond2 != tBond1)) {
              int idx4 = tBond2->getOtherAtomIdx(idx3);
              // make sure this isn't a three-membered ring:
              if (idx4 != idx1) {
                // we now have a torsion involving atoms (bonds):
                //  bIdx - (tBond1) - idx1 - (bond) - idx2 - (tBond2) - eIdx
                unsigned int torType;
                MMFFTor mmffTorParams;
                if (mmffMolProperties->getMMFFTorsionParams(
                        mol, idx1, idx2, idx3, idx4, torType, mmffTorParams)) {
                  TorsionAngleContrib *contrib = new TorsionAngleContrib(
                      field, idx1, idx2, idx3, idx4, &mmffTorParams);
                  field->contribs().push_back(ForceFields::ContribPtr(contrib));
                  if (mmffMolProperties->getMMFFVerbosity()) {
                    const Atom *iAtom = mol.getAtomWithIdx(idx1);
                    const Atom *lAtom = mol.getAtomWithIdx(idx4);
                    unsigned int iAtomType =
                        mmffMolProperties->getMMFFAtomType(idx1);
                    unsigned int jAtomType =
                        mmffMolProperties->getMMFFAtomType(idx2);
                    unsigned int kAtomType =
                        mmffMolProperties->getMMFFAtomType(idx3);
                    unsigned int lAtomType =
                        mmffMolProperties->getMMFFAtomType(idx4);
                    const RDGeom::Point3D p1((*(points[idx1]))[0],
                                             (*(points[idx1]))[1],
                                             (*(points[idx1]))[2]);
                    const RDGeom::Point3D p2((*(points[idx2]))[0],
                                             (*(points[idx2]))[1],
                                             (*(points[idx2]))[2]);
                    const RDGeom::Point3D p3((*(points[idx3]))[0],
                                             (*(points[idx3]))[1],
                                             (*(points[idx3]))[2]);
                    const RDGeom::Point3D p4((*(points[idx4]))[0],
                                             (*(points[idx4]))[1],
                                             (*(points[idx4]))[2]);
                    const double cosPhi =
                        MMFF::Utils::calcTorsionCosPhi(p1, p2, p3, p4);
                    const double torsionEnergy = MMFF::Utils::calcTorsionEnergy(
                        mmffTorParams.V1, mmffTorParams.V2, mmffTorParams.V3,
                        cosPhi);
                    if (mmffMolProperties->getMMFFVerbosity() ==
                        MMFF_VERBOSITY_HIGH) {
                      oStream
                          << std::left << std::setw(2) << iAtom->getSymbol()
                          << " #" << std::setw(5) << idx1 + 1 << std::setw(2)
                          << jAtom->getSymbol() << " #" << std::setw(5)
                          << idx2 + 1 << std::setw(2) << kAtom->getSymbol()
                          << " #" << std::setw(5) << idx3 + 1 << std::setw(2)
                          << lAtom->getSymbol() << " #" << std::setw(5)
                          << idx4 + 1 << std::right << std::setw(5) << iAtomType
                          << std::setw(5) << jAtomType << std::setw(5)
                          << kAtomType << std::setw(5) << lAtomType
                          << std::setw(6) << torType << "  " << std::fixed
                          << std::setprecision(3) << std::setw(10)
                          << RAD2DEG * acos(cosPhi) << std::setw(10)
                          << torsionEnergy << std::setw(10) << mmffTorParams.V1
                          << std::setw(10) << mmffTorParams.V2 << std::setw(10)
                          << mmffTorParams.V3 << std::endl;
                    }
                    totalTorsionEnergy += torsionEnergy;
                  }
                }
              }
            }
            beg2++;
          }
        }
        beg1++;
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL TORSIONAL ENERGY         =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalTorsionEnergy
            << std::endl;
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addVdW(const ROMol &mol, int confId, MMFFMolProperties *mmffMolProperties,
            ForceFields::ForceField *field,
            boost::shared_array<boost::uint8_t> neighborMatrix,
            double nonBondedThresh, bool ignoreInterfragInteractions) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  INT_VECT fragMapping;
  if (ignoreInterfragInteractions) {
    std::vector<ROMOL_SPTR> molFrags =
        MolOps::getMolFrags(mol, true, &fragMapping);
  }

  unsigned int nAtoms = mol.getNumAtoms();
  double totalVdWEnergy = 0.0;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "V A N   D E R   W A A L S\n\n"
                 "------ATOMS------   ATOM TYPES                               "
                 "  WELL\n"
                 "  I        J          I    J    DISTANCE   ENERGY     R*     "
                 " DEPTH\n"
                 "-------------------------------------------------------------"
                 "-------" << std::endl;
    }
  }
  const Conformer &conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < nAtoms; ++i) {
    for (unsigned int j = i + 1; j < nAtoms; ++j) {
      if (ignoreInterfragInteractions && (fragMapping[i] != fragMapping[j])) {
        continue;
      }
      if (getTwoBitCell(neighborMatrix, twoBitCellPos(nAtoms, i, j)) >= RELATION_1_4) {
        double dist = (conf.getAtomPos(i) - conf.getAtomPos(j)).length();
        if (dist > nonBondedThresh) {
          continue;
        }
        MMFFVdWRijstarEps mmffVdWConstants;
        if (mmffMolProperties->getMMFFVdWParams(i, j, mmffVdWConstants)) {
          VdWContrib *contrib = new VdWContrib(field, i, j, &mmffVdWConstants);
          field->contribs().push_back(ForceFields::ContribPtr(contrib));
          if (mmffMolProperties->getMMFFVerbosity()) {
            const Atom *iAtom = mol.getAtomWithIdx(i);
            const Atom *jAtom = mol.getAtomWithIdx(j);
            const double vdWEnergy = MMFF::Utils::calcVdWEnergy(
                dist, mmffVdWConstants.R_ij_star, mmffVdWConstants.epsilon);
            if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
              unsigned int iAtomType = mmffMolProperties->getMMFFAtomType(i);
              unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(j);
              oStream << std::left << std::setw(2) << iAtom->getSymbol() << " #"
                      << std::setw(5) << i + 1 << std::setw(2)
                      << jAtom->getSymbol() << " #" << std::setw(5) << j + 1
                      << std::right << std::setw(5) << iAtomType << std::setw(5)
                      << jAtomType << "  " << std::fixed << std::setprecision(3)
                      << std::setw(9) << dist << std::setw(10) << vdWEnergy
                      << std::setw(9) << mmffVdWConstants.R_ij_star << std::setw(9)
                      << mmffVdWConstants.epsilon << std::endl;
            }
            totalVdWEnergy += vdWEnergy;
          }
        }
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL VAN DER WAALS ENERGY     =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalVdWEnergy
            << std::endl;
  }
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
void addEle(const ROMol &mol, int confId, MMFFMolProperties *mmffMolProperties,
            ForceFields::ForceField *field,
            boost::shared_array<boost::uint8_t> neighborMatrix,
            double nonBondedThresh, bool ignoreInterfragInteractions) {
  PRECONDITION(field, "bad ForceField");
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  std::ostream &oStream = mmffMolProperties->getMMFFOStream();
  INT_VECT fragMapping;
  if (ignoreInterfragInteractions) {
    std::vector<ROMOL_SPTR> molFrags =
        MolOps::getMolFrags(mol, true, &fragMapping);
  }
  unsigned int nAtoms = mol.getNumAtoms();
  double totalEleEnergy = 0.0;
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << "\n"
                 "E L E C T R O S T A T I C\n\n"
                 "------ATOMS------   ATOM TYPES\n"
                 "  I        J          I    J    DISTANCE   ENERGY\n"
                 "--------------------------------------------------"
              << std::endl;
    }
  }
  const Conformer &conf = mol.getConformer(confId);
  double dielConst = mmffMolProperties->getMMFFDielectricConstant();
  boost::uint8_t dielModel = mmffMolProperties->getMMFFDielectricModel();
  for (unsigned int i = 0; i < nAtoms; ++i) {
    for (unsigned int j = i + 1; j < nAtoms; ++j) {
      if (ignoreInterfragInteractions && (fragMapping[i] != fragMapping[j])) {
        continue;
      }
      boost::uint8_t cell = getTwoBitCell(neighborMatrix, twoBitCellPos(nAtoms, i, j));
      bool is1_4 = (cell == RELATION_1_4);
      if (cell >= RELATION_1_4) {
        if (isDoubleZero(mmffMolProperties->getMMFFPartialCharge(i))
          || isDoubleZero(mmffMolProperties->getMMFFPartialCharge(j)))
          continue;
        double dist = (conf.getAtomPos(i) - conf.getAtomPos(j)).length();
        if (dist > nonBondedThresh) {
          continue;
        }
        double chargeTerm = mmffMolProperties->getMMFFPartialCharge(i) *
                            mmffMolProperties->getMMFFPartialCharge(j) /
                            dielConst;
        EleContrib *contrib = new EleContrib(
          field, i, j, chargeTerm, dielModel, is1_4);
        field->contribs().push_back(ForceFields::ContribPtr(contrib));
        if (mmffMolProperties->getMMFFVerbosity()) {
          const unsigned int iAtomType = mmffMolProperties->getMMFFAtomType(i);
          const unsigned int jAtomType = mmffMolProperties->getMMFFAtomType(j);
          const Atom *iAtom = mol.getAtomWithIdx(i);
          const Atom *jAtom = mol.getAtomWithIdx(j);
          const double eleEnergy = MMFF::Utils::calcEleEnergy(
            i, j, dist, chargeTerm, dielModel, is1_4);
          if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
            oStream << std::left << std::setw(2) << iAtom->getSymbol() << " #"
                    << std::setw(5) << i + 1 << std::setw(2)
                    << jAtom->getSymbol() << " #" << std::setw(5) << j + 1
                    << std::right << std::setw(5) << iAtomType << std::setw(5)
                    << jAtomType << "  " << std::fixed << std::setprecision(3)
                    << std::setw(9) << dist << std::setw(10) << eleEnergy
                    << std::endl;
          }
          totalEleEnergy += eleEnergy;
        }
      }
    }
  }
  if (mmffMolProperties->getMMFFVerbosity()) {
    if (mmffMolProperties->getMMFFVerbosity() == MMFF_VERBOSITY_HIGH) {
      oStream << std::endl;
    }
    oStream << "TOTAL ELECTROSTATIC ENERGY     =" << std::right << std::setw(16)
            << std::fixed << std::setprecision(4) << totalEleEnergy
            << std::endl;
  }
}

}  // end of namespace Tools

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
ForceFields::ForceField *constructForceField(ROMol &mol, double nonBondedThresh,
                                             int confId,
                                             bool ignoreInterfragInteractions) {
  MMFFMolProperties mmffMolProperties(mol);
  PRECONDITION(mmffMolProperties.isValid(),
               "missing atom types - invalid force-field");
  ForceFields::ForceField *res =
      constructForceField(mol, &mmffMolProperties, nonBondedThresh, confId,
                          ignoreInterfragInteractions);

  return res;
}

// ------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------
ForceFields::ForceField *constructForceField(
    ROMol &mol, MMFFMolProperties *mmffMolProperties, double nonBondedThresh,
    int confId, bool ignoreInterfragInteractions) {
  PRECONDITION(mmffMolProperties, "bad MMFFMolProperties");
  PRECONDITION(mmffMolProperties->isValid(),
               "missing atom types - invalid force-field");

  ForceFields::ForceField *res = new ForceFields::ForceField();
  // add the atomic positions:
  Conformer &conf = mol.getConformer(confId);
  for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {
    res->positions().push_back(&(conf.getAtomPos(i)));
  }

  res->initialize();
  if (mmffMolProperties->getMMFFBondTerm()) {
    Tools::addBonds(mol, mmffMolProperties, res);
  }
  if (mmffMolProperties->getMMFFAngleTerm()) {
    Tools::addAngles(mol, mmffMolProperties, res);
  }
  if (mmffMolProperties->getMMFFStretchBendTerm()) {
    Tools::addStretchBend(mol, mmffMolProperties, res);
  }
  if (mmffMolProperties->getMMFFOopTerm()) {
    Tools::addOop(mol, mmffMolProperties, res);
  }
  if (mmffMolProperties->getMMFFTorsionTerm()) {
    Tools::addTorsions(mol, mmffMolProperties, res);
  }
  if (mmffMolProperties->getMMFFVdWTerm() ||
      mmffMolProperties->getMMFFEleTerm()) {
    boost::shared_array<boost::uint8_t> neighborMat =
        Tools::buildNeighborMatrix(mol);
    if (mmffMolProperties->getMMFFVdWTerm()) {
      Tools::addVdW(mol, confId, mmffMolProperties, res, neighborMat,
                    nonBondedThresh, ignoreInterfragInteractions);
    }
    if (mmffMolProperties->getMMFFEleTerm()) {
      Tools::addEle(mol, confId, mmffMolProperties, res, neighborMat,
                    nonBondedThresh, ignoreInterfragInteractions);
    }
  }

  return res;
}
}
}


text:
currentl datastore is a MySQL db on the same machine as the app - hosted on OpenShift. (not active as of 1/3/15)

## log
id, datetime, userid, action, medium

## players

id, firstName, lastName, subscriptionStatus, phone, email, twitter, gameState, timezone

redpajama_set_name: RedPajamaGithub


text:
from os import path
from PyQt5.QtWidgets import QDialog
from PyQt5.uic import loadUi

from maestro.gui.main import app
from maestro.core import audio

class SpectroDialog(QDialog):
	def __init__(self, flags, *args, **kwargs):
		super(SpectroDialog, self).__init__(flags, *args, **kwargs)
		loadUi(path.join(path.dirname(__file__), 'spectro.ui'), self)

		graphItem = self.graph.getPlotItem()
		graphItem.setXRange(0, 3000)
		graphItem.setYRange(0, 3000)
		self.microphone = audio.IO()

	def show(self):
		super(SpectroDialog, self).show()
		while True:
			data = self.microphone.readData()
			f, Pxx = audio.get_spectrum(data, self.microphone.RATE)
			self.graph.plot(x=f, y=Pxx, clear=True)
			app.processEvents()


text:
package org.knowm.xchange.bitmarket.service.account;

import static org.junit.Assert.assertNotNull;

import org.junit.Before;
import org.junit.Test;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitmarket.ExchangeUtils;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.service.polling.account.PollingAccountService;

/**
 * @author kfonal
 */
public class DepositFetchIntegration {

  private Exchange exchange;

  @Before
  public void setUp() {

    exchange = ExchangeUtils.createExchangeFromProperties();
  }

  @Test
  public void fetchDepositTest() throws Exception {

    if (exchange.getExchangeSpecification().getApiKey() == null || exchange.getExchangeSpecification().getSecretKey() == null) {
      return; // forces pass if there is no keys passed
    }

    PollingAccountService service = exchange.getPollingAccountService();
    assertNotNull(service);
    //verify address for deposit for BTC exists
    String deposit = service.requestDepositAddress(Currency.BTC);
    assertNotNull(deposit);
    //verify address for deposit for LTC exists
    deposit = service.requestDepositAddress(Currency.LTC);
    assertNotNull(deposit);
  }
}


text:
package org.apache.harmony.tools.toolutils.tests;

import java.io.File;
import java.io.IOException;
import java.security.KeyStore;

import junit.framework.TestCase;

import org.apache.harmony.tools.toolutils.KeyStoreLoaderSaver;

public class KeyStoreLoaderSaverTest extends TestCase {

    public static void main(String[] args) {
        junit.textui.TestRunner.run(KeyStoreLoaderSaverTest.class);
    }

    /**
     * @tests 'KeyStoreLoaderSaver.loadStore(String, String, char[], String)'
     */
    public void testLoadStore() throws Exception {

        // Regression for HARMONY-1794
        try {
            KeyStoreLoaderSaver.loadStore("there_is_no_such_file", "BKS", "pwd"
                    .toCharArray(), null);

            // IOException must be thrown, because file does not exist
            fail("No expected IOException");
        } catch (IOException ok) {
        }
    }

    /**
     * @tests 'KeyStoreLoaderSaver.saveStore(KeyStore, String, char[], boolean)'
     */
    public void testSaveStore() throws Exception {

        // Regression for HARMONY-1927
        // create a path to save the store to
        String tempDir = System.getProperty("java.io.tmpdir")
                + File.separatorChar;
        String keyStorePath = tempDir + "SaveStoreTestTemporaryFile";
        try {
            KeyStore keyStore = KeyStoreLoaderSaver.loadStore(null, "BKS",
                    "pwd".toCharArray(), null);

            KeyStoreLoaderSaver.saveStore(keyStore, keyStorePath, "pwd"
                    .toCharArray(), false);
        } finally {
            new File(keyStorePath).delete();
        }
    }
}


text:
    <java-class-file name="D:\Experiments\Analisi di Sopravvivenza\Progetto16715\ProgettiDaAnalizzare\jfreechart\jfreechart-0.6.0\source\com\jrefinery\chart\event\ChartChangeEvent.java">
        <package-decl name="com.jrefinery.chart.event"/>
        <class name="ChartChangeEvent" visibility="public">
            <constructor visibility="public" name="ChartChangeEvent">
            </constructor>
            <constructor visibility="public" name="ChartChangeEvent">
            </constructor>
            <constructor visibility="public" name="ChartChangeEvent">
            </constructor>
            <method name="getChart" visibility="public">
            </method>
            <method name="setChart" visibility="public">
            </method>
            <method name="getType" visibility="public">
            </method>
            <method name="setType" visibility="public">
            </method>
        </class>
    </java-class-file>


text:
package org.terasology.world.internal;

import org.terasology.engine.SimpleUri;

/**
 * Summary information on a world.
 *
 */
public class WorldInfo {

    private String title = "";
    private String customTitle = "";
    private String seed = "";
    private long time;
    private SimpleUri worldGenerator = new SimpleUri();

    public WorldInfo() {
    }

    public WorldInfo(String title, String seed, long time, SimpleUri worldGenerator) {
        this(title, "", seed, time, worldGenerator);
    }

    public WorldInfo(String title, String customTitle, String seed, long time, SimpleUri worldGenerator) {
        if (title != null) {
            this.title = title;
        }
        this.customTitle = customTitle;
        if (seed != null) {
            this.seed = seed;
        }
        if (worldGenerator != null) {
            this.worldGenerator = worldGenerator;
        }
        this.time = time;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        if (title != null) {
            this.title = title;
        }
    }

    public String getCustomTitle() {
        return customTitle;
    }

    public String getSeed() {
        return seed;
    }

    public void setSeed(String seed) {
        if (seed != null) {
            this.seed = seed;
        }
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public SimpleUri getWorldGenerator() {
        return worldGenerator;
    }

    public void setWorldGenerator(SimpleUri worldGenerator) {
        this.worldGenerator = worldGenerator;
    }

    @Override
    public String toString() {
        return title;
    }
}


text:
#ifndef __ASM_SH64_CHECKSUM_H
#define __ASM_SH64_CHECKSUM_H

#include <asm/registers.h>

/*
 * computes the checksum of a memory block at buff, length len,
 * and adds in "sum" (32-bit)
 *
 * returns a 32-bit number suitable for feeding into itself
 * or csum_tcpudp_magic
 *
 * this function must be called with even lengths, except
 * for the last fragment, which may be odd
 *
 * it's best to have buff aligned on a 32-bit boundary
 */
asmlinkage unsigned int csum_partial(const unsigned char *buff, int len,
				     unsigned int sum);

/*
 *	Note: when you get a NULL pointer exception here this means someone
 *	passed in an incorrect kernel address to one of these functions.
 *
 *	If you use these functions directly please don't forget the
 *	access_ok().
 */

unsigned int csum_partial_copy_nocheck(const char *src, char *dst, int len,
				       unsigned int sum);

unsigned int csum_partial_copy_from_user(const char *src, char *dst,
					 int len, int sum, int *err_ptr);

/*
 * These are the old (and unsafe) way of doing checksums, a warning message will be
 * printed if they are used and an exeption occurs.
 *
 * these functions should go away after some time.
 */

#define csum_partial_copy_fromuser csum_partial_copy

unsigned int csum_partial_copy(const char *src, char *dst, int len,
			       unsigned int sum);

static inline unsigned short csum_fold(unsigned int sum)
{
        sum = (sum & 0xffff) + (sum >> 16);
        sum = (sum & 0xffff) + (sum >> 16);
        return ~(sum);
}

unsigned short ip_fast_csum(unsigned char * iph, unsigned int ihl);

unsigned long csum_tcpudp_nofold(unsigned long saddr, unsigned long daddr,
				 unsigned short len, unsigned short proto,
				 unsigned int sum);

/*
 * computes the checksum of the TCP/UDP pseudo-header
 * returns a 16-bit checksum, already complemented
 */
static inline unsigned short int csum_tcpudp_magic(unsigned long saddr,
						   unsigned long daddr,
						   unsigned short len,
						   unsigned short proto,
						   unsigned int sum)
{
	return csum_fold(csum_tcpudp_nofold(saddr,daddr,len,proto,sum));
}

/*
 * this routine is used for miscellaneous IP-like checksums, mainly
 * in icmp.c
 */
static inline unsigned short ip_compute_csum(unsigned char * buff, int len)
{
	return csum_fold(csum_partial(buff, len, 0));
}

#endif /* __ASM_SH64_CHECKSUM_H */


text:
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)))
import manage
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.base'
from systems import models
def main():
    print 'id, old_hostname, new_hostname'
    for sys in models.System.objects.all():
        if sys.keyvalue_set.filter(key='system.hostname.alias.0'):
            old_hostname = sys.keyvalue_set.filter(key='system.hostname.alias.0')[0].value
        else:
            old_hostname = sys.hostname
        if old_hostname != sys.hostname:
            print '%s,%s,%s' % (sys.id, old_hostname, sys.hostname)

if __name__ == '__main__':
    main()


text:
import tornado.ioloop
import tornado.web
from tornado import gen
import pymongo.errors as perr
import doct
import ujson
import jsonschema
import json
import types
from metadataservice.server import utils
from metadatastore.core import NoRunStop, NoEventDescriptors, NoRunStart

loop = tornado.ioloop.IOLoop.instance()

class DefaultHandler(tornado.web.RequestHandler):
    """DefaultHandler which takes care of CORS for @hslepicka js gui."""
    @tornado.web.asynchronous
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Content-type', 'application/json')

    def data_received(self, chunk):
        """Abstract method, here to show it exists explicitly.
        Useful for streaming client"""
        pass

    def queryable(self, func):
        try:
            return self.queryables[func]
        except KeyError as err:
            utils.report_error(500, 'Provided query method {} is not supported'.format(func))

    def insertable(self, func):
        try:
            return self.insertables[func]
        except KeyError as err:
            utils.report_error(500, 'Not a valid insert routine', func)

    @tornado.web.asynchronous
    def get(self):
        request = utils.unpack_params(self)
        try:
            sign = request['signature']
        except KeyError:
            utils.report_error(400,
                               'No valid signature function provided!')
        try:
            func = self.queryable(sign)
        except AttributeError as err:
            utils.report_error(500, err)
        try:
            query = request['query']
        except KeyError:
            utils.report_error(400,
                               'A query string must be provided')
        try:
            docs_gen = func(**query)
        except (NoRunStop, NoRunStart, NoEventDescriptors):
           docs_gen = []
        if isinstance(docs_gen, (doct.Document, list)):
            self.write(json.dumps(docs_gen))
        elif isinstance(docs_gen, types.GeneratorType):
            self.write(json.dumps(list(docs_gen)))
        self.finish()

    @tornado.web.asynchronous
    def post(self):
        payload = ujson.loads(self.request.body.decode("utf-8"))
        try:
            data = payload.pop('data')
        except KeyError:
            utils.report_error(400, 'No data provided to insert ')
        try:
            sign = payload.pop('signature')
        except KeyError:
            utils.report_error(400, 'No signature provided for insert')
        try:
            func = self.insertable(sign)
        except AttributeError as err:
            utils.report_error(500, err)
        try:
            func(**data)
        except (RuntimeError, TypeError, KeyError) as err:
            utils.report_error(500, err, data)
        self.write(ujson.dumps({"status": True}))
        self.finish()

    @tornado.web.asynchronous
    def put(self):
        utils.report_error(403, 'Not allowed on server')

    @tornado.web.asynchronous
    def delete(self):
        utils.report_error(403, 'Not allowed on server')

class RunStartHandler(DefaultHandler):
    """Handler for run_start insert and query operations.
    Uses traditional RESTful lingo. get for querying and post for inserts

    Methods
    -------
    queryable()
        Identifies whether client provided function is fair game for get()
    get()
        Query run_start documents.
    post()
        Insert a run_start document.Same validation method as bluesky, secondary
        safety net.
    insertable()
        Identifies whether client provided function name is fair game for post(). If so,
        it returns the appropriate handle from metadatastore
    queryable()
        Identifies whether client provided function name is fair game for get(). If so,
        it returns the appropriate handle from metadatastore
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        mdsro = self.settings['mdsro']
        mdsrw = self.settings['mdsrw']
        self.queryables = {'find_run_starts': mdsro.find_run_starts,
                           'run_start_given_uid': mdsro.run_start_given_uid,
                           'find_last': mdsro.find_last}
        self.insertables = {'insert_run_start': mdsrw.insert_run_start}

class EventDescriptorHandler(DefaultHandler):
    """Handler for event_descriptor insert and query operations.
    Uses traditional RESTful lingo. get for querying and post for inserts

    Methods
    -------
    get()
        Query event_descriptor documents. Get params are json encoded in order
        to preserve type
    post()
        Insert a event_descriptor document.Same validation method as bluesky,
        secondary safety net.
    insertable()
        Identifies whether client provided function name is fair game for post(). If so,
        it returns the appropriate handle from metadatastore
    queryable()
        Identifies whether client provided function name is fair game for get(). If so,
        it returns the appropriate handle from metadatastore
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        mdsro = self.settings['mdsro']
        mdsrw = self.settings['mdsrw']
        self.queryables = {'descriptor_given_uid': mdsro.descriptor_given_uid,
                           'descriptors_by_start': mdsro.descriptors_by_start,
                           'find_descriptors': mdsro.find_descriptors}
        self.insertables = {'insert_descriptor': mdsrw.insert_descriptor}

class RunStopHandler(DefaultHandler):
    """Handler for run_stop insert and query operations.
    Uses traditional RESTful lingo. get for querying and post for inserts

    Methods
    -------
    get()
        Query run_stop documents. Get params are json encoded in order to preserve type
    post()
        Insert a run_stop document.Same validation method as bluesky, secondary
        safety net.
    insertable()
        Identifies whether client provided function name is fair game for post(). If so,
        it returns the appropriate handle from metadatastore
    queryable()
        Identifies whether client provided function name is fair game for get(). If so,
        it returns the appropriate handle from metadatastore
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        mdsro = self.settings['mdsro']
        mdsrw = self.settings['mdsrw']
        self.queryables = {'stop_by_start': mdsro.stop_by_start,
                           'run_stop_given_uid': mdsro.run_stop_given_uid,
                           'find_run_stops': mdsro.find_run_stops}
        self.insertables = {'insert_run_stop': mdsrw.insert_run_stop}

class EventHandler(DefaultHandler):
    """Handler for event insert and query operations.
    Uses traditional RESTful lingo. get for querying and post for inserts

    Methods
    -------
    get()
        Query event documents. Get params are json encoded in order to preserve type
    post()
        Insert a event document.Same validation method as bluesky, secondary
        safety net.
    insertable()
        Identifies whether client provided function name is fair game for post(). If so,
        it returns the appropriate handle from metadatastore
    queryable()
        Identifies whether client provided function name is fair game for get(). If so,
        it returns the appropriate handle from metadatastore
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        mdsro = self.settings['mdsro']
        mdsrw = self.settings['mdsrw']
        self.queryables = {'get_events_generator': mdsro.get_events_generator,
                           'get_events_table': mdsro.get_events_table,
                           'find_events': mdsro.find_events}
        self.insertables = {'insert_event': mdsrw.insert_event,
                            'bulk_insert_events': mdsrw.bulk_insert_events
                            }


text:
class Elasticad::User
  include Mongoid::Document
end


text:
This package contains a C# SDK for Azure Communication Services for SMS and Telephony.

[Source code][source] | [Package (NuGet)][package] | [Product documentation][product_docs]
## Getting started

### Install the package
Install the Azure Communication SMS client library for .NET with [NuGet][nuget]:

```dotnetcli
dotnet add package Azure.Communication.Sms
```

### Prerequisites
You need an [Azure subscription][azure_sub] and a [Communication Service Resource][communication_resource_docs] to use this package.

To create a new Communication Service, you can use the [Azure Portal][communication_resource_create_portal], the [Azure PowerShell][communication_resource_create_power_shell], or the [.NET management client library][communication_resource_create_net].

### Key concepts
`SmsClient` provides the functionality to send messages between phone numbers.

### Using statements
```C# Snippet:Azure_Communication_Sms_Tests_UsingStatements
using System;
using Azure.Communication.Sms;
```

### Authenticate the client
SMS clients can be authenticated using the connection string acquired from an Azure Communication Resource in the [Azure Portal][azure_portal].

```C# Snippet:Azure_Communication_Sms_Tests_Samples_CreateSmsClient
var connectionString = "<connection_string>"; // Find your Communication Services resource in the Azure portal
SmsClient client = new SmsClient(connectionString);
```

Alternatively, SMS clients can also be authenticated using a valid token credential. With this option,
`AZURE_CLIENT_SECRET`, `AZURE_CLIENT_ID` and `AZURE_TENANT_ID` environment variables need to be set up for authentication.

```C# Snippet:Azure_Communication_Sms_Tests_Samples_CreateSmsClientWithToken
string endpoint = "<endpoint_url>";
TokenCredential tokenCredential = new DefaultAzureCredential();
SmsClient client = new SmsClient(new Uri(endpoint), tokenCredential);
```

## Examples
### Send a 1:1 SMS Message
To send a SMS message, call the `Send` or `SendAsync` function from the `SmsClient`.
```C# Snippet:Azure_Communication_Sms_Tests_SendAsync
SmsSendResult sendResult = await smsClient.SendAsync(
    from: "<from-phone-number>", // Your E.164 formatted from phone number used to send SMS
    to: "<to-phone-number>", // E.164 formatted recipient phone number
    message: "Hi");
Console.WriteLine($"Sms id: {sendResult.MessageId}");
```
### Send a 1:N SMS Message
To send a SMS message to a list of recipients, call the `Send` or `SendAsync` function from the `SmsClient` with a list of recipient's phone numbers.
You may also add pass in an options object to specify whether the delivery report should be enabled and set custom tags.
```C# Snippet:Azure_Communication_SmsClient_Send_GroupSmsWithOptionsAsync
var response = await smsClient.SendAsync(
    from: "<from-phone-number>", // Your E.164 formatted from phone number used to send SMS
    to: new string[] { "<to-phone-number-1>", "<to-phone-number-2>" }, // E.164 formatted recipient phone numbers
    message: "Weekly Promotion!",
    options: new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL
    {
        Tag = "marketing", // custom tags
    });
foreach (SmsSendResult result in response.Value)
{
    Console.WriteLine($"Sms id: {result.MessageId}");
    Console.WriteLine($"Send Result Successful: {result.Successful}");
}
```
## Troubleshooting
SMS operations will throw an exception if the request to the server fails.
Exceptions will not be thrown if the error is caused by an individual message, only if something fails with the overall request.
Please use the `Successful` flag to validate each individual result to verify if the message was sent.

```C# Snippet:Azure_Communication_Sms_Tests_Troubleshooting
try
{
    var response = await smsClient.SendAsync(
        from: "<from-phone-number>" // Your E.164 formatted phone number used to send SMS
        to: new string [] {"<to-phone-number-1>", "<to-phone-number-2>"}, // E.164 formatted recipient phone number
        message: "Weekly Promotion!",
        options: new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL
        {
            Tag = "marketing", // custom tags
        });
    foreach (SmsSendResult result in response.Value)
    {
        if (result.Successful)
        {
            Console.WriteLine($"Successfully sent this message: {result.MessageId} to {result.To}.");
        }
        else
        {
            Console.WriteLine($"Something went wrong when trying to send this message {result.MessageId} to {result.To}.");
            Console.WriteLine($"Status code {result.HttpStatusCode} and error message {result.ErrorMessage}.");
        }
    }
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.Message);
}
```

## Next steps
- [Read more about SMS in Azure Communication Services][nextsteps]
- For a basic guide on how to configure Delivery Reporting for your SMS messages please refer to the [Handle SMS Events quickstart][handle_sms_events].

## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla].

This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.

<!-- LINKS -->
[azure_sub]: https://azure.microsoft.com/free/dotnet/
[azure_portal]: https://portal.azure.com
[cla]: https://cla.microsoft.com
[coc]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
[coc_contact]: mailto:opencode@microsoft.com
[communication_resource_docs]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-azp
[communication_resource_create_portal]:  https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-azp
[communication_resource_create_power_shell]: https://docs.microsoft.com/powershell/module/az.communication/new-azcommunicationservice
[communication_resource_create_net]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-net
[handle_sms_events]: https://docs.microsoft.com/azure/communication-services/quickstarts/telephony-sms/handle-sms-events
[package]: https://www.nuget.org/packages/Azure.Communication.Sms
[product_docs]: https://docs.microsoft.com/azure/communication-services/overview
[nextsteps]:https://docs.microsoft.com/azure/communication-services/quickstarts/telephony-sms/send?pivots=programming-language-csharp
[nuget]: https://www.nuget.org/
[source]: https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/communication/Azure.Communication.Sms/src


text:
mb_osname := $(shell uname)
mb_version := $(shell cat VERSION)
mb_count := $(shell git rev-list --count $(shell cat VERSION)..)
mb_hash := $(shell git rev-parse --short HEAD)

.PHONY: build doc fmt lint run test vendor_clean vendor_get vendor_update vet

default: build

build: vet
	go build -ldflags "-X main.Version $(mb_version)-$(mb_count).$(mb_hash)" -v -o ./dist/mediabase ./server/boot.go

doc:
	godoc -http=:6060 -index

# http://golang.org/cmd/go/#hdr-Run_gofmt_on_package_sources
fmt:
	go fmt ./...

# https://github.com/golang/lint
# go get github.com/golang/lint/golint
lint:
	golint ./src

test:
	go test ./...

clean:
	rm -rf build
	rm -rf dist/web/app
	rm -rf dist/web/css
	rm -rf dist/web/js
	rm -rf dist/web/index.html
	unlink dist/web/img || true
	unlink dist/db || true

run: clean build
	cp -r client/* dist/web
	ln -s "$(shell echo $$HOME)/.mediabase/db" dist/db
	ln -s "$(shell echo $$HOME)/.mediabase/web/img" dist/web/img
	cd dist && ./mediabase

release: clean build
	mkdir build
	cp dist/mediabase build
	cp CHANGES build
	cp LICENSE build
	cp README.md build
ifeq ($(mb_osname), Darwin)
	cd build && zip mediabase-$(mb_version)-darwin-amd64.zip *
else
	cd build && tar czf mediabase-$(mb_version)-linux-amd64.tar.gz *
endif

# http://godoc.org/code.google.com/p/go.tools/cmd/vet
# go get code.google.com/p/go.tools/cmd/vet
vet:
	go vet ./server/...


text:
module Azure::Network::Mgmt::V2020_06_01
  module Models
    #
    # VirtualNetworkGatewayConnection properties.
    #
    class TunnelConnectionHealth

      include MsRestAzure

      # @return [String] Tunnel name.
      attr_accessor :tunnel

      # @return [VirtualNetworkGatewayConnectionStatus] Virtual Network Gateway
      # connection status. Possible values include: 'Unknown', 'Connecting',
      # 'Connected', 'NotConnected'
      attr_accessor :connection_status

      # @return [Integer] The Ingress Bytes Transferred in this connection.
      attr_accessor :ingress_bytes_transferred

      # @return [Integer] The Egress Bytes Transferred in this connection.
      attr_accessor :egress_bytes_transferred

      # @return [String] The time at which connection was established in Utc
      # format.
      attr_accessor :last_connection_established_utc_time

      #
      # Mapper for TunnelConnectionHealth class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'TunnelConnectionHealth',
          type: {
            name: 'Composite',
            class_name: 'TunnelConnectionHealth',
            model_properties: {
              tunnel: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'tunnel',
                type: {
                  name: 'String'
                }
              },
              connection_status: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'connectionStatus',
                type: {
                  name: 'String'
                }
              },
              ingress_bytes_transferred: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'ingressBytesTransferred',
                type: {
                  name: 'Number'
                }
              },
              egress_bytes_transferred: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'egressBytesTransferred',
                type: {
                  name: 'Number'
                }
              },
              last_connection_established_utc_time: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'lastConnectionEstablishedUtcTime',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
mutable struct PhysicalParam
	dt::Float64
	w_car::Float64
	l_car::Float64
	v_nominal::Float64
	w_lane::Float64
	v_fast::Float64
	v_slow::Float64
	v_med::Float64
	v_max::Float64
	v_min::Float64
    brake_limit::Float64 # always positive
    nb_lanes::Int
	lane_length::Float64
end

function PhysicalParam(nb_lanes::Int;dt::Float64=0.75,
						w_car::Float64=2.,
						l_car::Float64=4.,
						v_nominal::Float64=31.,
						w_lane::Float64=4.,
						v_fast::Float64=35.,
						v_slow::Float64=27.,
						v_med::Float64=31.,
						lane_length::Float64=12.,
						v_max::Float64=v_fast+0.,
						v_min::Float64=v_slow-0.,
                        brake_limit::Float64=8. # coefficient of friction of about 0.8
                        )

	assert(v_fast >= v_med)
	assert(v_med >= v_slow)
	assert(v_fast > v_slow)
    return PhysicalParam(dt, w_car, l_car, v_nominal, w_lane, v_fast, v_slow, v_med, v_max, v_min, brake_limit, nb_lanes, lane_length)
end

"""
Returns true if cars at y1 and y2 occupy the same lane
"""
function occupation_overlap(y1::Float64, y2::Float64)
    return abs(y1-y2) < 1.0 || ceil(y1) == floor(y2) || floor(y1) == ceil(y2)
end

"""
Return a Pair{Int} of lanes that the car will occupy at some point in the time step (both lanes could be the same)

Recall that a car can occupy at most two lanes on a single time step
"""
function occupation_lanes(y::Float64, lc::Float64)
    if !isinteger(y)
        return Pair{Int,Int}(floor(Int, y), ceil(Int, y))
    else # y is an integer
        return Pair{Int,Int}(y, y + sign(lc))
    end
end

"""
Return true if cars will occupy the same lane at some time in the time step
"""
function occupation_overlap(y1::Float64, lc1::Float64, y2::Float64, lc2::Float64)
    lanes1 = occupation_lanes(y1, lc1)
    lanes2 = occupation_lanes(y2, lc2)
    return lanes1[1] in lanes2 || lanes1[2] in lanes2
end


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>"consoles/coinbaseProConsole" | Coinbase Pro Trading Toolkit API Reference</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Coinbase Pro Trading Toolkit API Reference

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"consoles/coinbaseProConsole"

External module "consoles/coinbaseProConsole"

Index

Variables

coinbase<wbr>Pro<wbr>Api

Functions

has<wbr>Auth

log<wbr>Error

make<wbr>Generic<wbr>Request

required<wbr>Options

Object literals

auth

coinbase<wbr>Pro<wbr>Config

Variables

Const coinbase<wbr>Pro<wbr>Api

coinbase<wbr>Pro<wbr>Api: CoinbaseProExchangeAPI = new CoinbaseProExchangeAPI(coinbaseProConfig)

Defined in consoles/coinbaseProConsole.ts:61

Functions

has<wbr>Auth

has<wbr>Auth(): boolean

Defined in consoles/coinbaseProConsole.ts:72

Returns boolean

log<wbr>Error

log<wbr>Error(err: any): void

Defined in consoles/coinbaseProConsole.ts:80

Parameters

err: any

Returns void

make<wbr>Generic<wbr>Request

make<wbr>Generic<wbr>Request(method: string, url: string, body: string): Promise<any>

Defined in consoles/coinbaseProConsole.ts:100

Parameters

method: string

url: string

body: string

Returns Promise<any>

required<wbr>Options

required<wbr>Options(options: string[]): boolean

Defined in consoles/coinbaseProConsole.ts:89

Parameters

options: string[]

Returns boolean

Object literals

Const auth

auth: object

Defined in consoles/coinbaseProConsole.ts:47

key

key: any = process.env.COINBASE_PRO_KEY

Defined in consoles/coinbaseProConsole.ts:48

passphrase

passphrase: any = process.env.COINBASE_PRO_PASSPHRASE

Defined in consoles/coinbaseProConsole.ts:50

secret

secret: any = process.env.COINBASE_PRO_SECRET

Defined in consoles/coinbaseProConsole.ts:49

Const coinbase<wbr>Pro<wbr>Config

coinbase<wbr>Pro<wbr>Config: object

Defined in consoles/coinbaseProConsole.ts:52

api<wbr>Url

api<wbr>Url: any = program.api || process.env.API_URL || 'https://api.pro.coinbase.com'

Defined in consoles/coinbaseProConsole.ts:54

logger

logger: null = null

Defined in consoles/coinbaseProConsole.ts:53

						Globals

						"consoles/coinbase<wbr>Pro<wbr>Console"

						coinbase<wbr>Pro<wbr>Api

						has<wbr>Auth

						log<wbr>Error

						make<wbr>Generic<wbr>Request

						required<wbr>Options

						auth

						coinbase<wbr>Pro<wbr>Config

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System.Windows;
using System.Windows.Controls;
using Sce.Atf.Wpf.Applications;

namespace Sce.Atf.Wpf.Controls
{
    ///
    /// Helper class to select a template for ToolBarItems
    public class ToolBarItemTemplateSelector : DataTemplateSelector
    {
        ///
        /// Gets the static instance
        public static ToolBarItemTemplateSelector Instance
        {
            get { return s_instance ?? (s_instance = new ToolBarItemTemplateSelector()); }
        }

        ///
        /// Gets t
        /// <param name="item">The ICommandItem for this item</param>
        /// <param name="container">The element to get the template for</param>
        /// <returns>If there is a custom template for this type, it is returned. If no custom template is
        /// found but item is non-null, returns the standard ATF ToolBarItemTemplate. Otherwise, returns null.</returns>
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var element = container as FrameworkElement;
            if (element != null)
            {
                // Try and find a custom template for this type
                var dataTemplate = element.TryFindResource(element.GetType()) as DataTemplate;
                if (dataTemplate != null)
                    return dataTemplate;

                // If this fails then use the default ICommandItem template
                var commandItem = item as ICommandItem;
                if (commandItem != null)
                    return element.FindResource(Resources.ToolBarItemTemplateKey) as DataTemplate;
            }

            return null;
        }

        private static ToolBarItemTemplateSelector s_instance;
    }
}


text:
package com.accia77.mockey.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.widget.Toast;

import com.accia77.mockey.R;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;

public class SettingsActivity extends SherlockPreferenceActivity {
	private static final int PICK_IMAGE = 1;

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		// Listener for the item that lets the user select the background image(s)
		Preference selectAnimationFramesPref = findPreference("select_animation_frames");
		selectAnimationFramesPref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					public boolean onPreferenceClick(Preference preference) {
						Intent intent = new Intent(getApplicationContext(), PickBackgroundImagesActivity.class);
						startActivity(intent);

						return true;
					}
				});

		// Listener for the item that lets the user reset the background image(s)
		Preference resetBackgroundImgPref = findPreference("reset_animation_frames");
		resetBackgroundImgPref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					public boolean onPreferenceClick(Preference preference) {
						SharedPreferences spref = PreferenceManager
								.getDefaultSharedPreferences(SettingsActivity.this);
						Editor editor = spref.edit();
						editor.putString("backgroundImagePath", "");
						editor.commit();
						editor.putString("animationPhase0", "");
						editor.commit();
						editor.putString("animationPhase1", "");
						editor.commit();
						editor.putString("animationPhase2", "");
						editor.commit();

						String strAvviso = getResources().getString(
								R.string.reset_background_success);
						Toast.makeText(getApplicationContext(), strAvviso,
								Toast.LENGTH_LONG).show();
						return true;
					}
				});

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    // Respond to the action bar's Up/Home button
	    case android.R.id.home:
	        NavUtils.navigateUpFromSameTask(this);
	        return true;
	    }
	    return super.onOptionsItemSelected(item);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<feature
      id="org.eclipse.jst.common.fproj.enablement.jdt"
      label="%featureName"
      version="3.6.3.v201501141810"
      provider-name="%providerName"
      plugin="org.eclipse.jst.common.project.facet.core">

   <description>
      %description
   </description>

   <copyright>
      %copyright
   </copyright>

   <license url="%licenseURL">
      %license
   </license>

   <plugin
         id="org.eclipse.jst.common.project.facet.core"
         download-size="171"
         install-size="368"
         version="1.4.400.v201403261418"
         unpack="false"/>

   <plugin
         id="org.eclipse.jst.common.project.facet.ui"
         download-size="134"
         install-size="250"
         version="1.4.510.v201501141810"
         unpack="false"/>

</feature>