text:
namespace python = boost::python;

namespace RDKit {

python::object MolToBinary(const ROMol &self) {
  std::string res;
  {
    NOGIL gil;
    MolPickler::pickleMol(self, res);
  }
  python::object retval = python::object(
      python::handle<>(PyBytes_FromStringAndSize(res.c_str(), res.length())));
  return retval;
}

python::object MolToBinaryWithProps(const ROMol &self, unsigned int props) {
  std::string res;
  {
    NOGIL gil;
    MolPickler::pickleMol(self, res, props);
  }
  python::object retval = python::object(
      python::handle<>(PyBytes_FromStringAndSize(res.c_str(), res.length())));
  return retval;
}

//
// allows molecules to be pickled.
//  since molecules have a constructor that takes a binary string
//  we only need to provide getinitargs()
//
struct mol_pickle_suite : python::pickle_suite {
  static python::tuple getinitargs(const ROMol &self) {
    return python::make_tuple(MolToBinary(self));
  };
};

bool HasSubstructMatchStr(std::string pkl, const ROMol &query,
                          bool recursionPossible = true,
                          bool useChirality = false,
                          bool useQueryQueryMatches = false) {
  NOGIL gil;
  ROMol *mol;
  try {
    mol = new ROMol(pkl);
  } catch (...) {
    mol = NULL;
  }
  if (!mol) {
    throw ValueErrorException("Null Molecule");
  }
  MatchVectType res;
  bool hasM = SubstructMatch(*mol, query, res, recursionPossible, useChirality,
                             useQueryQueryMatches);
  delete mol;
  return hasM;
}

bool HasSubstructMatch(const ROMol &mol, const ROMol &query,
                       bool recursionPossible = true, bool useChirality = false,
                       bool useQueryQueryMatches = false) {
  NOGIL gil;
  MatchVectType res;
  return SubstructMatch(mol, query, res, recursionPossible, useChirality,
                        useQueryQueryMatches);
}

PyObject *convertMatches(MatchVectType &matches) {
  PyObject *res = PyTuple_New(matches.size());
  MatchVectType::const_iterator i;
  for (i = matches.begin(); i != matches.end(); i++) {
    PyTuple_SetItem(res, i->first, PyInt_FromLong(i->second));
  }
  return res;
}
PyObject *GetSubstructMatch(const ROMol &mol, const ROMol &query,
                            bool useChirality = false,
                            bool useQueryQueryMatches = false) {
  MatchVectType matches;
  {
    NOGIL gil;
    SubstructMatch(mol, query, matches, true, useChirality,
                   useQueryQueryMatches);
  }
  return convertMatches(matches);
}

PyObject *GetSubstructMatches(const ROMol &mol, const ROMol &query,
                              bool uniquify = true, bool useChirality = false,
                              bool useQueryQueryMatches = false,
                              unsigned int maxMatches = 1000) {
  std::vector<MatchVectType> matches;
  int matched;
  {
    NOGIL gil;
    matched = SubstructMatch(mol, query, matches, uniquify, true, useChirality,
                             useQueryQueryMatches, maxMatches);
  }
  PyObject *res = PyTuple_New(matched);
  for (int idx = 0; idx < matched; idx++) {
    PyTuple_SetItem(res, idx, convertMatches(matches[idx]));
  }
  return res;
}

unsigned int AddMolConformer(ROMol &mol, Conformer *conf,
                             bool assignId = false) {
  Conformer *nconf = new Conformer(*conf);
  return mol.addConformer(nconf, assignId);
}

Conformer *GetMolConformer(ROMol &mol, int id = -1) {
  return &(mol.getConformer(id));
}

PyObject *GetMolConformers(ROMol &mol) {
  PyObject *res = PyTuple_New(mol.getNumConformers());
  ROMol::ConformerIterator ci;
  unsigned int i = 0;
  for (ci = mol.beginConformers(); ci != mol.endConformers(); ci++) {
    PyTuple_SetItem(res, i, python::converter::shared_ptr_to_python(*ci));
    i++;
  }
  return res;
}

int MolHasProp(const ROMol &mol, const char *key) {
  int res = mol.hasProp(key);
  // std::cout << "key: "  << key << ": " << res << std::endl;
  return res;
}

template <class T>
void MolSetProp(const ROMol &mol, const char *key, const T &val,
                bool computed = false) {
  mol.setProp<T>(key, val, computed);
}

void MolClearProp(const ROMol &mol, const char *key) {
  if (!mol.hasProp(key)) {
    return;
  }
  mol.clearProp(key);
}

void MolClearComputedProps(const ROMol &mol) { mol.clearComputedProps(); }

void MolDebug(const ROMol &mol, bool useStdout) {
  if (useStdout) {
    mol.debugMol(std::cout);
  } else {
    std::ostream *dest = &std::cerr;
    if (rdInfoLog != NULL) {
      if (rdInfoLog->teestream) {
        dest = rdInfoLog->teestream;
      } else if (rdInfoLog->dp_dest) {
        dest = rdInfoLog->dp_dest;
      }
      mol.debugMol(*dest);
    }
  }
}

// FIX: we should eventually figure out how to do iterators properly
AtomIterSeq *MolGetAtoms(ROMol *mol) {
  AtomIterSeq *res = new AtomIterSeq(mol->beginAtoms(), mol->endAtoms(),
                                     AtomCountFunctor(*mol));
  return res;
}
QueryAtomIterSeq *MolGetAromaticAtoms(ROMol *mol) {
  QueryAtom *qa = new QueryAtom();
  qa->setQuery(makeAtomAromaticQuery());
  QueryAtomIterSeq *res = new QueryAtomIterSeq(
      mol->beginQueryAtoms(qa), mol->endQueryAtoms(), AtomCountFunctor(*mol));
  return res;
}
QueryAtomIterSeq *MolGetQueryAtoms(ROMol *mol, QueryAtom *qa) {
  QueryAtomIterSeq *res = new QueryAtomIterSeq(
      mol->beginQueryAtoms(qa), mol->endQueryAtoms(), AtomCountFunctor(*mol));
  return res;
}

// AtomIterSeq *MolGetHeteros(ROMol *mol){
//  AtomIterSeq *res = new AtomIterSeq(mol->beginHeteros(),
//                                     mol->endHeteros());
//  return res;
//}
BondIterSeq *MolGetBonds(ROMol *mol) {
  BondIterSeq *res = new BondIterSeq(mol->beginBonds(), mol->endBonds(),
                                     BondCountFunctor(*mol));
  return res;
}

int getMolNumAtoms(const ROMol &mol, int onlyHeavy, bool onlyExplicit) {
  if (onlyHeavy > -1) {
    BOOST_LOG(rdWarningLog)
        << "WARNING: the onlyHeavy argument to mol.GetNumAtoms() has been "
           "deprecated. Please use the onlyExplicit argument instead or "
           "mol.GetNumHeavyAtoms() if you want the heavy atom count."
        << std::endl;
    return mol.getNumAtoms(onlyHeavy);
  }
  return mol.getNumAtoms(onlyExplicit);
}

class ReadWriteMol : public RWMol {
 public:
  ReadWriteMol(){};
  ReadWriteMol(const ROMol &m, bool quickCopy = false, int confId = -1)
      : RWMol(m, quickCopy, confId){};

  void RemoveAtom(unsigned int idx) { removeAtom(idx); };
  void RemoveBond(unsigned int idx1, unsigned int idx2) {
    removeBond(idx1, idx2);
  };
  int AddBond(unsigned int begAtomIdx, unsigned int endAtomIdx,
              Bond::BondType order = Bond::UNSPECIFIED) {
    return addBond(begAtomIdx, endAtomIdx, order);
  };
  int AddAtom(Atom *atom) {
    PRECONDITION(atom, "bad atom");
    return addAtom(atom, true, false);
  };
  void ReplaceAtom(unsigned int idx, Atom *atom) { replaceAtom(idx, atom); };
  void ReplaceBond(unsigned int idx, Bond *bond) { replaceBond(idx, bond); };
  ROMol *GetMol() const {
    ROMol *res = new ROMol(*this);
    return res;
  }
};

std::string molClassDoc =
    "The Molecule class.\n\n\
  In addition to the expected Atoms and Bonds, molecules contain:\n\
    - a collection of Atom and Bond bookmarks indexed with integers\n\
        that can be used to flag and retrieve particular Atoms or Bonds\n\
        using the {get|set}{Atom|Bond}Bookmark() methods.\n\n\
    - a set of string-valued properties. These can have arbitrary string\n\
        labels and can be set and retrieved using the {set|get}Prop() methods\n\
        Molecular properties can be tagged as being *computed*, in which case\n\
          they will be automatically cleared under certain circumstances (when the\n\
          molecule itself is modified, for example).\n\
        Molecules also have the concept of *private* properties, which are tagged\n\
          by beginning the property name with an underscore (_).\n";
std::string rwmolClassDoc =
    "The RW molecule class (read/write)\n\n\
  This class is a more-performant version of the EditableMolecule class in that\n\
  it is a 'live' molecule and shares the interface from the Mol class.\n\
  All changes are performed without the need to create a copy of the\n\
  molecule using GetMol() (this is still available, however).\n\
  \n\
  n.b. Eventually this class may become a direct replacement for EditableMol";

struct mol_wrapper {
  static void wrap() {
    python::register_exception_translator<ConformerException>(
        &rdExceptionTranslator);

    python::enum_<RDKit::PicklerOps::PropertyPickleOptions>(
        "PropertyPickleOptions")
        .value("NoProps", RDKit::PicklerOps::NoProps)
        .value("MolProps", RDKit::PicklerOps::MolProps)
        .value("AtomProps", RDKit::PicklerOps::AtomProps)
        .value("BondProps", RDKit::PicklerOps::BondProps)
        .value("QueryAtomData", RDKit::PicklerOps::QueryAtomData)
        .value("PrivateProps", RDKit::PicklerOps::PrivateProps)
        .value("ComputedProps", RDKit::PicklerOps::ComputedProps)
        .value("AllProps", RDKit::PicklerOps::AllProps)
        .export_values();
    ;

    python::def("GetDefaultPickleProperties",
                MolPickler::getDefaultPickleProperties,
                "Get the current global mol pickler options.");
    python::def("SetDefaultPickleProperties",
                MolPickler::setDefaultPickleProperties,
                "Set the current global mol pickler options.");

    python::class_<ROMol, ROMOL_SPTR, boost::noncopyable>(
        "Mol", molClassDoc.c_str(),
        python::init<>("Constructor, takes no arguments"))
        .def(python::init<const std::string &>())
        .def(python::init<const ROMol &>())
        .def(python::init<const ROMol &, bool>())
        .def(python::init<const ROMol &, bool, int>())
        .def("__copy__", &generic__copy__<ROMol>)
        .def("__deepcopy__", &generic__deepcopy__<ROMol>)
        .def(
            "GetNumAtoms", getMolNumAtoms,
            (python::arg("onlyHeavy") = -1, python::arg("onlyExplicit") = true),
            "Returns the number of atoms in the molecule.\n\n"
            "  ARGUMENTS:\n"
            "    - onlyExplicit: (optional) include only explicit atoms "
            "(atoms in the molecular graph)\n"
            "                    defaults to 1.\n"
            "  NOTE: the onlyHeavy argument is deprecated\n"

            )
        .def("GetNumHeavyAtoms", &ROMol::getNumHeavyAtoms,
             "Returns the number of heavy atoms (atomic number >1) in the "
             "molecule.\n\n")
        .def("GetAtomWithIdx",
             (Atom * (ROMol::*)(unsigned int)) & ROMol::getAtomWithIdx,
             python::return_internal_reference<
                 1, python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a particular Atom.\n\n"
             "  ARGUMENTS:\n"
             "    - idx: which Atom to return\n\n"
             "  NOTE: atom indices start at 0\n")

        .def("GetNumBonds", &ROMol::getNumBonds,
             (python::arg("onlyHeavy") = true),
             "Returns the number of Bonds in the molecule.\n\n"
             "  ARGUMENTS:\n"
             "    - onlyHeavy: (optional) include only bonds to heavy atoms "
             "(not Hs)\n"
             "                  defaults to 1.\n")

        .def("GetBondWithIdx",
             (Bond * (ROMol::*)(unsigned int)) & ROMol::getBondWithIdx,
             python::return_internal_reference<
                 1, python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a particular Bond.\n\n"
             "  ARGUMENTS:\n"
             "    - idx: which Bond to return\n\n"
             "  NOTE: bond indices start at 0\n")

        .def("GetNumConformers", &ROMol::getNumConformers,
             "Return the number of conformations on the molecule")

        .def("AddConformer", AddMolConformer,
             (python::arg("self"), python::arg("conf"),
              python::arg("assignId") = false),
             "Add a conformer to the molecule and return the conformer ID")

#if 0
        .def("AddConformersFromTrajectory", &ROMol::addConformersFromTrajectory,
             (python::arg("self"), python::arg("traj"),
              python::arg("nConf") = -1),
             "Add conformers from a Trajectory to the molecule and return\n"
             "the number of conformations that were added")
#endif

        .def("GetConformer", GetMolConformer,
             (python::arg("self"), python::arg("id") = -1),
             "Get the conformer with a specified ID",
             python::return_internal_reference<
                 1, python::with_custodian_and_ward_postcall<0, 1> >())

        .def("GetConformers", GetMolConformers,
             "Get all the conformers as a tuple")

        .def("RemoveAllConformers", &ROMol::clearConformers,
             "Remove all the conformations on the molecule")

        .def("RemoveConformer", &ROMol::removeConformer,
             "Remove the conformer with the specified ID")
        .def("GetBondBetweenAtoms",
             (Bond * (ROMol::*)(unsigned int, unsigned int)) &
                 ROMol::getBondBetweenAtoms,
             python::return_internal_reference<
                 1, python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns the bond between two atoms, if there is one.\n\n"
             "  ARGUMENTS:\n"
             "    - idx1,idx2: the Atom indices\n\n"
             "  Returns:\n"
             "    The Bond between the two atoms, if such a bond exists.\n"
             "    If there is no Bond between the atoms, None is returned "
             "instead.\n\n"
             "  NOTE: bond indices start at 0\n")

        // substructures
        .def("HasSubstructMatch", HasSubstructMatch,
             (python::arg("self"), python::arg("query"),
              python::arg("recursionPossible") = true,
              python::arg("useChirality") = false,
              python::arg("useQueryQueryMatches") = false),
             "Queries whether or not the molecule contains a particular "
             "substructure.\n\n"
             "  ARGUMENTS:\n"
             "    - query: a Molecule\n\n"
             "    - recursionPossible: (optional)\n\n"
             "    - useChirality: enables the use of stereochemistry in the "
             "matching\n\n"
             "    - useQueryQueryMatches: use query-query matching logic\n\n"
             "  RETURNS: True or False\n")
        .def("GetSubstructMatch", GetSubstructMatch,
             (python::arg("self"), python::arg("query"),
              python::arg("useChirality") = false,
              python::arg("useQueryQueryMatches") = false),
             "Returns the indices of the molecule's atoms that match a "
             "substructure query.\n\n"
             "  ARGUMENTS:\n"
             "    - query: a Molecule\n\n"
             "    - useChirality: enables the use of stereochemistry in the "
             "matching\n\n"
             "    - useQueryQueryMatches: use query-query matching logic\n\n"
             "  RETURNS: a tuple of integers\n\n"
             "  NOTES:\n"
             "     - only a single match is returned\n"
             "     - the ordering of the indices corresponds to the atom "
             "ordering\n"
             "         in the query. For example, the first index is for the "
             "atom in\n"
             "         this molecule that matches the first atom in the "
             "query.\n")

        .def("GetSubstructMatches", GetSubstructMatches,
             (python::arg("self"), python::arg("query"),
              python::arg("uniquify") = true,
              python::arg("useChirality") = false,
              python::arg("useQueryQueryMatches") = false,
              python::arg("maxMatches") = 1000),
             "Returns tuples of the indices of the molecule's atoms that "
             "match "
             "a substructure query.\n\n"
             "  ARGUMENTS:\n"
             "    - query: a Molecule.\n"
             "    - uniquify: (optional) determines whether or not the "
             "matches "
             "are uniquified.\n"
             "                Defaults to 1.\n\n"
             "    - useChirality: enables the use of stereochemistry in the "
             "matching\n\n"
             "    - useQueryQueryMatches: use query-query matching logic\n\n"
             "    - maxMatches: The maximum number of matches that will be "
             "returned.\n"
             "                  In high-symmetry cases with medium-sized "
             "molecules, it is\n"
             "                  very easy to end up with a combinatorial "
             "explosion in the\n"
             "                  number of possible matches. This argument "
             "prevents that from\n"
             "                  having unintended consequences\n\n"
             "  RETURNS: a tuple of tuples of integers\n\n"
             "  NOTE:\n"
             "     - the ordering of the indices corresponds to the atom "
             "ordering\n"
             "         in the query. For example, the first index is for the "
             "atom in\n"
             "         this molecule that matches the first atom in the "
             "query.\n")

        // properties
        .def("SetProp", MolSetProp<std::string>,
             (python::arg("self"), python::arg("key"), python::arg("val"),
              python::arg("computed") = false),
             "Sets a molecular property\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to be set (a string).\n"
             "    - value: the property value (a string).\n"
             "    - computed: (optional) marks the property as being "
             "computed.\n"
             "                Defaults to False.\n\n")
        .def("SetDoubleProp", MolSetProp<double>,
             (python::arg("self"), python::arg("key"), python::arg("val"),
              python::arg("computed") = false),
             "Sets a double valued molecular property\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to be set (a string).\n"
             "    - value: the property value as a double.\n"
             "    - computed: (optional) marks the property as being "
             "computed.\n"
             "                Defaults to 0.\n\n")
        .def("SetIntProp", MolSetProp<int>,
             (python::arg("self"), python::arg("key"), python::arg("val"),
              python::arg("computed") = false),
             "Sets an integer valued molecular property\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to be set (an unsigned "
             "number).\n"
             "    - value: the property value as an integer.\n"
             "    - computed: (optional) marks the property as being "
             "computed.\n"
             "                Defaults to False.\n\n")
        .def("SetUnsignedProp", MolSetProp<unsigned int>,
             (python::arg("self"), python::arg("key"), python::arg("val"),
              python::arg("computed") = false),
             "Sets an unsigned integer valued molecular property\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to be set (a string).\n"
             "    - value: the property value as an unsigned integer.\n"
             "    - computed: (optional) marks the property as being "
             "computed.\n"
             "                Defaults to False.\n\n")
        .def("SetBoolProp", MolSetProp<bool>,
             (python::arg("self"), python::arg("key"), python::arg("val"),
              python::arg("computed") = false),
             "Sets a boolean valued molecular property\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to be set (a string).\n"
             "    - value: the property value as a bool.\n"
             "    - computed: (optional) marks the property as being "
             "computed.\n"
             "                Defaults to False.\n\n")
        .def("HasProp", MolHasProp,
             "Queries a molecule to see if a particular property has been "
             "assigned.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to check for (a string).\n")
        .def("GetProp", GetProp<ROMol, std::string>,
             "Returns the value of the property.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to return (a string).\n\n"
             "  RETURNS: a string\n\n"
             "  NOTE:\n"
             "    - If the property has not been set, a KeyError exception "
             "will be raised.\n")
        .def("GetDoubleProp", GetProp<ROMol, double>,
             "Returns the double value of the property if possible.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to return (a string).\n\n"
             "  RETURNS: a double\n\n"
             "  NOTE:\n"
             "    - If the property has not been set, a KeyError exception "
             "will be raised.\n")
        .def("GetIntProp", GetProp<ROMol, int>,
             "Returns the integer value of the property if possible.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to return (a string).\n\n"
             "  RETURNS: an integer\n\n"
             "  NOTE:\n"
             "    - If the property has not been set, a KeyError exception "
             "will be raised.\n")
        .def("GetUnsignedProp", GetProp<ROMol, unsigned int>,
             "Returns the unsigned int value of the property if possible.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to return (a string).\n\n"
             "  RETURNS: an unsigned integer\n\n"
             "  NOTE:\n"
             "    - If the property has not been set, a KeyError exception "
             "will be raised.\n")
        .def("GetBoolProp", GetProp<ROMol, bool>,
             "Returns the double value of the property if possible.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to return (a string).\n\n"
             "  RETURNS: a bool\n\n"
             "  NOTE:\n"
             "    - If the property has not been set, a KeyError exception "
             "will be raised.\n")
        .def("ClearProp", MolClearProp,
             "Removes a property from the molecule.\n\n"
             "  ARGUMENTS:\n"
             "    - key: the name of the property to clear (a string).\n")

        .def("ClearComputedProps", MolClearComputedProps,
             "Removes all computed properties from the molecule.\n\n")

        .def("UpdatePropertyCache", &ROMol::updatePropertyCache,
             (python::arg("self"), python::arg("strict") = true),
             "Regenerates computed properties like implicit valence and ring "
             "information.\n\n")

        .def("NeedsUpdatePropertyCache", &ROMol::needsUpdatePropertyCache,
             (python::arg("self")),
             "Returns true or false depending on whether implicit and "
             "explicit "
             "valence of the molecule have already been calculated.\n\n")

        .def("GetPropNames", &ROMol::getPropList,
             (python::arg("self"), python::arg("includePrivate") = false,
              python::arg("includeComputed") = false),
             "Returns a tuple with all property names for this molecule.\n\n"
             "  ARGUMENTS:\n"
             "    - includePrivate: (optional) toggles inclusion of private "
             "properties in the result set.\n"
             "                      Defaults to 0.\n"
             "    - includeComputed: (optional) toggles inclusion of computed "
             "properties in the result set.\n"
             "                      Defaults to 0.\n\n"
             "  RETURNS: a tuple of strings\n")

        .def("GetPropsAsDict", GetPropsAsDict<ROMol>,
             (python::arg("self"), python::arg("includePrivate") = false,
              python::arg("includeComputed") = false),
             "Returns a dictionary populated with the molecules properties.\n"
             " n.b. Some properties are not able to be converted to python "
             "types.\n\n"
             "  ARGUMENTS:\n"
             "    - includePrivate: (optional) toggles inclusion of private "
             "properties in the result set.\n"
             "                      Defaults to False.\n"
             "    - includeComputed: (optional) toggles inclusion of computed "
             "properties in the result set.\n"
             "                      Defaults to False.\n\n"
             "  RETURNS: a dictionary\n")

        .def("GetAtoms", MolGetAtoms,
             python::return_value_policy<
                 python::manage_new_object,
                 python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a read-only sequence containing all of the molecule's "
             "Atoms.\n")
        .def("GetAromaticAtoms", MolGetAromaticAtoms,
             python::return_value_policy<
                 python::manage_new_object,
                 python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a read-only sequence containing all of the molecule's "
             "aromatic Atoms.\n")
        .def("GetAtomsMatchingQuery", MolGetQueryAtoms,
             python::return_value_policy<
                 python::manage_new_object,
                 python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a read-only sequence containing all of the atoms in a "
             "molecule that match the query atom.\n")

        .def("GetBonds", MolGetBonds,
             python::return_value_policy<
                 python::manage_new_object,
                 python::with_custodian_and_ward_postcall<0, 1> >(),
             "Returns a read-only sequence containing all of the molecule's "
             "Bonds.\n")

        // enable pickle support
        .def_pickle(mol_pickle_suite())

        .def("Debug", MolDebug,
             (python::arg("mol"), python::arg("useStdout") = true),
             "Prints debugging information about the molecule.\n")

        .def("ToBinary", MolToBinary,
             "Returns a binary string representation of the molecule.\n")
        .def("ToBinary", MolToBinaryWithProps,
             (python::arg("mol"), python::arg("propertyFlags")),
             "Returns a binary string representation of the molecule pickling "
             "the "
             "specified properties.\n")

        .def("GetRingInfo", &ROMol::getRingInfo,
             python::return_value_policy<python::reference_existing_object>(),
             "Returns the number of molecule's RingInfo object.\n\n");

    // ---------------------------------------------------------------------------------------------
    python::def("_HasSubstructMatchStr", HasSubstructMatchStr,
                (python::arg("pkl"), python::arg("query"),
                 python::arg("recursionPossible") = true,
                 python::arg("useChirality") = false,
                 python::arg("useQueryQueryMatches") = false),
                "This function is included to speed substructure queries from "
                "databases, \n"
                "it's probably not of\n"
                "general interest.\n\n"
                "  ARGUMENTS:\n"
                "    - pkl: a Molecule pickle\n\n"
                "    - query: a Molecule\n\n"
                "    - recursionPossible: (optional)\n\n"
                "    - useChirality: (optional)\n\n"
                "    - useQueryQueryMatches: use query-query matching logic\n\n"
                "  RETURNS: True or False\n");

    python::class_<ReadWriteMol, python::bases<ROMol> >(
        "RWMol", rwmolClassDoc.c_str(),
        python::init<const ROMol &>("Construct from a Mol"))
        .def(python::init<>())
        .def(python::init<const ROMol &, bool>())
        .def(python::init<const ROMol &, bool, int>())
        .def("__copy__", &generic__copy__<ReadWriteMol>)
        .def("__deepcopy__", &generic__deepcopy__<ReadWriteMol>)
        .def("RemoveAtom", &ReadWriteMol::RemoveAtom,
             "Remove the specified atom from the molecule")
        .def("RemoveBond", &ReadWriteMol::RemoveBond,
             "Remove the specified bond from the molecule")

        .def("AddBond", &ReadWriteMol::AddBond,
             (python::arg("mol"), python::arg("beginAtomIdx"),
              python::arg("endAtomIdx"),
              python::arg("order") = Bond::UNSPECIFIED),
             "add a bond, returns the new number of bonds")

        .def("AddAtom", &ReadWriteMol::AddAtom,
             (python::arg("mol"), python::arg("atom")),
             "add an atom, returns the index of the newly added atom")
        .def("ReplaceAtom", &ReadWriteMol::ReplaceAtom,
             (python::arg("mol"), python::arg("index"), python::arg("newAtom")),
             "replaces the specified atom with the provided one")
        .def("ReplaceBond", &ReadWriteMol::ReplaceBond,
             (python::arg("mol"), python::arg("index"), python::arg("newBond")),
             "replaces the specified bond with the provided one")
        .def("GetMol", &ReadWriteMol::GetMol,
             "Returns a Mol (a normal molecule)",
             python::return_value_policy<python::manage_new_object>());
  };
};
}  // end of namespace
void wrap_mol() { RDKit::mol_wrapper::wrap(); }


text:
import * as React from "react";
import Error from "next/error";

interface WithFooProps {
    foo: string;
}

const result = <Error statusCode={404} />;

class MyError extends Error<WithFooProps> {
    static getInitialProps() {
        return { statusCode: 404, foo: 'bar'};
    }

    render() {
        const { statusCode, foo } = this.props;
        return <div>{statusCode} {foo}</div>;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* eslint no-unused-vars: 0 */ // unused arguments to demonstrate what args are available

module.exports.init = function (bot) {};

module.exports.name = 'sirc-test';

module.exports.command = 'test';

const testOutputs = [
  'Hello and, again, welcome to the Aperture Science computer-aided enrichment center.',
  'Do not submerge the IRC Network in liquid',
  'Do not stare directly into the IRC Network',
  'This test is impossible; make no attempt to solve it',
  "Don't worry, you passed <3",
  'Is this a test?',
  'Do you think this is a test? Well, do you?',
  'If quizzes are quizical, what are tests?',
  'Test, test, is this thing on?',
  'test (n): a cricial examination, observation, or evaluation.',
  "Yup, I'm still here.",
  'Question 1: If an electron has a mass, does that mean it is Catholic?',
  'toast',
  'test(1) check file types and compare values',
];

module.exports.commands = ['test2', 'test3', /(t+)test/];
module.exports.run = function (remainder, parts, reply, command, from, to, text, raw, regex) {
  if (typeof regex === 'undefined') {
    reply(testOutputs[Math.floor(Math.random() * testOutputs.length)]);
  } else {
    reply('One of my test regex commands was called!', 'In fact it was', regex, 'which matched', command);
  }
};

module.exports.runTest4 = function (r, p, reply) {
  reply('I was called with test4');
};
module.exports.runTest5 = function (r, p, reply) {
  reply('My parts are:', p.join(', '));
};
module.exports.run_test6 = function (r, p, reply) {
  reply(`My name is ${this.name}`);
};

module.exports.run_testspam = function (r, p, reply) {
  reply('foo\nbar\nbaz');
};

module.exports.run_testscrollback = function (r, p, reply, command, from, to) {
  const scrollbackModule = this.modules['sirc-scrollback'];

  scrollbackModule.getFormattedScrollbackLinesFromRanges(to, r, (err, res) => {
    reply(err, JSON.stringify(res));
  });
};


text:
'use strict';

describe('Service: tree', function () {

  // load the service's module
  beforeEach(module('angoApp'));

  // instantiate service
  var tree;
  beforeEach(inject(function (_tree_) {
    tree = _tree_;
  }));

  it('should do something', function () {
    expect(!!tree).toBe(true);
  });

});


text:
/**
 * Network and AJAX helpers.
 * @static
 * @class schnipp.net
 * @module schnipp.net
 **/
schnipp.net = {}

/**
 * Sends a GET request.
 *
 * @param {string} url The request URL
 * @param {string} data The post data
 * @param {Function} Callback to be executed on success
 * @param {string} type The type of data expected from the server. Per Default, type is an intelligent guess (--> jQuery)
 * @method get
 **/
schnipp.net.get = function (url, data, callback, type) {
    // shift arguments if data argument was omitted
    if ($.isFunction(data)) {
        type = type || callback
        callback = data
        data = {}
    }
    schnipp.spinner.show()

    return $.get(
        url,
        data,
        function(data, textStatus, jqXHR) {
            callback(data, textStatus, jqXHR)
            schnipp.spinner.hide()
        },
        type
    ).error(schnipp.net.error_handler)
}

/**
 * Sends a post request.
 *
 * @param {string} url The request URL
 * @param {string} data The post data
 * @param {Function} Callback to be executed on success
 * @param {string} type The type of data expected from the server. Per Default, type is an intelligent guess (--> jQuery)
 * @method post
 **/
schnipp.net.post = function (url, data, callback, type) {
    // shift arguments if data argument was omitted
    if ($.isFunction(data)) {
        type = type || callback
        callback = data
        data = {}
    }
    schnipp.spinner.show()
    return $.post(
        url,
        data,
        function(data, textStatus, jqXHR) {
            callback(data, textStatus, jqXHR)
            schnipp.spinner.hide()
        },
        type
    ).error(schnipp.net.error_handler)
}

/**
 * AJAX error handler.
 *
 * @param {object} jqXHR The jQuery XHR object
 * @param {string} textStatus The http error status
 * @param {string} errorThrown The text portion of the http error status
 * @method error_handler
 **/
schnipp.net.error_handler = function(jqXHR, textStatus, errorThrown) {
    alert('Sorry, a network error has occured!\n You may have to reload the page.')
}

schnipp.net._iframe_seq = 1;

/**
 * Sends the form data in a invinsible Iframe for file-uploads.
 *
 * @param {dom node} form The jQuery form node
 * @param {function} on_success The success callback
 * @param {function} on_error The error callback
 **/
schnipp.net._iframe_post = function(form, on_success, on_error) {
    remoter_id = 'schnipp_remoter' + (schnipp.net._iframe_seq++);
    var iframe = schnipp.net._create_iframe(remoter_id)
    form.attr('target', remoter_id)

    iframe.unbind('load')
    iframe.load(function() {
        var a = $(iframe.contents().children()[0]) //Whats going on here?
        on_success(a.html())
        schnipp.net._unregister_iframe(iframe)
        schnipp.net._trigger_form_success_events(form)
        schnipp.spinner.hide()
    })
}

/**
 * Iframe garbage collector - removes the iframe from the DOM
 * @param {dom node} iframe The iframe as jQuery dom node
 **/
schnipp.net._unregister_iframe = function(iframe) {
    //wait a little
    setTimeout(function() {
        iframe.remove()
    }, 300)
}

/**
 * Creates an invisible iframe with id iid and name iname and adds it to the DOM
 *  - if iname is not given iid will be used for name also
 * @param {string} iid The unique iframe id
 * @param {string} iname The iframe name
 **/
schnipp.net._create_iframe = function(iid, iname) {
    if (iname == undefined)
        iname = iid
    var iframe
    try {
        // IE HACK
        iframe = $.create('',{})
    } catch (ex) {
        iframe = $('')
    }
    iframe.appendTo(document.body)
    return iframe
}


text:
import * as React from 'react'
import * as Scrivito from 'scrivito'
import isEmpty from 'is-empty'
import { isPlainObject } from 'lodash-es'
import dataFromAuthor from './SchemaDotOrg/dataFromAuthor'
import dataFromEvent from './SchemaDotOrg/dataFromEvent'
import dataFromJob from './SchemaDotOrg/dataFromJob'
import dataFromBlog from './SchemaDotOrg/dataFromBlog'
import dataFromBlogPost from './SchemaDotOrg/dataFromBlogPost'
import dataFromAddressWidget from './SchemaDotOrg/dataFromAddressWidget'

const SchemaDotOrg = Scrivito.connect(({ content }) => {
  const data = pruneEmptyValues(dataFromItem(content))

  return <script type='application/ld+json'>{JSON.stringify(data)}</script>
})

function dataFromItem (item) {
  switch (item.objClass()) {
    case 'AddressWidget':
      return dataFromAddressWidget(item)
    case 'Author':
      return dataFromAuthor(item)
    case 'Blog':
      return dataFromBlog(item)
    case 'BlogPost':
      return dataFromBlogPost(item)
    case 'Event':
      return dataFromEvent(item)
    case 'Job':
      return dataFromJob(item)
    default:
      throw new Error(
        `SchemaDotOrg for objClass ${item.objClass()} not supported!`
      )
  }
}

function pruneEmptyValues (data) {
  let prunedData = mapValues(data, subData => {
    if (isPlainObject(subData)) {
      return pruneEmptyValues(subData)
    }
    return subData
  })

  prunedData = pickBy(prunedData, v => !isEmpty(v))

  const keysWithoutAt = Object.keys(prunedData).filter(
    sd => !sd.startsWith('@')
  )
  if (keysWithoutAt.length) {
    return prunedData
  }
  return {}
}

function arrayToObject (array) {
  return Object.assign(...array.map(([key, value]) => ({ [key]: value })))
}

function mapValues (data, fn) {
  return arrayToObject(
    Object.entries(data).map(([key, value]) => [key, fn(value)])
  )
}

function pickBy (data, fn) {
  return arrayToObject(
    Object.entries(data).filter(([_key, value]) => fn(value))
  )
}

export default SchemaDotOrg


text:
package org.apache.velocity.runtime.parser.node;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.parser.Parser;

/**
 *
 */
public class ASTNotNode extends SimpleNode
{
    /**
     * @param id
     */
    public ASTNotNode(int id)
    {
        super(id);
    }

    /**
     * @param p
     * @param id
     */
    public ASTNotNode(Parser p, int id)
    {
        super(p, id);
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.SimpleNode#jjtAccept(org.apache.velocity.runtime.parser.node.ParserVisitor, java.lang.Object)
     */
    @Override
    public Object jjtAccept(ParserVisitor visitor, Object data)
    {
        return visitor.visit(this, data);
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.SimpleNode#evaluate(org.apache.velocity.context.InternalContextAdapter)
     */
    @Override
    public boolean evaluate(InternalContextAdapter context)
        throws MethodInvocationException
    {
        return !jjtGetChild(0).evaluate(context);
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.SimpleNode#value(org.apache.velocity.context.InternalContextAdapter)
     */
    @Override
    public Object value(InternalContextAdapter context)
        throws MethodInvocationException
    {
        return (jjtGetChild(0).evaluate( context ) ? Boolean.FALSE : Boolean.TRUE) ;
    }

    /**
     * @throws TemplateInitException
     * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
     */
    @Override
    public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
    {
    	Object obj = super.init(context, data);
    	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
    	return obj;
    }

    @Override
    public String literal()
    {
        return "!" + jjtGetChild(0).literal();
    }
}


text:
                <ng-content select="nb-dialog-header"></ng-content>

            <ng-content select="nb-dialog-body"></ng-content>

                <ng-content select="nb-dialog-footer"></ng-content>

            <ng-container *ngIf="ref.children.length == 0">
                <button nb-button class="nb-dialog-footer-control-button" (click)="confirm()">确定</button>
                <button nb-button class="nb-dialog-footer-control-button" (click)="hide()" theme="default">取消</button>
            </ng-container>


text:
/* Loop with surrounding parentheses. */

package main

func main() {
	for (i := 0 ; i < 2 ; i++) { // Error: Can't have parentheses.
		// Do nothing.
	}
}


text:
using namespace blink;
#if defined(OS_WIN)
#define _USE_MATH_DEFINES
#include <math.h>
#endif

//#undef FROM_HERE
#if 0
#undef TRACE_EVENT0
#undef TRACE_EVENT1
#undef TRACE_EVENT2
#undef TRACE_EVENT_WITH_FLOW0
#undef TRACE_EVENT_WITH_FLOW1
#undef TRACE_EVENT_WITH_FLOW2
#undef TRACE_EVENT_MARK_WITH_TIMESTAMP1
#undef TRACE_EVENT_COPY_MARK_WITH_TIMESTAMP
#undef TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0
#undef TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0
#undef TRACE_EVENT_ENTER_CONTEXT
#undef TRACE_EVENT_LEAVE_CONTEXT
#undef TRACE_STR_COPY
#undef TRACE_ID_MANGLE
#undef TRACE_ID_DONT_MANGLE
#undef TRACE_ID_WITH_SCOPE
#undef TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET
#undef TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET
#undef TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET
//#undef TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED
#undef TRACE_EVENT_API_ADD_TRACE_EVENT
#undef TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION
#undef INTERNAL_TRACE_EVENT_UID2
//#undef INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO
#undef INTERNAL_TRACE_EVENT_ADD
#undef INTERNAL_TRACE_EVENT_ADD_SCOPED
#undef INTERNAL_TRACE_EVENT_ADD_SCOPED_WITH_FLOW
#undef INTERNAL_TRACE_EVENT_ADD_WITH_ID
#undef INTERNAL_TRACE_EVENT_ADD_WITH_TIMESTAMP
#undef INTERNAL_TRACE_EVENT_SCOPED_CONTEXT
//#undef INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE
#endif
//#undef LOCKS_EXCLUDED
//#undef LOCK_RETURNED
//#undef EXCLUSIVE_LOCK_FUNCTION
//#undef SHARED_LOCK_FUNCTION
//#undef UNLOCK_FUNCTION
//#undef EXCLUSIVE_TRYLOCK_FUNCTION
//#undef SHARED_TRYLOCK_FUNCTION
//#undef NO_THREAD_SAFETY_ANALYSIS

//#include "third_party/WebKit/Source/config.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_local_frame.h"

#undef BLINK_IMPLEMENTATION
#define BLINK_IMPLEMENTATION 1
#pragma clang diagnostic ignored "-Wimplicit-const-int-float-conversion"
#include "base/thread_annotations.h"

#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"

#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/renderer/core/script/modulator.h"
#include "third_party/blink/renderer/core/script/js_module_script.h"
#include "third_party/blink/renderer/core/script/module_record_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"

//#include "third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h"
//#include "third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h"

//#undef CHECK
#include "v8_html_iframe_element.h"
#include "extensions/renderer/script_context_set.h"

namespace content {
#if defined(COMPONENT_BUILD) && defined(WIN32)
CONTENT_EXPORT base::FilePath g_nw_temp_dir, g_nw_old_cwd;
#else
extern base::FilePath g_nw_temp_dir, g_nw_old_cwd;
#endif
}

using blink::WebFrame;

namespace extensions {

namespace {
bool MakePathAbsolute(base::FilePath* file_path) {
  DCHECK(file_path);

  base::FilePath current_directory;
  if (!base::GetCurrentDirectory(&current_directory))
    return false;

  if (file_path->IsAbsolute())
    return true;

  if (current_directory.empty()) {
    *file_path = base::MakeAbsoluteFilePath(*file_path);
    return true;
  }

  if (!current_directory.IsAbsolute())
    return false;

#ifdef OS_LINUX
  //linux might gives "/" as current_directory, return false
  if (current_directory.value().length() <= 1)
	return false;
#endif

  *file_path = current_directory.Append(*file_path);
  return true;
}

} // namespace

void NWCustomBindings::AddRoutes() {
  RouteHandlerFunction("crashRenderer",
                base::BindRepeating(&NWCustomBindings::CrashRenderer,
                           base::Unretained(this)));
  RouteHandlerFunction("getOldCwd",
                base::BindRepeating(&NWCustomBindings::GetOldCwd,
                           base::Unretained(this)));
  RouteHandlerFunction("evalScript",
                base::BindRepeating(&NWCustomBindings::EvalScript,
                           base::Unretained(this)));
  RouteHandlerFunction("evalNWBin",
                base::BindRepeating(&NWCustomBindings::EvalNWBin,
                           base::Unretained(this)));
  RouteHandlerFunction("getAbsolutePath",
                base::BindRepeating(&NWCustomBindings::GetAbsolutePath,
                           base::Unretained(this)));
  RouteHandlerFunction("addOriginAccessWhitelistEntry",
                base::BindRepeating(&NWCustomBindings::AddOriginAccessWhitelistEntry,
                           base::Unretained(this)));
  RouteHandlerFunction("removeOriginAccessWhitelistEntry",
                base::BindRepeating(&NWCustomBindings::RemoveOriginAccessWhitelistEntry,
                           base::Unretained(this)));
  RouteHandlerFunction("getProxyForURL",
                base::BindRepeating(&NWCustomBindings::GetProxyForURL,
                           base::Unretained(this)));
  RouteHandlerFunction("setDevToolsJail",
                base::BindRepeating(&NWCustomBindings::SetDevToolsJail,
                           base::Unretained(this)));
  RouteHandlerFunction("getWidgetRoutingID",
                base::BindRepeating(&NWCustomBindings::GetWidgetRoutingID,
                           base::Unretained(this)));
  RouteHandlerFunction("getRoutingID",
                base::BindRepeating(&NWCustomBindings::GetRoutingID,
                           base::Unretained(this)));
  RouteHandlerFunction("callInWindow",
                base::BindRepeating(&NWCustomBindings::CallInWindow,
                           base::Unretained(this)));
}

NWCustomBindings::NWCustomBindings(ScriptContext* context)
    : ObjectBackedNativeHandler(context) {
}

void NWCustomBindings::CallInWindow(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Local<v8::Context> target_context = v8::Local<v8::Object>::Cast(args[0])->GetCreationContextChecked();
  v8::Local<v8::String> method   = v8::Local<v8::String>::Cast(args[1]);
  ScriptContext* context = ScriptContextSet::GetContextByV8Context(target_context);
  v8::Context::Scope cscope(target_context);
  v8::MaybeLocal<v8::Value> val = v8::Local<v8::Object>::Cast(args[0])->Get(target_context, method);
  v8::Local<v8::Function> func = val.ToLocalChecked().As<v8::Function>();
  v8::Local<v8::Value>* argv = new v8::Local<v8::Value>[args.Length() - 2];
  for (int i = 0; i < args.Length() - 2; i++)
    argv[i] = args[i + 2];
  context->SafeCallFunction(func, args.Length() - 2, argv);
  delete[] argv;
}

void NWCustomBindings::GetRoutingID(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  int routing_id = context()->GetRenderFrame()->GetMainRenderFrame()->GetRoutingID();
  args.GetReturnValue().Set(v8::Integer::New(GetIsolate(), routing_id));
}

void NWCustomBindings::GetWidgetRoutingID(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  int routing_id = context()->GetRenderFrame()->GetMainRenderFrame()->GetRoutingID();
  args.GetReturnValue().Set(v8::Integer::New(GetIsolate(), routing_id));
}

void NWCustomBindings::CrashRenderer(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  //LOG(ERROR) << "crashing renderer";
  int* ptr = nullptr;
  *ptr = 1;
}

void NWCustomBindings::EvalScript(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  content::RenderFrame* render_frame = context()->GetRenderFrame();
  if (!render_frame)
    return;
  v8::Isolate* isolate = args.GetIsolate();
  WebFrame* main_frame = render_frame->GetWebFrame();
  if (args.Length() > 2) {
    int frame_id = args[2].As<v8::Int32>()->Value();
    content::RenderFrame* frame =
      content::RenderFrame::FromRoutingID(frame_id);
    if (frame && frame->GetWebFrame())
      main_frame = frame->GetWebFrame();
    else {
      args.GetReturnValue().Set(isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate,
           "Invalid frame id. Window could be in remote process", v8::NewStringType::kNormal).ToLocalChecked())));
      return;
    }
  }
  v8::Handle<v8::Value> result;
  WebFrame* web_frame = NULL;
  if (args[0]->IsNull()) {
    web_frame = main_frame;
  }else{
    v8::Handle<v8::Object> frm = v8::Handle<v8::Object>::Cast(args[0]);
    blink::HTMLIFrameElement* iframe = blink::V8HTMLIFrameElement::ToImpl(frm);
    web_frame = blink::WebFrame::FromCoreFrame(iframe->ContentFrame());
  }
#if defined(OS_WIN)
  std::u16string jscript(base::WideToUTF16((WCHAR*)*v8::String::Value(isolate, args[1])));
#else
  std::u16string jscript((char16_t*)*v8::String::Value(isolate, args[1]));
#endif
  if (web_frame) {
    blink::WebLocalFrame* local_frame = web_frame->ToWebLocalFrame();
    result = local_frame->ExecuteScriptAndReturnValue(blink::WebScriptSource(blink::WebString::FromUTF16(jscript)));
  }
  args.GetReturnValue().Set(result);
  return;
}

void NWCustomBindings::EvalNWBin(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  content::RenderFrame* render_frame = context()->GetRenderFrame();
  if (!render_frame)
    return;

  if (!args[1]->IsArrayBuffer()) {
    return;
  }

  v8::Local<v8::ArrayBuffer> ab = args[1].As<v8::ArrayBuffer>();
  int64_t length = ab->GetBackingStore()->ByteLength();
  uint8_t *data = reinterpret_cast<uint8_t*>(ab->GetBackingStore()->Data());

  WebFrame* main_frame = render_frame->GetWebFrame();
  if (args.Length() > 3) {
    int frame_id = args[3].As<v8::Int32>()->Value();
    content::RenderFrame* frame =
      content::RenderFrame::FromRoutingID(frame_id);
    if (frame && frame->GetWebFrame())
      main_frame = frame->GetWebFrame();
    else {
      args.GetReturnValue().Set(isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate,
           "Invalid frame id. Window could be in remote process", v8::NewStringType::kNormal).ToLocalChecked())));
      return;
    }
  }
  v8::Handle<v8::String> source_string = v8::String::NewFromUtf8(isolate, "", v8::NewStringType::kNormal).ToLocalChecked();
  v8::ScriptCompiler::CachedData* cache;
  cache = new v8::ScriptCompiler::CachedData(
                                             data, length, v8::ScriptCompiler::CachedData::BufferNotOwned);

  WebFrame* web_frame = NULL;
  if (args[0]->IsNull()) {
    web_frame = main_frame;
  }else{
    v8::Handle<v8::Object> frm = v8::Handle<v8::Object>::Cast(args[0]);
    blink::HTMLIFrameElement* iframe = blink::V8HTMLIFrameElement::ToImpl(frm);
    web_frame = blink::WebFrame::FromCoreFrame(iframe->ContentFrame());
  }
  blink::WebLocalFrame* local_frame = web_frame->ToWebLocalFrame();
  if (args.Length() == 2 || args[2]->IsNull()) {
    v8::Local<v8::UnboundScript> script;
    v8::ScriptCompiler::Source source(source_string, cache);
    script = v8::ScriptCompiler::CompileUnboundScript(
                                                      isolate, &source, v8::ScriptCompiler::kConsumeCodeCache).ToLocalChecked();
    CHECK(!cache->rejected);
    v8::Local<v8::Value> result;
    v8::Context::Scope cscope (local_frame->MainWorldScriptContext());
    v8::FixSourceNWBin(isolate, script);
    std::ignore = script->BindToCurrentContext()->Run(local_frame->MainWorldScriptContext()).ToLocal(&result);
    args.GetReturnValue().Set(result);
  } else {
    v8::ScriptOrigin origin(isolate,
                            args[2].As<v8::String>(),
                            0, 0,
                            true,
                            -1,    // script id
                            v8::Local<v8::Value>(),  // source_map_url
                            true,
                            false,  // is_wasm
                            true);
    v8::Local<v8::Module> module;
    v8::ScriptCompiler::Source source(source_string, origin, cache);
    module = v8::ScriptCompiler::CompileModuleWithCache(isolate, &source).ToLocalChecked();
                                                                                //fix
                                                                                //v8
                                                                                //here
    v8::FixSourceNWBin(isolate, module);
    blink::Modulator* modulator = blink::Modulator::From(ToScriptStateForMainWorld(static_cast<blink::WebLocalFrameImpl*>(local_frame)->GetFrame()));
    GURL url = render_frame->GetWebFrame()->GetDocument().Url();
    v8::String::Utf8Value file(args.GetIsolate(), args[2]);
    url = url.Resolve(*file);
    // LOG(WARNING) << "registering module as: " << url;
    KURL kurl(WTF::String(url.spec().c_str()));
    //blink::ModuleRecord script_module(isolate, module, kurl);
    blink::JSModuleScript* module_script =
      blink::JSModuleScript::CreateForTest(modulator, module, kurl);
    modulator->AddToMap(kurl, module_script);
  }
}

void NWCustomBindings::GetAbsolutePath(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  base::FilePath path = base::FilePath::FromUTF8Unsafe(*v8::String::Utf8Value(isolate, args[0]));
  MakePathAbsolute(&path);
#if defined(OS_POSIX)
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, path.value().c_str(), v8::NewStringType::kNormal).ToLocalChecked());
#else
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, path.AsUTF8Unsafe().c_str(), v8::NewStringType::kNormal).ToLocalChecked());
#endif
}

void NWCustomBindings::GetOldCwd(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  base::FilePath path = content::g_nw_old_cwd;
#if defined(OS_POSIX)
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, path.value().c_str(), v8::NewStringType::kNormal).ToLocalChecked());
#else
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, path.AsUTF8Unsafe().c_str(), v8::NewStringType::kNormal).ToLocalChecked());
#endif
}

void NWCustomBindings::AddOriginAccessWhitelistEntry(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();

  std::string sourceOrigin        = *v8::String::Utf8Value(isolate, args[0]);
  std::string destinationProtocol = *v8::String::Utf8Value(isolate, args[1]);
  std::string destinationHost     = *v8::String::Utf8Value(isolate, args[2]);
  bool allowDestinationSubdomains = args[3].As<v8::Boolean>()->Value();

  blink::WebSecurityPolicy::AddOriginAccessAllowListEntry(GURL(sourceOrigin),
                                                          blink::WebString::FromUTF8(destinationProtocol),
                                                          blink::WebString::FromUTF8(destinationHost), 0,
                                                          allowDestinationSubdomains ?
                                                          network::mojom::CorsDomainMatchMode::kAllowSubdomains : network::mojom::CorsDomainMatchMode::kDisallowSubdomains,
                                                          network::mojom::CorsPortMatchMode::kAllowAnyPort,
                                                          network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
  args.GetReturnValue().Set(v8::Undefined(isolate));
  return;
}

void NWCustomBindings::RemoveOriginAccessWhitelistEntry(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();

  std::string sourceOrigin        = *v8::String::Utf8Value(isolate, args[0]);

  //FIXME blink::WebSecurityPolicy::RemoveAllOriginAccessWhitelistEntriesForOrigin(GURL(sourceOrigin));

  args.GetReturnValue().Set(v8::Undefined(isolate));
  return;
}

void NWCustomBindings::GetProxyForURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();

  std::string url = *v8::String::Utf8Value(isolate, args[0]);
  GURL gurl(url);
  if (!gurl.is_valid()) {
    args.GetReturnValue().Set(isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate,
                                                                                "Invalid URL passed to App.getProxyForURL()", v8::NewStringType::kNormal).ToLocalChecked())));
    return;
  }
  std::string proxy;
  bool result = content::RenderThread::Get()->ResolveProxy(gurl, &proxy);
  if (!result) {
    args.GetReturnValue().Set(v8::Undefined(isolate));
    return;
  }
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, proxy.c_str(), v8::NewStringType::kNormal).ToLocalChecked());
  return;
}

void NWCustomBindings::SetDevToolsJail(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  if (!args.Length())
    return;
  content::RenderFrame* render_frame = context()->GetRenderFrame();
  if (!render_frame)
    return;
  WebFrame* main_frame = render_frame->GetWebFrame();
  if (args[0]->IsNull() || args[0]->IsUndefined()) {
    main_frame->setDevtoolsJail(NULL);
  }else{
	  v8::Handle<v8::Object> frm = v8::Handle<v8::Object>::Cast(args[0]);
	  blink::HTMLIFrameElement* iframe = blink::V8HTMLIFrameElement::ToImpl(frm);
    main_frame->setDevtoolsJail(blink::WebFrame::FromCoreFrame(iframe->ContentFrame()));
  }
  args.GetReturnValue().Set(v8::Undefined(isolate));
  return;
}

}  // namespace extensions


text:
<?php

/**
 * @package    symfony
 * @subpackage i18n
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
abstract class sfI18nYamlExtractor implements sfI18nExtractorInterface
{
}


text:
package io.reflectoring.coderadar.useradministration.port.driven;

import io.reflectoring.coderadar.domain.User;

public interface GetUserPort {

  /**
   * Retrieves a user given their id.
   *
   * @param id The id of the user.
   * @return The user with the id.
   */
  User getUser(long id);

  /**
   * Retrieves a user given their username.
   *
   * @param username The username of the user.
   * @return The user with the username.
   */
  User getUserByUsername(String username);

  /**
   * @param username The username of the user.
   * @return True if a user with this username exists, false otherwise.
   */
  boolean existsByUsername(String username);

  /**
   * @param id The id of the user.
   * @return True if a user with this id exists, false otherwise.
   */
  boolean existsById(long id);
}


text: This template configure **Front Door** for client IP whitelisting or blacklisting


text:
set(MAPTK_UTIL_ROOT "${CMAKE_CURRENT_LIST_DIR}")

include("${CMAKE_CURRENT_LIST_DIR}/utils/maptk-utils-buildinfo.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/utils/maptk-utils-targets.cmake")


text:
package org.vitrivr.cineast.core.features;

import org.vitrivr.cineast.core.data.entities.SimpleFulltextFeatureDescriptor;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.features.abstracts.AbstractTextRetriever;

public class AudioTranscriptionSearch extends AbstractTextRetriever {

  public static final String AUDIO_TRANSCRIPTION_TABLE_NAME = "features_audiotranscription";

  /**
   * Default constructor for {@link AudioTranscriptionSearch}.
   */
  public AudioTranscriptionSearch() {
    super(AudioTranscriptionSearch.AUDIO_TRANSCRIPTION_TABLE_NAME);
  }

  /**
   * Extracts the subtitle text and ingests it using the {@link SimpleFulltextFeatureDescriptor}.
   *
   * @param shot The {@link SegmentContainer} that should be processed.
   */
  @Override
  public void processSegment(SegmentContainer shot) {
    shot.getSubtitleItems().stream()
        .map(s -> new SimpleFulltextFeatureDescriptor(shot.getId(), s.getText()))
        .forEach(s -> this.writer.write(s));
  }
}


text:
package com.opengamma.analytics.financial.credit;

/**
 * Enumeration of the different methods for creating the stub on the premium leg of a credit default swap
 * Note that the code does not calculate if the first coupon is long or short. The first coupon is determined based on this switches setting
 */
public enum StubType {
  /**
   * Stub is at the start (front) of the cashflow schedule; first coupon is on the first IMM date after the effective date (short stub)
   */
  FRONTSHORT,
  /**
   * Stub is at the start (front) of the cashflow schedule; first coupon is on the first but one IMM date after the effective date (long stub)
   */
  FRONTLONG,
  /**
   * Stub is at the end (back) of the cashflow schedule; last but one coupon is on the last scheduled coupon date before the maturity date (short stub)
   */
  BACKSHORT,
  /**
   * Stub is at the end (back) of the cashflow schedule; last but one coupon is on the last but one scheduled coupon date before the maturity date (long stub)
   */
  BACKLONG,
  /**
   * No stub
   */
  NONE;

  // TODO : Double check these definitions
}


text:
set -e

POSTGRESQL_BIN=/usr/lib/postgresql/9.6/bin/postgres
POSTGRESQL_CONFIG_FILE=/etc/postgresql/9.6/main/postgresql.conf
POSTGRESQL_DATA=/var/lib/postgresql/9.6/main

exec $POSTGRESQL_BIN -D $POSTGRESQL_DATA -c config_file=$POSTGRESQL_CONFIG_FILE


text:
/**
 * @module
 * @description
 * Entry point for all public APIs of Angular Material.
 */
export * from './version';
export * from './core';
export * from './module';
export * from './autocomplete/index';
export * from './button/index';
export * from './button-toggle/index';
export * from './card/index';
export * from './chips/index';
export * from './checkbox/index';
export * from './datepicker/index';
export * from './dialog/index';
export * from './expansion/index';
export * from './form-field/index';
export * from './grid-list/index';
export * from './icon/index';
export * from './input/index';
export * from './list/index';
export * from './menu/index';
export * from './paginator/index';
export * from './progress-bar/index';
export * from './progress-spinner/index';
export * from './radio/index';
export * from './select/index';
export * from './sidenav/index';
export * from './slider/index';
export * from './slide-toggle/index';
export * from './snack-bar/index';
export * from './sort/index';
export * from './table/index';
export * from './tabs/index';
export * from './tabs/tab-nav-bar/index';
export * from './toolbar/index';
export * from './tooltip/index';


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/quick_edit_large_shadow"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:weightSum="3" >

    <ImageView
        android:id="@+id/image_post_set"
        android:layout_width="0dip"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:contentDescription="@string/empty"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:id="@+id/info_wrap"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="2"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/title_wrap"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="10" >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="9"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="2"
                    android:textSize="18sp" />

                <EditText
                    android:id="@+id/input_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@android:color/transparent"
                    android:gravity="center_horizontal|left"
                    android:inputType="textMultiLine"
                    android:maxLines="2"
                    android:singleLine="false"
                    android:textSize="18sp"
                    android:visibility="gone" />
            </LinearLayout>

            <TextView
                android:id="@+id/close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:drawableRight="@drawable/close"
                android:gravity="right" />
        </LinearLayout>

        <TextView
            android:id="@+id/url"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:textColor="@color/soft_grey_split"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="5"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/input_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:gravity="center_horizontal|left"
            android:inputType="textMultiLine"
            android:maxLines="5"
            android:singleLine="false"
            android:textSize="16sp"
            android:visibility="gone" />

        <LinearLayout
            android:id="@+id/thumbnail_options"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:orientation="vertical"
            android:visibility="gone" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <Button
                    android:id="@+id/post_previous"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_gravity="center_vertical"
                    android:background="@drawable/common_button_blue"
                    android:paddingBottom="4dp"
                    android:text="@string/previous"
                    android:textColor="@android:color/white" />

                <Button
                    android:id="@+id/post_forward"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginRight="4dp"
                    android:background="@drawable/common_button_blue"
                    android:paddingBottom="4dp"
                    android:text="@string/forward"
                    android:textColor="@android:color/white" />

                <TextView
                    android:id="@+id/count"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:textSize="14sp" />
            </LinearLayout>

            <TextView
                android:id="@+id/choose_thumbnail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/choose_thumbnail"
                android:textColor="@color/soft_grey_choose"
                android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/no_thumbnail_options"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:visibility="gone" >

            <CheckBox
                android:id="@+id/no_thumbnail_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/no_thumbnail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no_thumbnail"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
\documentclass[11pt]{meetingmins}
\usepackage[utf8]{inputenc}

\setcommittee{BugBusters}

\setmembers{

  D.~Polonio,
  D.~Rigoni,
  M.~Di Pirro,
  G.~Mazzocchin,
  L.~Bianco,
  A.~Mantovani,
  E.~Carraro
}

\setdate{May 2, 2016}

\setpresent{

  D.~Polonio,
  E.~Carraro,
  D.~Rigoni,
  A.~Mantovani
  G.~Mazzocchin
}

\absent{

  L.~Bianco,
  M.~Di Pirro
}

\alsopresent{None}

\begin{document}

\maketitle

\section{Ordine del giorno}

\begin{enumerate}

\item Note dal taccuino sulle Norme
\item Pianificazione e assegnazione dei \textit{task} per la stesura di MaaS
\item Controllare codice di un \textit{backend} di esempio presentato da Luca Bianco
\item Definire le regole da inserire nelle norme in base ai punti segnati nel taccuino

\end{enumerate}

\section{Orari}

\begin{itemize}
\item[Inizio]: ore 11:45
\item[Fine]: ore 12:30
\item[Tempo]: Previsto di 45 min, effettivo di 45 min

\end{itemize}

\section{Verbale}

\subsection{Note dal taccuino di Teamwork sulle Norme}
	\paragraph*{Creazione Pull Request}
		La procedura: un membro termina il proprio task, apre la Pull Request con le stesse
		label del task e con la stessa Milestone. Il verificatore chiude il task.
		Quando si termina un task va chiusa la issue corrispondente.

	\paragraph*{Descrizione dei commit, come specificare le modifiche a seconda del tipo di file}
		Al momento dell'apertura di una Pull Request, il suo creatore deve segnalare le sezioni modificate e
		le motivazioni (va inserita una descrizione adeguatamente approfondita).

	\paragraph*{Definire una regola corretta per i nomi del glossario}
		Il responsabile dovr\`a occuparsi di questo problema.

	\paragraph*{Nome fasi in maiuscolo o minuscolo}
		\`E stato stabilito che i nomi delle fasi dovranno essere tutti in maiuscolo.
		Nel caso in cui una voce sia composta da pi\`u termini, tutti i singoli termini devono avere l'iniziale maiuscola.

	\paragraph*{Procedura apertura issue. Il branch dell'attivit\`a da chi \`e aperto? Quando viene concluso un task come bisogna procedere?}
		L'assegnatario dell'attivitit\`a apre il \textit{branch} corrispondente all'activity.

	\paragraph*{Se l'attivit\`a riguarda una modifica, quale versione va considerata?}
		La versione nel branch in cui verr\`a applicata la modifica? Oppure l'ultima \textit{release}?)
		\`E stato stabilito che il responsabile applicher\`a la procedura adeguata per il problema in esame.

	\paragraph*{Conflitti nelle Pull Request}
		\`E stato stabilito che in caso di conflitto il verificatore operer\`a congiuntamente all'assegnatario della
		\textit{issue} per risolvere problema.

	\paragraph*{\textbf{Specifica tecnica}: l'\textit{editor} e l'interprete hanno titoli in cui ogni elemento è preceduto
		dal package (es: DSLCreator::DSLElement) mentre il \textit{frontend} e \textit{backend}
		non sono conformi alla stessa notazione. La notazione andrebbe uniformata}
		Da definire.

	\paragraph*{Decidere il momento della chiusura delle \textit{issue}: una volta completato il task o dopo l'approvazione della PR}
		La issue va chiusa immediatamente dopo la chiusura di una Pull Request.

	\paragraph*{Convenzione nomi file}
		I nomi dei file andranno in inglese, in minuscolo e seguendo la convenzione \textit{camelCase}.

\nextmeeting{da definire}

\end{document}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gongylia macrospora Suza

### Remarks
null


text:
using Gem.Engine.AI.BehaviorTree;
using Gem.Engine.AI.BehaviorTree.Composites;
using Gem.Engine.AI.BehaviorTree.Decorators;
using Gem.Engine.AI.BehaviorTree.Leaves;
using Gem.Engine.AI.BehaviorTree.Visualization;
using Gem.DrawingSystem;
using Gem.Engine.BehaviorTreeVisualization.Behaviors;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Gem.Engine.BehaviorTreeVisualization
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class BehaviorTreeVisualizer : Game
    {
        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private TreeVisualizer visualizer;
        private Texture2D background;
        private RenderTargetRenderer renderer;
        private Level level;

        public BehaviorTreeVisualizer()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferHeight = 715;
            graphics.PreferredBackBufferWidth = 1420;
            graphics.ApplyChanges();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            level = new Level(Content, 64, 64);

            var nodeTexture = Content.Load<Texture2D>(@"Sprites/node");
            var linkTexture = Content.Load<Texture2D>(@"Sprites/link");
            var lineTexture = Content.Load<Texture2D>(@"Sprites/line");
            var success = Content.Load<Texture2D>(@"Sprites/success");
            var failure = Content.Load<Texture2D>(@"Sprites/failure");
            var running = Content.Load<Texture2D>(@"Sprites/running");
            var nodeFont = Content.Load<SpriteFont>(@"Fonts/nodeFont");
            background = Content.Load<Texture2D>(@"Sprites/treeBackground");

            visualizer = new TreeVisualizer(nodeTexture, lineTexture, linkTexture, running, success, failure, nodeFont);
            level.Context.onBehaviorChanged += (sender, args) => ConfigureTreeVisualizer((sender as BehaviorContext).Behavior);
            ConfigureTreeVisualizer(level.Context.Behavior);

        }

        private void ConfigureTreeVisualizer<AIContext>(IBehaviorNode<AIContext> behavior)
        {
            visualizer.Prepare(new MinimalColorPainter(), level.Context.Behavior);
            renderer = new RenderTargetRenderer(batch =>
            {
                spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);

                visualizer.RenderTree(spriteBatch);
                spriteBatch.End();
            },
               GraphicsDevice,
               new Vector2(GraphicsDevice.Viewport.Width*2, visualizer.TreeSize.Y));
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here
            level.Update(gameTime.ElapsedGameTime.TotalSeconds);
            visualizer.Update(gameTime.ElapsedGameTime.TotalSeconds);

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(new Color(44, 62, 80));

            renderer.Render(spriteBatch);
            spriteBatch.Begin();
            spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, new Color(236, 240, 241));
            spriteBatch.Draw(renderer.Target, new Vector2(-220, -15), Color.White);
            level.Draw(spriteBatch, new Vector2(60, 645));
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LogOutActivity" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LOGOUT page"
        android:textSize="25sp" />

    <Button
        android:id="@+id/btnLogOut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click to Login" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="45dp"
        android:text="@string/app_detail"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


text:
const _ = require('lodash');
const helpers = require('./helpers');
const FastBitSet = require('fastbitset');

/**
 * search by filters
 */
module.exports.search = function(items, input, configuration, fulltext, facets) {

  input = input || {};

  const per_page = parseInt(input.per_page || 12);
  const page = parseInt(input.page || 1);
  const is_all_filtered_items = input.is_all_filtered_items || false;

  if (configuration.native_search_enabled === false && (input.query || input.filter)) {
    throw new Error('"query" and "filter" options are not working once native search is disabled');
  }

  let search_time = 0;
  const total_time_start = new Date().getTime();
  let query_ids;
  // all ids bitmap
  let filtered_indexes_bitmap = facets.bits_ids();
  let _ids;
  let all_filtered_items;

  if (input._ids) {
    query_ids = new FastBitSet(input._ids);
    _ids = input._ids;
  } else if (input.ids) {
    _ids = facets.internal_ids_from_ids_map(input.ids);
    //console.log(_ids);
    query_ids = new FastBitSet(_ids);
  } else if (fulltext && (input.query || input.filter)) {

    const search_start_time = new Date().getTime();
    _ids = fulltext.search(input.query, input.filter);
    search_time = new Date().getTime() - search_start_time;
    query_ids = new FastBitSet(_ids);
  }

  let facets_time = new Date().getTime();
  const facet_result = facets.search(input, {
    query_ids: query_ids
  });
  facets_time = new Date().getTime() - facets_time;

  if (query_ids) {
    filtered_indexes_bitmap = query_ids;
  }

  if (facet_result.ids) {
    filtered_indexes_bitmap = filtered_indexes_bitmap.new_intersection(facet_result.ids);
  }

  if (facet_result.not_ids) {
    filtered_indexes_bitmap = filtered_indexes_bitmap.new_difference(facet_result.not_ids);
  }

  // new filters to items
  // -------------------------------------
  let filtered_indexes = filtered_indexes_bitmap.array();

  let filtered_items = filtered_indexes.map(_id => {
    return facets.get_item(_id);
  });

  /**
   * sorting items
   */
  let paginationApplied = false;
  const sorting_start_time = new Date().getTime();
  let sorting_time = 0;
  if (input.sort) {
    filtered_items = module.exports.sorted_items(filtered_items, input.sort, configuration.sortings);
  } else {

    if (_ids) {

      filtered_indexes = _ids.filter(v => {
        return filtered_indexes_bitmap.has(v);
      });

      const filtered_items_indexes = filtered_indexes.slice((page - 1) * per_page, page * per_page);
      filtered_items = filtered_items_indexes.map(_id => {
        return facets.get_item(_id);
      });

      paginationApplied = true;
    }
  }
  // pagination
  if (!paginationApplied) {
    all_filtered_items = is_all_filtered_items ? filtered_items: null;
    filtered_items = filtered_items.slice((page - 1) * per_page, page * per_page);
  }

  sorting_time = new Date().getTime() - sorting_start_time;

  const total_time = new Date().getTime() - total_time_start;

  //console.log(facet_result);

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: filtered_indexes.length
    },
    timings: {
      total: total_time,
      facets: facets_time,
      //filter: filter_time,
      search: search_time,
      sorting: sorting_time
    },
    data: {
      items: filtered_items,
      allFilteredItems: all_filtered_items,
      //aggregations: aggregations,
      aggregations: helpers.getBuckets(facet_result, input, configuration.aggregations),
    }
  };
};

/**
 * return items by sort
 */
module.exports.sorted_items = function(items, sort, sortings) {
  if (sortings && sortings[sort]) {
    sort = sortings[sort];
  }

  if (sort.field) {
    return _.orderBy(
      items,
      sort.field,
      sort.order || 'asc'
    );
  }

  return items;
};

/**
 * returns list of elements in aggregation
 * useful for autocomplete or list all aggregation options
 */
module.exports.similar = function(items, id, options) {

  const per_page = options.per_page || 10;
  const minimum = options.minimum || 0;
  const page = options.page || 1;

  let item;

  for (let i = 0 ; i < items.length ; ++i) {
    if (items[i].id == id) {
      item = items[i];
      break;
    }
  }

  if (!options.field) {
    throw new Error('Please define field in options');
  }

  const field = options.field;
  let sorted_items = [];

  for (let i = 0 ; i < items.length ; ++i) {

    if (items[i].id !== id) {
      const intersection = _.intersection(item[field], items[i][field]);

      if (intersection.length >= minimum) {
        sorted_items.push(items[i]);
        sorted_items[sorted_items.length - 1].intersection_length = intersection.length;
      }
    }
  }

  sorted_items = _.orderBy(
    sorted_items,
    ['intersection_length'],
    ['desc']
  );

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: sorted_items.length
    },
    data: {
      items: sorted_items.slice((page - 1) * per_page, page * per_page),
    }
  };
};

/**
 * returns list of elements in specific facet
 * useful for autocomplete or list all aggregation options
 */
module.exports.aggregation = function (items, input, configuration, fulltext, facets) {
  const per_page = input.per_page || 10;
  const page = input.page || 1;

  if (input.name && (!configuration.aggregations || !configuration.aggregations[input.name])) {
    throw new Error('Please define aggregation "'.concat(input.name, '" in config'));
  }

  const search_input = helpers.clone(input);

  search_input.page = 1;
  search_input.per_page = 0;

  if (!input.name) {
    throw new Error('field name is required');
  }

  configuration.aggregations[input.name].size = 10000;

  const result = module.exports.search(items, search_input, configuration, fulltext, facets);
  const buckets = result.data.aggregations[input.name].buckets;

  return {
    pagination: {
      per_page: per_page,
      page: page,
      total: buckets.length
    },
    data: {
      buckets: buckets.slice((page - 1) * per_page, page * per_page)
    }
  };
};


text:
var assert = require("assert"),
    vows = require("vows"),
    Accept = require("./../lib/header/accept");

vows.describe("header/accept").addBatch({
    "An Accept header": {
        "should know its qvalues": function () {
            var header = new Accept("text/html, text/*;q=0.3, */*;q=0.5");
            assert.equal(header.qvalue("image/png"), 0.5);
            assert.equal(header.qvalue("text/plain"), 0.3);
            assert.equal(header.qvalue("text/html"), 1);

            header = new Accept("text/html");
            assert.equal(header.qvalue("image/png"), 0);

            header = new Accept("");
            assert.equal(header.qvalue("text/html"), 1);
        },
        "should match properly": function () {
            var header = new Accept("text/*, text/html, text/html;level=1, */*")
            assert.deepEqual(header.matches(""), ["*/*"]);
            assert.deepEqual(header.matches("image/jpeg"), ["*/*"]);
            assert.deepEqual(header.matches("text/plain"), ["text/*", "*/*"]);
            assert.deepEqual(header.matches("text/html"), ["text/html", "text/*", "*/*"]);
            assert.deepEqual(header.matches("text/html;level=1"), ["text/html;level=1", "text/html", "text/*", "*/*"]);
            assert.deepEqual(header.matches("text/html;level=1;answer=42"), ["text/html;level=1", "text/html", "text/*", "*/*"]);
        }
    }
}).export(module);


text:
import haversin = require( './index' );

// TESTS //

// The function returns a number...
{
	haversin( 8 ); // $ExpectType number
}

// The compiler throws an error if the function is provided a value other than a number...
{
	haversin( true ); // $ExpectError
	haversin( false ); // $ExpectError
	haversin( null ); // $ExpectError
	haversin( undefined ); // $ExpectError
	haversin( '5' ); // $ExpectError
	haversin( [] ); // $ExpectError
	haversin( {} ); // $ExpectError
	haversin( ( x: number ): number => x ); // $ExpectError
}

// The compiler throws an error if the function is provided insufficient arguments...
{
	haversin(); // $ExpectError
}


text:
#include <aws/gamelift/model/UpdateAliasRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateAliasRequest::UpdateAliasRequest() :
    m_aliasIdHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_routingStrategyHasBeenSet(false)
{
}

Aws::String UpdateAliasRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_aliasIdHasBeenSet)
  {
   payload.WithString("AliasId", m_aliasId);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_routingStrategyHasBeenSet)
  {
   payload.WithObject("RoutingStrategy", m_routingStrategy.Jsonize());

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateAliasRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.UpdateAlias"));
  return headers;

}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55010248"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<docTitle>
	<titlePart>Cross-Reference Your XML Data<lb/></titlePart>
	</docTitle>

	<byline>
	<docAuthor>Charles Heinemann<lb/></docAuthor>
	</byline>

	<byline>
	<affiliation>Microsoft Corporation<lb/></affiliation>
	</byline>

	<date>December 7, 1998<lb/></date>

	<note type="other">Download the source code for this article (2.3 KB)<lb/></note>

		</front>
	</text>
</tei>


text:
/*
 * Hackish way to implement setjmp/longjmp in pure MVP wasm using Binaryen's
 * Asyncify feature.
 *
 * Background: Setjmp/longjmp works in Emscripten (on the Web, in Node.js, in
 * wasmer, etc.) but it depends on JS support (or on the runtime to support
 * the special invoke/dynCall imports). This file shows how to implement
 * setjmp/longjmp in pure MVP wasm and without any special imports, instead
 * using Asyncify to modify the wasm to allow pause/resume and with a setjmp/
 * longjmp implementation that uses that.
 *
 *  https://kripken.github.io/blog/wasm/2019/07/16/asyncify.html
 *
 * Compile with something like
 *
 *   clang -O --target=wasm32 -c jmp.c -o jmp.o -Wno-incomplete-setjmp-declaration -Wno-incompatible-library-redeclaration -g
 *   wasm-ld --no-entry --export-all --allow-undefined jmp.o -o jmp.wasm
 *   wasm-opt jmp.wasm --asyncify -O -o jmp_async.wasm -g --pass-arg=asyncify-ignore-imports
 *
 * Run with something like
 *
 *  wasmer run jmp_async.wasm
 *  wasmtime jmp_async.wasm
 *
 * Printing code using wasi is from the very useful
 *
 *  https://gist.github.com/s-macke/6dd78c78be46214d418454abb667a1ba
 *
 * by @s-macke - thanks!
 */

// No #includes, do everything ourselves

#define NULL 0

#define WASM_IMPORT(module, base) \
  __attribute__((__import_module__(#module), __import_name__(#base)))

#define NOINLINE __attribute__((noinline))

typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef long size_t;

// The Asyncify API

void asyncify_start_unwind(void* buf) WASM_IMPORT(asyncify, start_unwind);
void asyncify_stop_unwind() WASM_IMPORT(asyncify, stop_unwind);
void asyncify_start_rewind(void* buf) WASM_IMPORT(asyncify, start_rewind);
void asyncify_stop_rewind() WASM_IMPORT(asyncify, stop_rewind);

// Enough WASI API to print

typedef uint16_t __wasi_errno_t;
typedef uint32_t __wasi_fd_t;

struct __wasi_ciovec_t {
  const void* buf;
  size_t buf_len;
};

__wasi_errno_t __wasi_fd_write(
  __wasi_fd_t fd,
  const struct __wasi_ciovec_t* iovs,
  size_t iovs_len,
  size_t* nwritten
) WASM_IMPORT(wasi_unstable, fd_write) __attribute__((__warn_unused_result__));

// Enough libc to print

NOINLINE
size_t strlen(const char* str) {
  const char* s;
  for (s = str;* s; ++s);
  return s - str;
}

// sends string to stdout
NOINLINE
void print(const char* str) {
  const __wasi_fd_t stdout = 1;
  size_t nwritten;
  __wasi_errno_t error;
  struct __wasi_ciovec_t iovec;
  iovec.buf = str;
  iovec.buf_len = strlen(str);
  error =__wasi_fd_write(stdout, &iovec, 1, &nwritten);
}

NOINLINE
void puts(const char* str) {
  print(str);
  print("\n");
}

//
// The "upper runtime" using Asyncify: A weird impl of setjmp/longjmp
//

#define ASYNC_BUF_BUFFER_SIZE 1000

// An Asyncify buffer.
struct async_buf {
  void* top; // current top of the used part of the buffer
  void* end; // fixed end of the buffer
  void* unwound; // top of the buffer when full (unwound and ready to rewind)
  char buffer[ASYNC_BUF_BUFFER_SIZE];
};

NOINLINE
void async_buf_init(struct async_buf* buf) {
  buf->top = &buf->buffer[0];
  buf->end = &buf->buffer[ASYNC_BUF_BUFFER_SIZE];
}

NOINLINE
void async_buf_note_unwound(struct async_buf* buf) {
  buf->unwound = buf->top;
}

NOINLINE
void async_buf_rewind(struct async_buf* buf) {
  buf->top = buf->unwound;
}

// A setjmp/longjmp buffer.
struct jmp_buf {
  // A buffer for the setjmp. Unwound and rewound immediately, and can
  // be rewound a second time to get to the setjmp from the longjmp.
  struct async_buf setjmp_buf;
  // A buffer for the longjmp. Unwound once and never rewound.
  struct async_buf longjmp_buf;
  // The value to return.
  int value;
  // FIXME We assume this is initialized to zero.
  int state;
};

static struct jmp_buf* __active_jmp_buf = NULL;

NOINLINE
int setjmp(struct jmp_buf* buf) {
  if (buf->state == 0) {
    __active_jmp_buf = buf;
    async_buf_init(&buf->setjmp_buf);
    asyncify_start_unwind(&buf->setjmp_buf);
  } else {
    asyncify_stop_rewind();
    if (buf->state == 2) {
      // We returned from the longjmp, all done.
      __active_jmp_buf = NULL;
    }
  }
  buf->state++;
  return buf->value;
}

NOINLINE
void longjmp(struct jmp_buf* buf, int value) {
  buf->value = value;
  async_buf_init(&buf->longjmp_buf);
  asyncify_start_unwind(&buf->longjmp_buf);
  // TODO: handle local var changes by updating the setjmp_buf
}

//
// The "lower runtime": Starts everything, is unwound to, resumes, etc.
//

void user_program();

void _start() {
  // This has enough logic to handle one longjmp.
  while (1) {
    // Call into the program. This is either the first call, or a resume.
    user_program();
    if (!__active_jmp_buf) {
      // The program has run to the end.
      return;
    }
    // The program is still working, just the stack has unwound to here.
    asyncify_stop_unwind();
    if (__active_jmp_buf->state == 1) {
      // Setjmp unwound to here. Prepare to rewind it twice.
      async_buf_note_unwound(&__active_jmp_buf->setjmp_buf);
    } else if (__active_jmp_buf->state == 2) {
      // Longjmp unwound to here. Rewind to the setjmp.
      async_buf_rewind(&__active_jmp_buf->setjmp_buf);
    }
    asyncify_start_rewind(&__active_jmp_buf->setjmp_buf);
  }
}

//===================================================================
// Start of the user program itself.
//===================================================================

struct jmp_buf my_buf;

// An inner function.
NOINLINE
void inner() {
  puts("call longjmp");
  longjmp(&my_buf, 1);
}

// The main part of the program (avoid main() because of wasi).
NOINLINE
void user_program() {
  puts("start");
  if (!setjmp(&my_buf)) {
    puts("call inner");
    inner();
  } else {
    puts("back from longjmp");
  }
  puts("end");
}

//===================================================================
// End of the user program itself.
//===================================================================


text:
<?php
namespace App\Modules\Robot\Models;
use App\Modules\Robot\Models\Request;
use App\Modules\Robot\Models\Response;
/**
* HTTP Request class – execute HTTP get and head requests
*
* @package HTTP
*/
class Request
{
		/**
	 * User agent
	 *
	 * @var string
	 */
		public static $user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8';

	/**
* Format timeout in seconds, if no timeout use default timeout
*
* @param int|float $timeout (seconds)
* @return int|float
*/
private static function __formatTimeout($timeout = 0)
{
	$timeout = (float)$timeout;
// format timeout value
	if($timeout < 0.1)
	{
		$timeout = 60;
// default timeout
	}
	return $timeout;
}
/**
* Parse HTTP response
*
* @param string $body
* @param array $header
* @return \HTTP\Response
*/
private static function __parseResponse($body, $header, $url)
{
	$status_code = 0;
	$content_type = '';

	if(is_array($header) && count($header) > 0)
	{
		foreach($header as $v)
		{
				// ex: HTTP/1.x XYZ Message
			if(substr($v, 0, 4) == 'HTTP'
				&& strpos($v, ' ') !== false)
			{
				$status_code = (int)substr($v,
						strpos($v, ' '), 4); // parse status code
			}
				// ex: Content-Type: *; charset=*
			else if(strncasecmp($v, 'Content-Type:', 13) === 0)
			{
				$content_type = $v;
			}
		}
	}

	return new Response($status_code, $content_type, $body, $header, $url);
}
	/**
	 * Execute HTTP GET request
	 *
	 * @param string $url
	 * @param int|float $timeout (seconds)
	 * @return \HTTP\Response
	 */
	public static function get($url, $timeout = 0)
	{
		$context = stream_context_create();

		stream_context_set_option($context, [
			'http' => [
			'timeout' => self::__formatTimeout($timeout),
			'header' => "User-Agent: " . self::$user_agent . "\r\n"
			]
			]);

		$http_response_header = NULL; // allow updating

		$res_body = file_get_contents($url, false, $context);

		return self::__parseResponse($res_body, $http_response_header, $url);
	}

	/**
	 * Execute HTTP HEAD request
	 *
	 * @param string $url
	 * @param int|float $timeout (seconds)
	 * @return \HTTP\Response
	 */
	public static function head($url, $timeout = 0)
	{
		$context = stream_context_create();

		stream_context_set_option($context, [
			'http' => [
			'method' => 'HEAD',
			'timeout' => self::__formatTimeout($timeout),
			'header' => "User-Agent: " . self::$user_agent . "\r\n"
			]
			]);

		$http_response_header = NULL; // allow updating

		$res_body =	file_get_contents($url, false, $context);

		return self::__parseResponse($res_body, $http_response_header, $url);
	}
}


text: Homework and excercises from the Software University & other projects


text:
namespace starboard {
namespace shared {
namespace starboard {

template <typename CHAR>
int lcpyT(CHAR* dst, const CHAR* src, int dst_size) {
  for (int i = 0; i < dst_size; ++i) {
    if ((dst[i] = src[i]) == 0)  // We hit and copied the terminating NULL.
      return i;
  }

  // We were left off at dst_size.  We over copied 1 byte.  Null terminate.
  if (dst_size != 0)
    dst[dst_size - 1] = 0;

  // Count the rest of the |src|, and return its length in characters.
  while (src[dst_size])
    ++dst_size;
  return dst_size;
}

}  // namespace starboard
}  // namespace shared
}  // namespace starboard

#endif  // SB_API_VERSION < 13

#endif  // STARBOARD_SHARED_STARBOARD_LCPY_H_