text:
// Copyright (c) 2016, Huang-Ming Huang,  Object Computing, Inc.
// All rights reserved.
//
// This file is part of mFAST.
// See the file license.txt for licensing information.
#include "field_builder.h"
#include "field_op.h"
#include "../exceptions.h"
#include <boost/tokenizer.hpp>
#include "mfast/field_instructions.h"

using namespace tinyxml2;

namespace mfast {
namespace xml_parser {
struct tag_referenced_by;
struct tag_template_name;

typedef boost::error_info<tag_referenced_by, std::string> referenced_by_info;
typedef boost::error_info<tag_template_name, std::string> template_name_info;

class template_not_found_error : public fast_dynamic_error {
public:
  template_not_found_error(const char *template_name, const char *referenced_by)
      : fast_dynamic_error("D8") {
    *this << template_name_info(template_name)
          << referenced_by_info(referenced_by);
  }
};

#ifndef NDEBUG

void print_node(const XMLElement *element, int indent)
{
  for (int i = 0; i < indent; ++i)
    std::cout << " ";
  std::cout << "node " << element->Name() ;
  const XMLAttribute *attr = element->FirstAttribute();
  while (attr) {
    std::cout << " " << attr->Name() << "=" << attr->Value();
    attr = attr->Next();
  }
  std::cout << "\n";

  const XMLElement *elem = element->FirstChildElement();
  while (elem){
    print_node(elem, indent+4);
    elem = elem->NextSiblingElement();
  }
}

#endif

const char *field_builder::name() const { return name_; }

std::size_t field_builder::num_instructions() const {
  return instructions_.size();
}

void field_builder::add_instruction(const field_instruction *inst) {
  instructions_.push_back(inst);
}

const char *field_builder::resolve_field_type(const XMLElement &element) {
  field_type_name_ = element.Name();
  content_element_ = &element;

  if (std::strcmp(field_type_name_, "field") == 0) {
    content_element_ = element.FirstChildElement();
    if (content_element_) {
      field_type_name_ = content_element_->Name();
      if (strcmp(field_type_name_, "type") == 0) {
        field_type_name_ = name_;
        name_ = nullptr;
        fast_xml_attributes::set(content_element_->FirstAttribute());

        if (name_ == nullptr)
          throw std::runtime_error("type element does not have a name");
        std::swap(field_type_name_, name_);
      } else {
        fast_xml_attributes::set(content_element_->FirstAttribute());
      }
    } else {
      throw std::runtime_error("field element must have a  child element");
    }
  }

  resolved_ns_ = ns_;
  if (resolved_ns_ == nullptr && parent_) {
    resolved_ns_ = parent_->resolved_ns();
  }

  return field_type_name_;
}

const field_instruction *field_builder::find_prototype(const char *type_name) {
  if (type_name == nullptr) {
    BOOST_THROW_EXCEPTION(fast_static_error("S1")
                          << reason_info("no field type specified"));
  }
  const field_instruction *instruction = nullptr;

  if (std::strcmp(type_name, "string") == 0) {
    if (this->charset_ == nullptr)
      this->charset_ = get_optional_attr(element_, "charset", "ascii");

    if (std::strcmp(this->charset_, "unicode") == 0) {
      static unicode_field_instruction prototype(
          operator_none, presence_mandatory, 0, nullptr, "", nullptr,
          string_value_storage(), 0, "", "");
      instruction = &prototype;
    }
  } else if (std::strcmp(type_name, "templateRef") == 0) {
    return templateref_instruction::default_instruction()[0];
  } else if (std::strcmp(type_name, "typeRef") == 0 ||
             std::strcmp(type_name, "length") == 0) {
    return nullptr;
  }

  if (instruction == nullptr) {
    instruction = this->find_type(ns_, type_name);
  }

  if (instruction == nullptr) {
    BOOST_THROW_EXCEPTION(
        fast_static_error("S1") << reason_info(
            (std::string("Invalid field type specified : ") + type_name)));
  }

  return instruction;
}

field_builder::field_builder(field_builder_base *parent,
                             const XMLElement &element)
    : fast_xml_attributes(element.FirstAttribute()),
      field_builder_base(parent->registry(), parent->local_types()),
      element_(element), parent_(parent) {}

field_builder::field_builder(field_builder_base *parent,
                             const XMLElement &element, const char *name)
    : fast_xml_attributes(element.FirstAttribute()),
      field_builder_base(parent->registry(), parent->local_types()),
      element_(element), parent_(parent) {
  name_ = name;
}

void field_builder::build() {
  const field_instruction *prototype =
      find_prototype(resolve_field_type(element_));
  if (prototype) {
    prototype->accept(*this, nullptr);
  }
}

template <typename IntType>
void field_builder::build_integer(const int_field_instruction<IntType> *inst) {
  field_op fop(inst, &element_, alloc());

  field_instruction *instruction = new (alloc()) int_field_instruction<IntType>(
      fop.op_, get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), fop.context_,
      int_value_storage<IntType>(fop.initial_value_), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const int32_field_instruction *inst, void *) {
  build_integer(inst);
}

void field_builder::visit(const uint32_field_instruction *inst, void *) {
  build_integer(inst);
}

void field_builder::visit(const int64_field_instruction *inst, void *) {
  build_integer(inst);
}

void field_builder::visit(const uint64_field_instruction *inst, void *) {
  build_integer(inst);
}

void field_builder::visit(const decimal_field_instruction *inst, void *) {
  const mantissa_field_instruction *base_mantissa_instruction =
      inst->mantissa_instruction();
  const XMLElement *mantissa_element = element_.FirstChildElement("mantissa");
  const XMLElement *exponent_element = element_.FirstChildElement("exponent");
  field_instruction *instruction;
  if (base_mantissa_instruction || mantissa_element || exponent_element) {

    mantissa_field_instruction *mantissa_instruction = nullptr;

    if (base_mantissa_instruction == nullptr) {
      static const mantissa_field_instruction mantissa_prototype(
          operator_none, nullptr, int_value_storage<int64_t>(0));
      base_mantissa_instruction = &mantissa_prototype;
    }

    if (mantissa_element) {
      field_op mantissa_op(base_mantissa_instruction, mantissa_element,
                           alloc());

      mantissa_instruction = new (alloc()) mantissa_field_instruction(
          mantissa_op.op_, mantissa_op.context_,
          int_value_storage<int64_t>(mantissa_op.initial_value_));
    } else {
      mantissa_instruction =
          new (alloc()) mantissa_field_instruction(*base_mantissa_instruction);
    }

    field_op exponent_op(inst, exponent_element, alloc());

    instruction = new (alloc()) decimal_field_instruction(
        exponent_op.op_, get_presence(inst), get_id(inst), get_name(alloc()),
        get_ns(inst, alloc()), exponent_op.context_, mantissa_instruction,
        decimal_value_storage(exponent_op.initial_value_), parse_tag(inst));
  } else {

    field_op decimal_op(inst, &element_, alloc());

    instruction = new (alloc()) decimal_field_instruction(
        decimal_op.op_, get_presence(inst), get_id(inst), get_name(alloc()),
        get_ns(inst, alloc()), decimal_op.context_,
        decimal_value_storage(decimal_op.initial_value_), parse_tag(inst));
  }
  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const ascii_field_instruction *inst, void *) {
  field_op fop(inst, &element_, alloc());
  field_instruction *instruction = new (alloc()) ascii_field_instruction(
      fop.op_, get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), fop.context_,
      string_value_storage(fop.initial_value_), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const unicode_field_instruction *inst, void *) {
  field_op fop(inst, &element_, alloc());

  const XMLAttribute *length_attributes = nullptr;
  const XMLElement *length_element = element_.FirstChildElement("length");

  if (length_element) {
    length_attributes = length_element->FirstAttribute();
  }

  fast_xml_attributes length_attrs(length_attributes);

  field_instruction *instruction = new (alloc()) unicode_field_instruction(
      fop.op_, get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), fop.context_,
      string_value_storage(fop.initial_value_),
      get_length_id(inst, length_attrs), get_length_name(inst, length_attrs),
      get_length_ns(inst, length_attrs), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const byte_vector_field_instruction *inst, void *) {
  field_op fop(inst, &element_, alloc());

  const XMLAttribute *length_attributes = nullptr;
  const XMLElement *length_element = element_.FirstChildElement("length");

  if (length_element) {
    length_attributes = length_element->FirstAttribute();
  }

  fast_xml_attributes length_attrs(length_attributes);

  field_instruction *instruction = new (alloc()) byte_vector_field_instruction(
      fop.op_, get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), fop.context_,
      string_value_storage(fop.initial_value_),
      get_length_id(inst, length_attrs), get_length_name(inst, length_attrs),
      get_length_ns(inst, length_attrs), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const int32_vector_field_instruction *inst, void *) {
  field_instruction *instruction = new (alloc()) int32_vector_field_instruction(
      get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const uint32_vector_field_instruction *inst, void *) {
  field_instruction *instruction = new (alloc())
      uint32_vector_field_instruction(get_presence(inst), get_id(inst),
                                      get_name(alloc()), get_ns(inst, alloc()),
                                      parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const int64_vector_field_instruction *inst, void *) {
  field_instruction *instruction = new (alloc()) int64_vector_field_instruction(
      get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const uint64_vector_field_instruction *inst, void *) {
  field_instruction *instruction = new (alloc())
      uint64_vector_field_instruction(get_presence(inst), get_id(inst),
                                      get_name(alloc()), get_ns(inst, alloc()),
                                      parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const templateref_instruction *, void *) {
  templateref_instruction *instruction;

  if (name_) {
    const char *resolved_ns =
        get_optional_attr(element_, "templateNs", parent_->resolved_ns());
    const template_instruction *target =
        dynamic_cast<const template_instruction *>(
            this->find_type(resolved_ns, name_));

    if (target == nullptr) {
      BOOST_THROW_EXCEPTION(template_not_found_error(name_, parent_->name()));
    }

    // if (parent_->num_instructions() == 0) {
    //   // if the templateRef is the first in a group or sequence, we don't
    //   need the clone the
    //   // individual field because the field_index remains the same
    //   for (size_t i = 0; i < target->subinstructions().size(); ++i) {
    //     const field_instruction* sub_inst = target->subinstruction(i);
    //     parent_->add_instruction(sub_inst);
    //   }
    // }
    // else if (target->subinstructions().size() > 0) {
    //   // In this case, we do need the clone the subfield instructions because
    //   the field
    //   // index would be different from those in the referenced template.
    //   field_instruction* new_inst;
    //   for (size_t i = 0; i < target->subinstructions().size(); ++i) {
    //     new_inst = target->subinstruction(i)->clone(alloc());
    //     parent_->add_instruction(new_inst);
    //   }
    //   if (target->subinstructions().size() == 1 && new_inst->field_type() ==
    //   field_type_sequence)
    //   {
    //     static_cast<sequence_field_instruction*>(new_inst)->ref_instruction(target);
    //   }
    // }

    if (target->subinstructions().size() == 1 &&
        target->subinstruction(0)->field_type() == field_type_sequence) {
      field_instruction *new_inst = target->subinstruction(0)->clone(alloc());

      new_inst->decimal_place(this->get_decimal_place(new_inst));
      parent_->add_instruction(new_inst);
      static_cast<sequence_field_instruction *>(new_inst)
          ->ref_instruction(target);
    } else {
      for (size_t i = 0; i < target->subinstructions().size(); ++i) {
        field_instruction *sub_inst=target->subinstruction(i)->clone(alloc());
        sub_inst->decimal_place(this->get_decimal_place(sub_inst));
        parent_->add_instruction(sub_inst);
      }
    }
  } else {

    instruction = new (alloc()) templateref_instruction(
        static_cast<uint16_t>(parent_->num_instructions()));

    instruction->decimal_place(this->get_decimal_place(instruction));
    parent_->add_instruction(instruction);
  }
}

instructions_view_t field_builder::build_subfields() {
  const XMLElement *child = content_element_->FirstChildElement();
  while (child != nullptr) {

    field_builder builder(this, *child);
    builder.build();
    child = child->NextSiblingElement();
  }

  auto result = new (alloc()) const_instruction_ptr_t[this->num_instructions()];
  std::copy(instructions_.begin(), instructions_.end(), result);
  return instructions_view_t(result, this->num_instructions());
}

const group_field_instruction *field_builder::get_sole_templateref() {
  const XMLElement *child = content_element_->FirstChildElement();
  if (strcmp(child->Name(), "templateRef") == 0 &&
      child->NextSibling() == nullptr) {
    const char *target_name = child->Attribute("name", nullptr);
    if (target_name) {
      const char *target_ns =
          get_optional_attr(*child, "templateNs", parent_->resolved_ns());

      const group_field_instruction *target =
          dynamic_cast<const group_field_instruction *>(
              this->find_type(target_ns, target_name));

      if (target == nullptr)
        BOOST_THROW_EXCEPTION(
            template_not_found_error(target_name, this->name()));

      return target;
    }
  }
  return nullptr;
}

void field_builder::visit(const group_field_instruction *inst, void *) {
  instructions_view_t subinstructions = inst->subinstructions();

  if (inst->subinstructions().size() == 0) {
    subinstructions = build_subfields();
  }

  auto instruction = new (alloc()) group_field_instruction(
      get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), get_dictionary(inst), subinstructions,
      get_typeRef_name(element_), get_typeRef_ns(element_), inst->cpp_ns(),
      parse_tag(inst));

  if (inst->subinstructions().size() == 0) {
    instruction->ref_instruction(get_sole_templateref());
  } else {
    instruction->ref_instruction(inst);
  }
  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

const uint32_field_instruction *
field_builder::get_length_instruction(const sequence_field_instruction *inst) {
  const uint32_field_instruction *length_instruction =
      inst->length_instruction();

  const XMLElement *length_element =
      content_element_->FirstChildElement("length");

  if (length_element) {

    fast_xml_attributes length_attributes(length_element->FirstAttribute());

    field_op length_fop(length_instruction, length_element, alloc());

    length_instruction = new (alloc()) uint32_field_instruction(
        length_fop.op_, get_presence(inst),
        length_attributes.get_id(length_instruction),
        length_attributes.get_name(alloc()),
        length_attributes.get_ns(length_instruction, alloc()),
        length_fop.context_,
        int_value_storage<uint32_t>(length_fop.initial_value_));
  } else if (length_instruction->optional() !=
             (get_presence(inst) == mfast::presence_optional)) {
    length_instruction = new (alloc()) uint32_field_instruction(
        length_instruction->field_operator(), get_presence(inst),
        length_instruction->id(), length_instruction->name(),
        length_instruction->ns(), length_instruction->op_context(),
        int_value_storage<uint32_t>(length_instruction->initial_value()));
  }
  return length_instruction;
}

void field_builder::visit(const sequence_field_instruction *inst, void *) {
  instructions_view_t subinstructions = inst->subinstructions();

  sequence_field_instruction *instruction;
  const group_field_instruction *element_instruction = nullptr;

  if (inst->subinstructions().size() == 0) {
    subinstructions = build_subfields();
    element_instruction = get_sole_templateref();
    if (element_instruction == nullptr && subinstructions.size() == 1 &&
        subinstructions[0]->name()[0] == 0) {
      element_instruction =
          dynamic_cast<const group_field_instruction *>(subinstructions[0]);
      if (element_instruction)
        element_instruction = static_cast<const group_field_instruction *>(
            element_instruction->ref_instruction());
    }
  }

  const group_field_instruction *ref_inst =
      inst->subinstructions().size() == 0 ? nullptr : inst;

  instruction = new (alloc()) sequence_field_instruction(
      get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), get_dictionary(inst), subinstructions,
      element_instruction, ref_inst, get_length_instruction(inst),
      get_typeRef_name(element_), get_typeRef_ns(element_), inst->cpp_ns(),
      parse_tag(inst));
  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

void field_builder::visit(const template_instruction *inst, void *) {
  bool reset = false;
  const XMLAttribute *reset_attr = element_.FindAttribute("scp:reset");
  if (reset_attr == nullptr)
    reset_attr = element_.FindAttribute("reset");

  if (reset_attr) {
    if (strcmp(reset_attr->Value(), "true") == 0 ||
        strcmp(reset_attr->Value(), "yes") == 0)
      reset = true;
  }

  auto instruction = new (alloc()) template_instruction(
      id_ ? boost::lexical_cast<uint32_t>(id_) : 0, string_dup(name_, alloc()),
      string_dup(ns_, alloc()), string_dup(templateNs_, alloc()),
      string_dup(dictionary_, alloc()), build_subfields(), reset,
      get_typeRef_name(element_), get_typeRef_ns(element_), inst->cpp_ns(),
      parse_tag(inst));

  parent_->add_template(this->resolved_ns(), instruction);
}

void field_builder::add_template(const char *, template_instruction *inst) {
  BOOST_THROW_EXCEPTION(fast_static_error("S1")
                        << reason_info("template cannot be nested")
                        << template_name_info(inst->name())
                        << referenced_by_info(parent_->name()));
}

bool parse_enum_value(const char **enum_element_names,
                      const uint64_t *enum_element_values,
                      uint64_t num_elements, const char *value_name,
                      uint64_t &result) {

  for (uint64_t i = 0; i < num_elements; ++i) {
    if (std::strcmp(enum_element_names[i], value_name) == 0) {
      if (enum_element_values)
        result = enum_element_values[i];
      else
        result = i;
      return true;
    }
  }

  return false;
}

bool parse_enum_value(const enum_field_instruction *inst,
                      const char *value_name, uint64_t &result) {
  return parse_enum_value(inst->elements(), inst->element_values(),
                          inst->num_elements(), value_name, result);
}

struct tag_value;
typedef boost::error_info<tag_value, std::string> value_info;

void field_builder::visit(const enum_field_instruction *inst, void *) {

  const XMLElement *element = &this->element_;
  if (!field_op::find_field_op_element(*element))
    element = content_element_;
  field_op fop(inst, element, alloc());

  const char **enum_element_names = inst->elements();
  uint64_t num_elements = inst->num_elements();
  const uint64_t *enum_element_values = inst->element_values();

  const char *init_value_str = nullptr;
  if (!fop.initial_value_.is_defined()) {
    // if the  defined flag is false, the content value is parsed string from
    // XML
    init_value_str = fop.initial_value_.get<const char *>();
  }

  if (enum_element_names == nullptr) {

    std::deque<const char *> names;
    std::deque<uint64_t> values;

    const XMLElement *xml_element =
        content_element_->FirstChildElement("element");
    for (; xml_element != nullptr;
         xml_element = xml_element->NextSiblingElement("element")) {
      const char *name_attr = xml_element->Attribute("name");
      if (name_attr != nullptr) {
        if (init_value_str && std::strcmp(name_attr, init_value_str) == 0) {
          fop.initial_value_.set<uint64_t>(names.size());
        }
        names.push_back(string_dup(name_attr, alloc()));

        const char *value_str = xml_element->Attribute("value");
        if (value_str) {
          uint64_t v = boost::lexical_cast<uint64_t>(value_str);
          if (values.empty() || v > values.back()) {
            values.push_back(v);
          }
        }
      } else {
        throw std::runtime_error("XML element must have a name attribute");
      }
    }

    if (values.size() && values.size() != names.size()) {
      throw std::runtime_error("Invalid value specification for enum elements");
    }

    num_elements = names.size();
    enum_element_names = static_cast<const char **>(
        alloc().allocate(names.size() * sizeof(const char *)));
    std::copy(names.begin(), names.end(), enum_element_names);

    if (values.size()) {
      uint64_t *values_array = static_cast<uint64_t *>(
          alloc().allocate(values.size() * sizeof(uint64_t)));
      std::copy(values.begin(), values.end(), values_array);
      enum_element_values = values_array;
    }
  } else if (init_value_str) {
    // In this case, the element names are already defined, but we haven't
    // decide what the specified
    // initial value is.

    uint64_t init_value;
    if (parse_enum_value(enum_element_names, enum_element_values, num_elements,
                         init_value_str, init_value)) {
      fop.initial_value_ =
          value_storage(0); // reset the storage to defined value
      fop.initial_value_.set<uint64_t>(init_value);
    } else {
      BOOST_THROW_EXCEPTION(
          fast_static_error("Unrecognized enum initial value : ")
          << value_info(init_value_str));
    }
  }

  if (!fop.initial_value_.is_defined()) {
    if (fop.initial_value_.get<const char *>() != nullptr) {
      std::string msg = "Invalid initial value for enum : ";
      throw std::runtime_error(msg + init_value_str);
    } else {
      // at this point if initial_value_ is still undefined, we should reset it
      // to zero
      fop.initial_value_.set<uint64_t>(0);
    }
  }

  auto instruction = new (alloc()) enum_field_instruction(
      fop.op_, get_presence(inst), get_id(inst), get_name(alloc()),
      get_ns(inst, alloc()), fop.context_,
      int_value_storage<uint64_t>(fop.initial_value_), enum_element_names,
      enum_element_values, num_elements,
      inst->elements_ == nullptr ? nullptr : inst, inst->cpp_ns(),
      parse_tag(inst));

  instruction->decimal_place(this->get_decimal_place(instruction));
  parent_->add_instruction(instruction);
}

instruction_tag field_builder::parse_tag(const field_instruction *inst) {
  uint64_t value = inst->tag().to_uint64();
  if (tag_) {
    try {
      value |= boost::lexical_cast<uint64_t>(tag_);
    } catch (...) {
      const enum_field_instruction *inst =
          dynamic_cast<const enum_field_instruction *>(
              this->find_type(nullptr, "mfast:tag"));
      if (inst) {
        // treat the input tag as a "|" delimited tokens

        boost::char_separator<char> sep("| ");
        std::string tag(tag_);
        boost::tokenizer<boost::char_separator<char>> tokens(tag, sep);
        for (auto &&t : tokens) {
          uint64_t result;
          if (parse_enum_value(inst, t.c_str(), result))
            value |= result;
          else
            BOOST_THROW_EXCEPTION(fast_error("invalid tag") << value_info(t));
        }
      }
    }
  }
  return instruction_tag(value);
}

} /* coder */

} /* mfast */


text:
#ifndef W_POT_EMBEM_H
#define W_POT_EMBEM_H

#include <armadillo>
#include <vector>
#include <string>
#include <libint2.hpp>
#include "w-qcmol/Integrals.hpp"

namespace willow {

class PES {
public:

  PES (const int& natom,
       const std::string& theory,
       const std::string& basis,
       const std::string& method,
       const std::string& epol_esp);

  ~PES ();

  void compute (const arma::mat& pos,
		const arma::ivec& Zs);

  void esp_mol_update (const arma::mat& pos,
		       const arma::ivec& Zs,
		       arma::vec& Qs);

  void esp_scf_update (const arma::mat& pos,
		       const arma::ivec& Zs,
		       arma::vec& Qs);

  // Embedded Many-Body Expansion or Binary Interaction Method
  double compute_embe (const arma::mat& pos,
		       const arma::ivec& Zs);

  // Many-Body Expansion
  double  compute_mbe (const arma::mat& pos,
		       const arma::ivec& Zs);

  // Polarization Energy
  double  compute_epol (const arma::mat& pos,
			const arma::ivec& Zs);

protected:
  double embe_monomer (const arma::mat& pos,
		       const arma::ivec& Zs);

  double embe_dimer (const arma::mat& pos,
		     const arma::ivec& Zs);

  double mbe_monomer (const arma::mat& pos,
		      const arma::ivec& Zs);

  double mbe_dimer (const arma::mat& pos,
		    const arma::ivec& Zs);

  double run_qcmol_esp (const std::vector<libint2::Atom>& atoms,
			const int& qm_chg,
			const std::vector<qcmol::QAtom>& atoms_Q,
			arma::mat& grads,
			arma::vec& qm_esp);

  double run_qcmol (const std::vector<libint2::Atom>& atoms,
		    const int& qm_chg,
		    const std::vector<qcmol::QAtom>& atoms_Q,
		    arma::mat& grads);

private:

  arma::vec m_enr_mon;
  arma::mat m_grd_mon;
  arma::mat m_grd_dim;
  arma::mat m_grd_pol;

  arma::vec m_esp_mol; // (r)esp charges of the molecule
  arma::vec m_esp_scf; // (r)esp charges in scf

  bool l_RHF;
  bool l_MP2;
  bool l_mbe;
  bool l_esp_scf;
  bool l_resp;

  int sys_me;
  int sys_nproc;
  int m_natom;
  int m_nwat;

  std::string m_basis;
};

} // namespace willow::pot

#endif

ext: hpp


text:
// All content Copyright (C) 2018 Genomics plc
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include "caller/region.hpp"
#include "caller/regionUtils.hpp"
#include "utils/flatten.hpp"
#include "ioTest/io/ioFixture.hpp"

using wecall::caller::Region;
using wecall::utils::Interval;
using wecall::caller::parseRegionString;

BOOST_FIXTURE_TEST_CASE( shouldExtractCorrectRegionsWhenNoneSuppliedOnCmdLine, wecall::test::FastaIndexFileFixture )
{
    auto actualRegions = wecall::utils::functional::flatten(
        wecall::caller::DataRegionsBuilder( {}, wecall::io::FastaIndex( indexFilename ) ).build() );

    // manual checks
    BOOST_CHECK_EQUAL( actualRegions.size(), 25 );
    BOOST_CHECK_EQUAL( actualRegions[0], Region( "1", 0, 249250621 ) );

    // automatic checks
    std::vector< Region > expectedRegions;
    for ( auto contigStr : fastaIndices[0]->standardContigs() )
    {
        expectedRegions.emplace_back( contigStr, fastaIndices[0]->contigs().at( contigStr ) );
    }
    BOOST_CHECK_EQUAL_COLLECTIONS( expectedRegions.begin(), expectedRegions.end(), actualRegions.begin(),
                                   actualRegions.end() );
}

BOOST_FIXTURE_TEST_CASE( shlouldExtractCorrectRegionsFromAList, wecall::test::FastaIndexFileFixture )
{
    auto actualRegions = wecall::utils::functional::flatten(
        wecall::caller::DataRegionsBuilder( {"1:2-3", "2:100-200"}, wecall::io::FastaIndex( indexFilename ) )
            .build() );
    std::vector< Region > expectedRegions = {Region( "1", 2, 3 ), Region( "2", 100, 200 )};

    BOOST_CHECK_EQUAL_COLLECTIONS( expectedRegions.begin(), expectedRegions.end(), actualRegions.begin(),
                                   actualRegions.end() );
}

ext: cpp

max_stars_repo_name: dylex/wecall

max_issues_repo_name: dylex/wecall

max_forks_repo_name: dylex/wecall


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

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BEAST_HTTP_IMPL_STATUS_IPP
#define BEAST_HTTP_IMPL_STATUS_IPP

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

namespace beast {
namespace http {
namespace detail {

template<class = void>
status
int_to_status(int v)
{
    switch(static_cast<status>(v))
    {
    // 1xx
    case status::continue_:
    case status::switching_protocols:
    case status::processing:
        BOOST_FALLTHROUGH;

    // 2xx
    case status::ok:
    case status::created:
    case status::accepted:
    case status::non_authoritative_information:
    case status::no_content:
    case status::reset_content:
    case status::partial_content:
    case status::multi_status:
    case status::already_reported:
    case status::im_used:
        BOOST_FALLTHROUGH;

    // 3xx
    case status::multiple_choices:
    case status::moved_permanently:
    case status::found:
    case status::see_other:
    case status::not_modified:
    case status::use_proxy:
    case status::temporary_redirect:
    case status::permanent_redirect:
        BOOST_FALLTHROUGH;

    // 4xx
    case status::bad_request:
    case status::unauthorized:
    case status::payment_required:
    case status::forbidden:
    case status::not_found:
    case status::method_not_allowed:
    case status::not_acceptable:
    case status::proxy_authentication_required:
    case status::request_timeout:
    case status::conflict:
    case status::gone:
    case status::length_required:
    case status::precondition_failed:
    case status::payload_too_large:
    case status::uri_too_long:
    case status::unsupported_media_type:
    case status::range_not_satisfiable:
    case status::expectation_failed:
    case status::misdirected_request:
    case status::unprocessable_entity:
    case status::locked:
    case status::failed_dependency:
    case status::upgrade_required:
    case status::precondition_required:
    case status::too_many_requests:
    case status::request_header_fields_too_large:
    case status::connection_closed_without_response:
    case status::unavailable_for_legal_reasons:
    case status::client_closed_request:
        BOOST_FALLTHROUGH;

    // 5xx
    case status::internal_server_error:
    case status::not_implemented:
    case status::bad_gateway:
    case status::service_unavailable:
    case status::gateway_timeout:
    case status::http_version_not_supported:
    case status::variant_also_negotiates:
    case status::insufficient_storage:
    case status::loop_detected:
    case status::not_extended:
    case status::network_authentication_required:
    case status::network_connect_timeout_error:
        return static_cast<status>(v);

    default:
        break;
    }
    return status::unknown;
}

template<class = void>
string_view
status_to_string(int v)
{
    switch(static_cast<status>(v))
    {
    // 1xx
    case status::continue_:                             return "Continue";
    case status::switching_protocols:                   return "Switching Protocols";
    case status::processing:                            return "Processing";

    // 2xx
    case status::ok:                                    return "OK";
    case status::created:                               return "Created";
    case status::accepted:                              return "Accepted";
    case status::non_authoritative_information:         return "Non-Authoritative Information";
    case status::no_content:                            return "No Content";
    case status::reset_content:                         return "Reset Content";
    case status::partial_content:                       return "Partial Content";
    case status::multi_status:                          return "Multi-Status";
    case status::already_reported:                      return "Already Reported";
    case status::im_used:                               return "IM Used";

    // 3xx
    case status::multiple_choices:                      return "Multiple Choices";
    case status::moved_permanently:                     return "Moved Permanently";
    case status::found:                                 return "Found";
    case status::see_other:                             return "See Other";
    case status::not_modified:                          return "Not Modified";
    case status::use_proxy:                             return "Use Proxy";
    case status::temporary_redirect:                    return "Temporary Redirect";
    case status::permanent_redirect:                    return "Permanent Redirect";

    // 4xx
    case status::bad_request:                           return "Bad Request";
    case status::unauthorized:                          return "Unauthorized";
    case status::payment_required:                      return "Payment Required";
    case status::forbidden:                             return "Forbidden";
    case status::not_found:                             return "Not Found";
    case status::method_not_allowed:                    return "Method Not Allowed";
    case status::not_acceptable:                        return "Not Acceptable";
    case status::proxy_authentication_required:         return "Proxy Authentication Required";
    case status::request_timeout:                       return "Request Timeout";
    case status::conflict:                              return "Conflict";
    case status::gone:                                  return "Gone";
    case status::length_required:                       return "Length Required";
    case status::precondition_failed:                   return "Precondition Failed";
    case status::payload_too_large:                     return "Payload Too Large";
    case status::uri_too_long:                          return "URI Too Long";
    case status::unsupported_media_type:                return "Unsupported Media Type";
    case status::range_not_satisfiable:                 return "Range Not Satisfiable";
    case status::expectation_failed:                    return "Expectation Failed";
    case status::misdirected_request:                   return "Misdirected Request";
    case status::unprocessable_entity:                  return "Unprocessable Entity";
    case status::locked:                                return "Locked";
    case status::failed_dependency:                     return "Failed Dependency";
    case status::upgrade_required:                      return "Upgrade Required";
    case status::precondition_required:                 return "Precondition Required";
    case status::too_many_requests:                     return "Too Many Requests";
    case status::request_header_fields_too_large:       return "Request Header Fields Too Large";
    case status::connection_closed_without_response:    return "Connection Closed Without Response";
    case status::unavailable_for_legal_reasons:         return "Unavailable For Legal Reasons";
    case status::client_closed_request:                 return "Client Closed Request";
    // 5xx
    case status::internal_server_error:                 return "Internal Server Error";
    case status::not_implemented:                       return "Not Implemented";
    case status::bad_gateway:                           return "Bad Gateway";
    case status::service_unavailable:                   return "Service Unavailable";
    case status::gateway_timeout:                       return "Gateway Timeout";
    case status::http_version_not_supported:            return "HTTP Version Not Supported";
    case status::variant_also_negotiates:               return "Variant Also Negotiates";
    case status::insufficient_storage:                  return "Insufficient Storage";
    case status::loop_detected:                         return "Loop Detected";
    case status::not_extended:                          return "Not Extended";
    case status::network_authentication_required:       return "Network Authentication Required";
    case status::network_connect_timeout_error:         return "Network Connect Timeout Error";

    default:
        break;
    }
    return "<unknown-status>";
}

template<class = void>
status_class
to_status_class(int v)
{
    switch(v / 100)
    {
    case 1: return status_class::informational;
    case 2: return status_class::successful;
    case 3: return status_class::redirection;
    case 4: return status_class::client_error;
    case 5: return status_class::server_error;
    default:
        break;
    }
    return status_class::unknown;
}

} // detail

inline
status
int_to_status(int v)
{
    return detail::int_to_status(v);
}

inline
status_class
to_status_class(int v)
{
    return detail::to_status_class(v);
}

inline
status_class
to_status_class(status v)
{
    return to_status_class(static_cast<int>(v));
}

inline
string_view
obsolete_reason(status v)
{
    return detail::status_to_string(
        static_cast<int>(v));
}

inline
std::ostream&
operator<<(std::ostream& os, status v)
{
    return os << obsolete_reason(v);
}

} // http
} // beast

#endif

ext: ipp

max_stars_repo_name: vinniefalco/rippled

max_issues_repo_name: vinniefalco/rippled

max_forks_repo_name: vinniefalco/rippled


text:
/** \file ElInfo1d.h */

#pragma once

#include <boost/numeric/mtl/mtl.hpp>

#include "ElInfo.hpp"

namespace AMDiS
{

  /** \ingroup Traverse
   * \brief
   * ElInfo class for 1-dimensional elements (\ref Line).
   */
  class ElInfo1d : public ElInfo
  {
  public:
    /// Constructor. Calls ElInfo's protected Constructor.
    ElInfo1d(Mesh* aMesh)
      : ElInfo(aMesh)
    {}

    /// 1-dimensional realisation of ElInfo's fillElInfo method.
    virtual void fillElInfo(int ichild, const ElInfo* elinfo_old) override;

    /// 1-dimensional realisation of ElInfo's fillMacroInfo method.
    virtual void fillMacroInfo(const MacroElement*) override;

    /// 1-dimensional realisation of ElInfo's worldToCoord method.
    virtual int worldToCoord(const WorldVector<double>& w, DimVec<double>& l) const override;

    /// 1-dimensional realisation of ElInfo's calcGrdLambda method.
    virtual double calcGrdLambda(DimVec<WorldVector<double>>& grd_lam) override;

    /// 1-dimensional realisation of ElInfo's getNormal method.
    virtual double getNormal(int side, WorldVector<double>& normal) const override;

    /// 1-dimensional realisation of ElInfo's getElementNormal method.
    virtual double getElementNormal(WorldVector<double>& normal) const override;

    int getSideOfNeighbour(int i) const
    {
      return (i + 1) % 2;
    }

    /// implements \ref Elnfo::getSubElemCoordsMat
    virtual mtl::dense2D<double>& getSubElemCoordsMat(int degree) const override;

  protected:
    static double mat_d1_val[2][2];

    static mtl::dense2D<double> mat_d1;

    static double mat_d1_left_val[2][2];

    static mtl::dense2D<double> mat_d1_left;

    static double mat_d1_right_val[2][2];

    static mtl::dense2D<double> mat_d1_right;

    static double mat_d2_val[3][3];

    static mtl::dense2D<double> mat_d2;

    static double mat_d2_left_val[3][3];

    static mtl::dense2D<double> mat_d2_left;

    static double mat_d2_right_val[3][3];

    static mtl::dense2D<double> mat_d2_right;
  };

} // end namespace AMDiS


text:
/*=============================================================================
    Copyright (c) 1998-2003 Joel de Guzman
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_MATCH_ATTR_TRAITS_IPP)
#define BOOST_SPIRIT_MATCH_ATTR_TRAITS_IPP

#include <boost/optional.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/is_same.hpp>

namespace boost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

namespace impl
{
    template <typename T>
    struct match_attr_traits
    {
        typedef typename
            boost::optional<T>::reference_const_type
        const_reference;

        //  case where src *IS* convertible to T (dest)
        template <typename T2>
        static void
        convert(boost::optional<T>& dest, T2 const& src, mpl::true_)
        {
            dest.reset(src);
        }

        //  case where src *IS NOT* convertible to T (dest)
        template <typename T2>
        static void
        convert(boost::optional<T>& dest, T2 const& /*src*/, mpl::false_)
        {
            dest.reset();
        }

        static void
        convert(boost::optional<T>& dest, nil_t/*src*/)
        {
            dest.reset();
        }

        template <typename T2>
        static void
        convert(boost::optional<T>& dest, T2 const& src)
        {
            convert(dest, src, is_convertible<T2, T>());
        }

        template <typename OtherMatchT>
        static void
        copy(boost::optional<T>& dest, OtherMatchT const& src)
        {
            if (src.has_valid_attribute())
                convert(dest, src.value());
        }

        template <typename OtherMatchT>
        static void
        assign(boost::optional<T>& dest, OtherMatchT const& src)
        {
            if (src.has_valid_attribute())
                convert(dest, src.value());
            else
                dest.reset();
        }

        // T is not reference
        template <typename ValueT>
        static void
        set_value(boost::optional<T>& dest, ValueT const& val, mpl::false_)
        {
            dest.reset(val);
        }

        // T is a reference
        template <typename ValueT>
        static void
        set_value(boost::optional<T>& dest, ValueT const& val, mpl::true_)
        {
            dest.get() = val;
        }
    };

}

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

}} // namespace boost::spirit::impl

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/* Copyright John Reid 2007, 2011
*/

#include "bio-pch.h"

#include "bio/defs.h"
//#define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP

#include "bio/biobase_likelihoods.h"
#include "bio/environment.h"
#include "bio/biobase_match.h"
#include "bio/biobase_db.h"
#include "bio/biobase_filter.h"
#include "bio/serialisable.h"
#include "bio/pssm_likelihood_cache.h"

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/filesystem/path.hpp>
using namespace boost;
namespace fs = boost::filesystem;

#include <fstream>
#include <numeric>
#include <iostream>
using namespace std;

#if BOOST_VERSION >= 104400
#define _FPC_NS ::boost::math::fpc
#else
# define _FPC_NS ::boost::test_tools
#endif

BIO_NS_START

/** Gets the index of a given score in [0,1]. */
size_t get_biobase_score_index(size_t size, float_t score)
{
	if (size == 0)
	{
		throw std::logic_error( "size == 0" );
	}

	if (0.0 > score)
	{
		throw std::logic_error( BIO_MAKE_STRING( "Score < 0: " << score ) );
	}

	if (score * 2 * size > 2 * size + 1)
	{
		throw std::logic_error( BIO_MAKE_STRING( "Score > 1 and a bit: " << score ) );
	}

	size_t idx = (size_t) (score * size);
	if (size == idx) //cater for a perfect match
	{
		--idx;
	}
	assert(0 <= idx && idx < size);

	return idx;
}

float_t
get_likelihood(const BiobaseLikelihoods & likelihoods, float_t score)
{
	return likelihoods[get_biobase_score_index(likelihoods.size(), score)];
}

/** Turn the counts of quantised scores into cumulative counts. */
BiobaseCounts
create_cumulative_from_counts(const BiobaseCounts & counts)
{
	BiobaseCounts result;
	size_t cumulative = 0;
	for (BiobaseCounts::const_iterator i = counts.begin();
		i != counts.end();
		++i)
	{
		cumulative += *i;
		result.push_back(cumulative);
	}
	return result;
}

/** Given a vector of counts, calculates the likelihoods. */
BiobaseLikelihoods
create_likelihoods_from_counts(const BiobaseCounts & counts)
{
	const size_t num_samples = std::accumulate(counts.begin(), counts.end(), 0);
	if (0 == num_samples)
	{
		throw std::logic_error( "No samples to generate likelihoods from" );
	}

	BiobaseLikelihoods result;
	for (BiobaseCounts::const_iterator i = counts.begin();
		counts.end() != i;
		++i)
	{
		result.push_back(((float_t) *i) / ((float_t) num_samples));
	}

	return result;
}

BiobaseLikelihoods
create_cumulative_likelihoods_from_non(const BiobaseLikelihoods & likelihoods)
{

	float_t cumulative = 0.0;
	unsigned idx = likelihoods.size();
	BiobaseLikelihoods result( idx );
	for (BiobaseLikelihoods::const_reverse_iterator i = likelihoods.rbegin();
		likelihoods.rend() != i;
		++i)
	{
		cumulative += *i;
		//adjust for rounding error
		cumulative = std::min( float_t( 1.0 ), cumulative );

		result[ --idx ] = cumulative;
	}
	BOOST_ASSERT(
		boost::test_tools::check_is_close(
			float_t( 1.0 ),
			cumulative,
			BIO_FPC_NS::percent_tolerance( 0.01f ) ) );

	return result;
}

unsigned
LikelihoodsCache::get_total_counts( const key_t & key ) const
{
	//look for the counts
	count_map_t::const_iterator c = counts.find( key );
	if ( counts.end() == c )
	{
		//we could not find the counts
		return 0;
	}

	//counts already in map
	return std::accumulate( c->second.begin(), c->second.end(), 0 );
}

BiobaseCounts *
LikelihoodsCache::get_counts(const key_t & key)
{
	BiobaseCounts * result = 0;

	//look for the counts
	count_map_t::iterator c = counts.find(key);
	if (counts.end() == c)
	{
		//we could not find the counts - insert a vector of 0's
		result =
			&(counts.insert(
				make_pair(
					key,
					BiobaseCounts(BioEnvironment::singleton().num_normalisation_quanta, 0))).first->second);
	}
	else
	{
		//counts already in map
		result = &(c->second); //retrieve them from map
	}

	//invalidate likelihoods
	background_likelihoods.erase(key);
	background_likelihoods_or_better.erase(key);
	binding_likelihoods.erase(key);
	binding_likelihoods_or_better.erase(key);

	return result;
}

const BiobaseLikelihoods *
LikelihoodsCache::get_score_likelihoods(
	const key_t & key,
	bool background,
	bool or_better)
{
	//which map are we going to look for the likelihoods in
	likelihood_map_t & map =
		background
			? (or_better ? background_likelihoods_or_better : background_likelihoods)
			: (or_better ? binding_likelihoods_or_better : binding_likelihoods);

	const BiobaseLikelihoods * result = 0;

	//look for the likelihoods
	likelihood_map_t::const_iterator l = map.find(key);
	if (map.end() == l)
	{
		//we could not find the likelihoods
		BiobaseLikelihoods likelihoods;

		if (or_better)
		{
			//we need cumulative likelihoods

			//first get the non-cumulative
			const BiobaseLikelihoods * non_cumulative = get_score_likelihoods(key, background, false);
			if (0 != non_cumulative)
			{
				//calculate the cumulative from the non.
				likelihoods = create_cumulative_likelihoods_from_non(*non_cumulative);
			}
		}
		else if (background)
		{
			//can we generate the likelihoods?
			count_map_t::const_iterator c = counts.find(key);
			if (counts.end() != c)
			{
				likelihoods = create_likelihoods_from_counts(c->second);
			}
		}
		else
		{
			likelihoods = *PssmLikelihoodCache::singleton().get_likelihoods(key);
		}

		//did we calculate any likelihoods?
		if (likelihoods.size() > 0)
		{
			//insert them
			std::pair<likelihood_map_t::iterator, bool> insert_result = map.insert(std::make_pair(key, likelihoods));
			assert(insert_result.second); //make sure it wasn't already in the map
			result = &(insert_result.first->second);
		}
	}
	else
	{
		//likelihoods already in map
		result = &(l->second); //retrieve normalisation from map
	}

	return result;
}

void
LikelihoodsCache::init_singleton()
{
	try
	{
		deserialise< false >(
			*this,
			fs::path(
				BioEnvironment::singleton().get_likelihoods_cache_file()
			)
		);
	}
	catch( const std::exception & ex )
	{
		std::cout << "LikelihoodsCache::init_singleton(): could not deserialise: " << ex.what() << std::endl;
	}
	catch( ... )
	{
		std::cout << "LikelihoodsCache::init_singleton(): could not deserialise: unknown error" << std::endl;
	}
}

void
LikelihoodsCache::update_counts(BiobaseDb & db, const seq_t & seq)
{
	//Normalising matrices
	quantise_counts(
		matrix_filter_it(db.get_matrices().begin(), db.get_matrices().end()),
		matrix_filter_it(db.get_matrices().end(), db.get_matrices().end()),
		seq);

	//Normalising sites
	quantise_counts(
		site_filter_it(db.get_sites().begin(), db.get_sites().end()),
		site_filter_it(db.get_sites().end(), db.get_sites().end()),
		seq);
}

bool
LikelihoodsCache::operator==(const LikelihoodsCache & rhs) const
{
	return counts == rhs.counts;
}

QuantisedScores::QuantisedScores( const BiobaseLikelihoods * likelihoods )
	: likelihoods( likelihoods )
{
}

float_t
QuantisedScores::operator()( float_t score ) const
{
	if( 0 == likelihoods )
	{
		throw std::logic_error( "Null pointer in QuantisedScores::operator()" );
	}

	return get_likelihood( *likelihoods, score );
}

QuantisedScores
get_biobase_quantised_scores(
	const LikelihoodsCache::key_t & key,
	bool background,
	bool or_better )
{
	return QuantisedScores( LikelihoodsCache::singleton().get_score_likelihoods( key, background, or_better ) );
}

BIO_NS_END

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
// --------------------------------------------------------------------------
//   SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing
// --------------------------------------------------------------------------
// Copyright The SmartPeak Team -- Novo Nordisk Foundation
// Center for Biosustainability, Technical University of Denmark 2018-2021.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey $
// $Authors: Douglas McCloskey $
// --------------------------------------------------------------------------

#include <SmartPeak/test_config.h>

#define BOOST_TEST_MODULE InputDataValidation test suite
#include <boost/test/included/unit_test.hpp>
#include <SmartPeak/io/InputDataValidation.h>
#include <SmartPeak/core/Filenames.h>
#include <SmartPeak/core/SequenceProcessor.h>

using namespace SmartPeak;
using namespace std;

const std::string main_dir = SMARTPEAK_GET_TEST_DATA_PATH("workflow_csv_files");

BOOST_AUTO_TEST_SUITE(inputdatavalidation)

BOOST_AUTO_TEST_CASE(fileExists)
{
  string pathname = SMARTPEAK_GET_TEST_DATA_PATH("OpenMSFile_standardsConcentrations_1.csv");
  BOOST_CHECK_EQUAL(InputDataValidation::fileExists(pathname), true);
  pathname = SMARTPEAK_GET_TEST_DATA_PATH("this_does_not_exist.csv");
  BOOST_CHECK_EQUAL(InputDataValidation::fileExists(pathname), false);
}

BOOST_AUTO_TEST_CASE(isValidFilename)
{
  string pathname = SMARTPEAK_GET_TEST_DATA_PATH("OpenMSFile_standardsConcentrations_1.csv");
  InputDataValidation::FilenameInfo v;
  v = InputDataValidation::isValidFilename(pathname, "some standards file");
  BOOST_CHECK_EQUAL(v.validity, InputDataValidation::FilenameInfo::valid);  // success
  pathname = SMARTPEAK_GET_TEST_DATA_PATH("this_does_not_exist.csv");
  v = InputDataValidation::isValidFilename(pathname, "a file that does not exist");
  BOOST_CHECK_EQUAL(v.validity, InputDataValidation::FilenameInfo::invalid); // failure
  pathname.clear();
  v = InputDataValidation::isValidFilename(pathname, "an empty pathname");
  BOOST_CHECK_EQUAL(v.validity, InputDataValidation::FilenameInfo::not_provided);  // not provided
}

BOOST_AUTO_TEST_CASE(validateNamesInStructures)
{
  const set<string> s1 = {"1", "2", "3"};
  const set<string> s2 = {"1", "2", "4"};
  const set<string> s3 = {"1", "2", "3", "4"};
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s1, s1, "", "", true), true); // check itself
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s1, s2, "", "", false), false); // s1 -> s2, "3" is missing
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s2, s1, "", "", false), false); // s1 -> s2, "4" is missing
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s2, s1, "", "", true), false); // s1 <-> s2, "3" and "4" are missing
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s1, s3, "", "", false), true); // s1 -> s3, no name is missing
  BOOST_CHECK_EQUAL(InputDataValidation::validateNamesInStructures(s1, s3, "", "", true), false); // s1 <-> s3, "4" is missing
}

BOOST_AUTO_TEST_CASE(findMissingNames)
{
  const set<string> s1 = {"1", "2", "3"};
  const set<string> s2 = {"1", "2", "4"};
  const set<string> s3 = {"1", "2", "3", "4"};
  set<string> result;

  result = InputDataValidation::findMissingNames(s1, s1);
  BOOST_CHECK_EQUAL(result.size(), 0);

  result = InputDataValidation::findMissingNames(s1, s2);
  BOOST_CHECK_EQUAL(result.size(), 1);
  BOOST_CHECK_EQUAL(result.count("3"), 1);

  result = InputDataValidation::findMissingNames(s2, s1);
  BOOST_CHECK_EQUAL(result.size(), 1);
  BOOST_CHECK_EQUAL(result.count("4"), 1);

  result = InputDataValidation::findMissingNames(s1, s3);
  BOOST_CHECK_EQUAL(result.size(), 0);

  result = InputDataValidation::findMissingNames(s3, s1);
  BOOST_CHECK_EQUAL(result.size(), 1);
  BOOST_CHECK_EQUAL(result.count("4"), 1);
}

BOOST_AUTO_TEST_CASE(sampleNamesAreConsistent)
{
  SequenceHandler sequenceHandler;
  Filenames filenames = Filenames::getDefaultStaticFilenames(main_dir);

  CreateSequence cs(sequenceHandler);
  cs.filenames_          = filenames;
  cs.delimiter          = ",";
  cs.checkConsistency   = false;
  cs.process();

  bool result;

  result = InputDataValidation::sampleNamesAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, true);

  filenames.sequence_csv_i = main_dir + "/sequence_missing.csv";
  sequenceHandler.clear();

  cs.filenames_ = filenames;
  cs.process();

  result = InputDataValidation::sampleNamesAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, false); // missing sample: fakeSample
}

BOOST_AUTO_TEST_CASE(componentNamesAreConsistent)
{
  SequenceHandler sequenceHandler;
  Filenames filenames = Filenames::getDefaultStaticFilenames(main_dir);

  CreateSequence cs(sequenceHandler);
  cs.filenames_          = filenames;
  cs.delimiter          = ",";
  cs.checkConsistency   = false;
  cs.process();

  bool result;

  result = InputDataValidation::componentNamesAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, true);

  filenames.traML_csv_i = main_dir + "/traML_missing.csv";
  // SequenceProcessor::createSequence(sequenceHandler, filenames, ",", false);
  RawDataHandler& rawData0 = sequenceHandler.getSequence().front().getRawData();
  LoadTransitions loadTransitions;
  loadTransitions.process(rawData0, {}, filenames);

  result = InputDataValidation::componentNamesAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, false);
}

BOOST_AUTO_TEST_CASE(componentNameGroupsAreConsistent)
{
  SequenceHandler sequenceHandler;
  Filenames filenames = Filenames::getDefaultStaticFilenames(main_dir);

  CreateSequence cs(sequenceHandler);
  cs.filenames_          = filenames;
  cs.delimiter          = ",";
  cs.checkConsistency   = false;
  cs.process();

  bool result;

  result = InputDataValidation::componentNameGroupsAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, true);

  filenames.traML_csv_i = main_dir + "/traML_missing.csv";
  //SequenceProcessor::createSequence(sequenceHandler, filenames, ",", false);
  RawDataHandler& rawData0 = sequenceHandler.getSequence().front().getRawData();
  LoadTransitions loadTransitions;
  loadTransitions.process(rawData0, {}, filenames);

  result = InputDataValidation::componentNameGroupsAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, false);
}

BOOST_AUTO_TEST_CASE(heavyComponentsAreConsistent)
{
  SequenceHandler sequenceHandler;
  Filenames filenames = Filenames::getDefaultStaticFilenames(main_dir);

  CreateSequence cs(sequenceHandler);
  cs.filenames_          = filenames;
  cs.delimiter          = ",";
  cs.checkConsistency   = false;
  cs.process();

  bool result;

  result = InputDataValidation::heavyComponentsAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, true);

  filenames.quantitationMethods_csv_i = main_dir + "/quantitationMethods_missing.csv";
  //SequenceProcessor::createSequence(sequenceHandler, filenames, ",", false);
  SequenceSegmentHandler& seqSeg0 = sequenceHandler.getSequenceSegments().front();
  LoadQuantitationMethods loadQuantitationMethods;
  loadQuantitationMethods.process(seqSeg0, SequenceHandler(), {}, filenames);

  result = InputDataValidation::heavyComponentsAreConsistent(sequenceHandler);
  BOOST_CHECK_EQUAL(result, false); // g6p.g6p_2.Heavy is missing
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ChristopherAbram/SmartPeak

max_issues_repo_name: ChristopherAbram/SmartPeak

max_forks_repo_name: ChristopherAbram/SmartPeak


text:
#include <nano_socket.h>
#include <messages.h>

#include <pubsub.h>
#include <pipeline.h>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <boost/program_options.hpp>
#include <boost/iostreams/copy.hpp>

#include <process.hpp>

#include <iostream>

namespace fs = boost::filesystem;
namespace po = boost::program_options;

using namespace kluster::transport;
using namespace kluster::messages;

class TmpFilesStorage
{
public:
  TmpFilesStorage(const FilesCollection& files)
  {
    m_tmpPath = fs::temp_directory_path() / "kluster" / fs::unique_path();

    std::wcout << "Tmp path " << m_tmpPath << std::endl;

    fs::create_directories(m_tmpPath);

    for (const FileData& file: files)
    {
      fs::path path = m_tmpPath / file.name;
      fs::ofstream stream {path, std::ios::out | std::ios::trunc | std::ios::binary};

      if (stream.is_open())
      {
		std::copy(file.data.begin(), file.data.end(), std::ostreambuf_iterator<char>(stream));
        stream.close();
        std::wcout << "Saved file to " << path.wstring() << std::endl;
      }
    }
  }

  ~TmpFilesStorage()
  {
    fs::remove_all(m_tmpPath);
  }

  std::string GetPath() const
  {
    return m_tmpPath.string();
  }

private:
  fs::path m_tmpPath;

};

class KlusterWorker
{
public:
  KlusterWorker()
  : m_jobSocket{NN_SUB}
  , m_tasksSocket{NN_PULL}
  , m_resultsSocket{NN_PUSH}
  {}

  void Join(const std::string& brokerAddress, int brokerPort) throw()
  {
    std::stringstream jobPubAddress;
    jobPubAddress << brokerAddress << ":" << brokerPort;
    m_jobSocket.Connect(jobPubAddress.str());
    m_jobSocket.SetSubscription();

    std::cout << "Connected job pub to " << jobPubAddress.str() << std::endl;

    std::stringstream taskSourceAddress;
    taskSourceAddress << brokerAddress << ":" << brokerPort+1;
    m_tasksSocket.Connect(taskSourceAddress.str());

    std::cout << "Tasks source to " << taskSourceAddress.str() << std::endl;

    std::stringstream taskResultsAddress;
    taskResultsAddress << brokerAddress << ":" << brokerPort+2;
    m_resultsSocket.Connect(taskResultsAddress.str());

    std::cout << "Tasks sink to " << taskResultsAddress.str() << std::endl;
  }

  void ProcessMessages()
  {
    std::cout << "Started message loop" << std::endl;
    for(;;)
    {
      try
      {
        NanoMessage message = m_jobSocket.Recv();
        std::cout << "Got message type " << message.header.type << std::endl;
        if (message.header.type == message_type::JobRequest)
        {
          std::wcout << "Got job request from " << message.header.senderNode << std::endl;
          JobRequestMessage jobRequest;

          if (message.GetMessageData(jobRequest))
          {
            DoJob(jobRequest);
          }
        }
      }
      catch(...)
      {

      }
    }
  }

  void DoJob(const JobRequestMessage& job) throw()
  {
    TmpFilesStorage jobFiles {job.jobFiles};

    NanoSocket* sockets[2] = {&m_jobSocket, &m_tasksSocket};
    for(;;)
    {
      std::pair<int, boost::optional<NanoMessage>> pollMessage = NanoSocket::Poll(sockets, 2, std::chrono::milliseconds(0));
      if (pollMessage.second)
      {
        const NanoMessage& message = *pollMessage.second;
        if (message.header.type == message_type::EndJob)
        {
          std::cout << "Got end job" << std::endl;
          break;
        }
        if (message.header.type == message_type::TaskRequest)
        {
          TaskRequestMessage request;
          message.GetMessageData(request);
          std::wcout << "Got task " << request.taskFile.name << std::endl;

          TaskResponseMessage response;
          response.jobId = request.jobId;

          if (!job.cmdLine.empty())
          {
            fs::path path {request.taskFile.name + L"_out"};

            FileData fileData;
            fileData.name = path.wstring();

            Process process {job.cmdLine, jobFiles.GetPath(),
            [&fileData](const char *bytes, size_t n)
            {
              std::copy(bytes, bytes+n, std::back_inserter(fileData.data));
            }};
            process.get_exit_status();

			std::wcout << "Prepared results " << fileData.name << ", size " << fileData.data.size() << std::endl;

            response.taskResults.push_back(fileData);

            /*fs::ifstream stream {path, std::ios::in | std::ios::binary};
            if (stream.is_open())
            {
              const auto size = fs::file_size(path);
              fileData.data.resize(size);
              stream.read(&fileData.data[0], size);
              stream.close();
            }*/
          }

          m_resultsSocket.Send(response);
        }
      }
    }
  }

private:
  NanoSocket m_jobSocket;
  NanoSocket m_tasksSocket;
  NanoSocket m_resultsSocket;
};

int main(int argc, const char** argv)
{
  po::options_description desc("Allowed options");
  desc.add_options()
      ("help", "produce help message")
      ("broker_ip", po::value<std::string>(), "broker ip")
      ("broker_port", po::value<int>(), "broker port")
      ("local_port", po::value<int>(), "local port");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
      std::cout << desc << "\n";
      return 1;
  }

  std::string brokerAddress = "tcp://127.0.0.1";
  if (vm.count("broker_ip"))
  {
      brokerAddress = vm["broker_ip"].as<std::string>();
  }
  int brokerPort = 12346;
  if (vm.count("broker_port"))
  {
      brokerPort = vm["broker_port"].as<int>();
  }
  std::cout << "Broker at " << brokerAddress << ":" << brokerPort << std::endl;

  KlusterWorker kw;
  kw.Join(brokerAddress, brokerPort);
  kw.ProcessMessages();

  return 0;
}

max_stars_repo_name: variar/kluster

max_issues_repo_name: variar/kluster

max_forks_repo_name: variar/kluster


text:
//------------------------------------------------------------------------------
/*
    Portions of this file are from Vpallab: https://github.com/vpallabs
    Copyright (c) 2013 - 2014 - Vpallab.com.
    Please visit http://www.vpallab.com/

    This file is part of Beast: https://github.com/vinniefalco/Beast
    Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <beast/http/basic_parser.h>
#include <beast/http/impl/joyent_parser.h>
#include <beast/http/rfc2616.h>
#include <beast/utility/noexcept.h>
#include <boost/system/error_code.hpp>

namespace beast {
namespace http {

boost::system::error_category const&
message_category() noexcept
{
    class message_category_t : public boost::system::error_category
    {
    public:
        const char*
        name() const noexcept override
        {
            return "http::message";
        }

        std::string
        message (int ev) const override
        {
            return joyent::http_errno_description (
                static_cast<joyent::http_errno>(ev));
        }

        boost::system::error_condition
        default_error_condition (int ev) const noexcept override
        {
            return boost::system::error_condition (ev, *this);
        }

        bool
        equivalent (int ev, boost::system::error_condition const& condition
            ) const noexcept override
        {
            return condition.value() == ev &&
                &condition.category() == this;
        }

        bool
        equivalent (boost::system::error_code const& error,
            int ev) const noexcept override
        {
            return error.value() == ev &&
                &error.category() == this;
        }
    };

    static message_category_t cat;
    return cat;
}

//------------------------------------------------------------------------------

basic_parser::basic_parser (bool request) noexcept
{
    static_assert (sizeof(joyent::http_parser) == sizeof(state_t),
        "state_t size must match http_parser size");

    static_assert (sizeof(joyent::http_parser_settings) == sizeof(hooks_t),
        "hooks_t size must match http_parser_settings size");

    auto s (reinterpret_cast <joyent::http_parser*> (&state_));
    s->data = this;

    auto h (reinterpret_cast <joyent::http_parser_settings*> (&hooks_));
    h->on_message_begin     = &basic_parser::cb_message_start;
    h->on_url               = &basic_parser::cb_url;
    h->on_status            = &basic_parser::cb_status;
    h->on_header_field      = &basic_parser::cb_header_field;
    h->on_header_value      = &basic_parser::cb_header_value;
    h->on_headers_complete  = &basic_parser::cb_headers_complete;
    h->on_body              = &basic_parser::cb_body;
    h->on_message_complete  = &basic_parser::cb_message_complete;

    joyent::http_parser_init (s, request
        ? joyent::http_parser_type::HTTP_REQUEST
        : joyent::http_parser_type::HTTP_RESPONSE);
}

basic_parser&
basic_parser::operator= (basic_parser&& other)
{
    *reinterpret_cast<joyent::http_parser*>(&state_) =
        *reinterpret_cast<joyent::http_parser*>(&other.state_);
    reinterpret_cast<joyent::http_parser*>(&state_)->data = this;
    complete_ = other.complete_;
    url_ = std::move (other.url_);
    status_ = std::move (other.status_);
    field_ = std::move (other.field_);
    value_ = std::move (other.value_);
    return *this;
}

basic_parser::error_code
basic_parser::error() const noexcept
{
    auto s (reinterpret_cast <joyent::http_parser const*> (&state_));
    return error_code{static_cast<int>(s->http_errno), message_category()};
}

std::pair <bool, std::size_t>
basic_parser::write (void const* data, std::size_t bytes)
{
    std::pair <bool, std::size_t> result (false, 0);
    auto s (reinterpret_cast <joyent::http_parser*> (&state_));
    auto h (reinterpret_cast <joyent::http_parser_settings const*> (&hooks_));
    result.second = joyent::http_parser_execute (s, h,
        static_cast <const char*> (data), bytes);
    result.first = s->http_errno == 0;
    return result;
}

bool
basic_parser::write_eof()
{
    auto s (reinterpret_cast <joyent::http_parser*> (&state_));
    auto h (reinterpret_cast <joyent::http_parser_settings const*> (&hooks_));
    joyent::http_parser_execute (s, h, nullptr, 0);
    return s->http_errno == 0;
}

//------------------------------------------------------------------------------

void
basic_parser::check_header()
{
    if (! value_.empty())
    {
        rfc2616::trim_right_in_place (value_);
        on_field (field_, value_);
        field_.clear();
        value_.clear();
    }
}

int
basic_parser::do_message_start ()
{
    complete_ = false;
    url_.clear();
    status_.clear();
    field_.clear();
    value_.clear();
    on_start();
    return 0;
}

int
basic_parser::do_url (char const* in, std::size_t bytes)
{
    url_.append (static_cast <char const*> (in), bytes);
    return 0;
}

int
basic_parser::do_status (char const* in, std::size_t bytes)
{
    status_.append (static_cast <char const*> (in), bytes);
    return 0;
}

int
basic_parser::do_header_field (char const* in, std::size_t bytes)
{
    check_header();
    field_.append (static_cast <char const*> (in), bytes);
    return 0;
}

int
basic_parser::do_header_value (char const* in, std::size_t bytes)
{
    value_.append (static_cast <char const*> (in), bytes);
    return 0;
}

/*  Called when all the headers are complete but before
    the content body, if present.
    Returning 1 from here tells the joyent parser
    that the message has no body (e.g. a HEAD request).
*/
int
basic_parser::do_headers_complete()
{
    check_header();
    auto const p (reinterpret_cast <joyent::http_parser const*> (&state_));
    bool const keep_alive (joyent::http_should_keep_alive (p) != 0);
    if (p->type == joyent::http_parser_type::HTTP_REQUEST)
        return on_request (joyent::convert_http_method (
            joyent::http_method(p->method)), url_,
                p->http_major, p->http_minor, keep_alive, p->upgrade) ? 0 : 1;
    return on_response (p->status_code, status_,
        p->http_major, p->http_minor, keep_alive, p->upgrade) ? 0 : 1;
}

/*  Called repeatedly for the content body. The passed buffer
    has already had the transfer-encoding removed.
*/
int
basic_parser::do_body (char const* in, std::size_t bytes)
{
    on_body (in, bytes);
    return 0;
}

/* Called when the both the headers and content body (if any) are complete. */
int
basic_parser::do_message_complete ()
{
    complete_ = true;
    on_complete();
    return 0;
}

//------------------------------------------------------------------------------

int
basic_parser::cb_message_start (joyent::http_parser* p)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_message_start();
}

int
basic_parser::cb_url (joyent::http_parser* p,
    char const* in, std::size_t bytes)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_url (in, bytes);
}

int
basic_parser::cb_status (joyent::http_parser* p,
    char const* in, std::size_t bytes)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_status (in, bytes);
}

int
basic_parser::cb_header_field (joyent::http_parser* p,
    char const* in, std::size_t bytes)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_header_field (in, bytes);
}

int
basic_parser::cb_header_value (joyent::http_parser* p,
    char const* in, std::size_t bytes)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_header_value (in, bytes);
}

int
basic_parser::cb_headers_complete (joyent::http_parser* p)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_headers_complete();
}

int
basic_parser::cb_body (joyent::http_parser* p,
    char const* in, std::size_t bytes)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_body (
            in, bytes);
}

int
basic_parser::cb_message_complete (joyent::http_parser* p)
{
    return reinterpret_cast <basic_parser*> (
        p->data)->do_message_complete();
}

} // http
} // beast


text:
#pragma once

// CUT begin
#include <boost/multiprecision/cpp_int.hpp>
using mpint = boost::multiprecision::cpp_int;


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2015, Oracle and/or its affiliates.

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_INSERT_TOUCH_INTERIOR_TURNS_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_INSERT_TOUCH_INTERIOR_TURNS_HPP

#include <deque>
#include <iterator>
#include <set>

#include <boost/range.hpp>

#include <boost/geometry/core/assert.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/policies/robustness/segment_ratio.hpp>

#include <boost/geometry/algorithms/append.hpp>
#include <boost/geometry/algorithms/clear.hpp>
#include <boost/geometry/algorithms/convert.hpp>

#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>
#include <boost/geometry/algorithms/detail/overlay/self_turn_points.hpp>
#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>

namespace boost { namespace geometry
{

namespace detail { namespace overlay
{

struct self_turns_no_interrupt_policy
{
    static bool const enabled = false;
    static bool const has_intersections = false;

    template <typename Range>
    static inline bool apply(Range const&)
    {
        return false;
    }
};

template <typename Turn>
static inline
typename Turn::turn_operation_type get_correct_op(Turn const& t)
{
    return
        (t.operations[0].fraction.is_zero()
         || t.operations[0].fraction.is_one())
        ?
        t.operations[1]
        :
        t.operations[0]
        ;
}

template <typename MAA_Turn>
struct maa_turn_less
{
    bool operator()(MAA_Turn const& t1, MAA_Turn const& t2) const
    {
        BOOST_GEOMETRY_ASSERT(t1.method == method_touch_interior);
        BOOST_GEOMETRY_ASSERT(t2.method == method_touch_interior);

        typename MAA_Turn::turn_operation_type op1 = get_correct_op(t1);
        typename MAA_Turn::turn_operation_type op2 = get_correct_op(t2);

        BOOST_GEOMETRY_ASSERT(! op1.fraction.is_zero()
                              && ! op1.fraction.is_one());
        BOOST_GEOMETRY_ASSERT(! op2.fraction.is_zero()
                              && ! op2.fraction.is_one());

        if (op1.seg_id.multi_index != op2.seg_id.multi_index)
        {
            return op1.seg_id.multi_index < op2.seg_id.multi_index;
        }
        if (op1.seg_id.ring_index != op2.seg_id.ring_index)
        {
            return op1.seg_id.ring_index < op2.seg_id.ring_index;
        }
        if (op1.seg_id.segment_index != op2.seg_id.segment_index)
        {
            return op1.seg_id.segment_index < op2.seg_id.segment_index;
        }
        return op1.fraction < op2.fraction;
    }
};

template <typename Areal, typename TagIn = typename tag<Areal>::type>
struct insert_maa_turns
{};

template <typename Box>
struct insert_maa_turns<Box, box_tag>
{
    template <typename BoxOut, typename TurnIterator>
    static inline TurnIterator apply(Box const& box,
                                     TurnIterator first,
                                     TurnIterator,
                                     BoxOut& box_out,
                                     int = -1,
                                     int = -1)
    {
        geometry::convert(box, box_out);
        return first;
    }
};

template <typename Ring>
struct insert_maa_turns<Ring, ring_tag>
{
    template <typename RingOut, typename TurnIterator>
    static inline TurnIterator apply(Ring const& ring,
                                     TurnIterator first,
                                     TurnIterator last,
                                     RingOut& ring_out,
                                     int ring_index = -1,
                                     int multi_index = -1)
    {
        typedef typename boost::range_iterator
            <
                Ring const
            >::type iterator_type;

        typedef typename std::iterator_traits
            <
                TurnIterator
            >::value_type::turn_operation_type operation_type;

        typename boost::range_size<Ring>::type point_index = 0;
        for (iterator_type it = boost::begin(ring);
             it != boost::end(ring);
             ++it, ++point_index)
        {
            geometry::append(ring_out, ring[point_index]);
            while (first != last)
            {
                operation_type op = get_correct_op(*first);
                if (op.seg_id.multi_index == multi_index
                    &&
                    op.seg_id.ring_index == ring_index
                    &&
                    op.seg_id.segment_index
                    == static_cast<signed_size_type>(point_index))
                {
                    geometry::append(ring_out, first->point);
                    ++first;
                }
                else
                {
                    break;
                }
            }
        }
        return first;
    }
};

template <typename Polygon>
struct insert_maa_turns<Polygon, polygon_tag>
{
    template
    <
        typename Ring,
        typename RingIterator,
        typename PolygonOut,
        typename TurnIterator
    >
    static inline
    TurnIterator do_interior_rings(RingIterator rings_first,
                                   RingIterator rings_last,
                                   TurnIterator first,
                                   TurnIterator last,
                                   PolygonOut& polygon_out,
                                   int multi_index)
    {
        typename geometry::ring_type<PolygonOut>::type ring_out;
        int ring_index = 0;
        for (RingIterator rit = rings_first;
             rit != rings_last;
             ++rit, ++ring_index)
        {
            geometry::clear(ring_out);
            first = insert_maa_turns<Ring>::apply(*rit,
                                                  first,
                                                  last,
                                                  ring_out,
                                                  ring_index,
                                                  multi_index);
            geometry::traits::push_back
                <
                    typename boost::remove_reference
                        <
                            typename traits::interior_mutable_type
                                <
                                    PolygonOut
                                >::type
                        >::type
                >::apply(geometry::interior_rings(polygon_out), ring_out);
        }
        return first;
    }

    template
    <
        typename Ring,
        typename InteriorRings,
        typename PolygonOut,
        typename TurnIterator
    >
    static inline
    TurnIterator do_interior_rings(InteriorRings const& irings,
                                   TurnIterator first,
                                   TurnIterator last,
                                   PolygonOut& polygon_out,
                                   int multi_index)
    {
        return do_interior_rings<Ring>(boost::begin(irings),
                                       boost::end(irings),
                                       first,
                                       last,
                                       polygon_out,
                                       multi_index);
    }

    template <typename PolygonOut, typename TurnIterator>
    static inline TurnIterator apply(Polygon const& polygon,
                                     TurnIterator first,
                                     TurnIterator last,
                                     PolygonOut& polygon_out,
                                     int multi_index = -1)
    {
        typedef typename geometry::ring_type<Polygon>::type ring_type;

        typename geometry::ring_type<PolygonOut>::type ring_out;

        // do exterior ring
        first = insert_maa_turns
            <
                ring_type
            >::apply(exterior_ring(polygon),
                     first,
                     last,
                     ring_out,
                     -1,
                     multi_index);
        geometry::append(polygon_out, ring_out, -1);

        return do_interior_rings<ring_type>(interior_rings(polygon),
                                            first,
                                            last,
                                            polygon_out,
                                            multi_index);
    }
};

template <typename MultiPolygon>
struct insert_maa_turns<MultiPolygon, multi_polygon_tag>
{
    template <typename MultiPolygonOut, typename TurnIterator>
    static inline TurnIterator apply(MultiPolygon const& multi_polygon,
                                     TurnIterator first,
                                     TurnIterator last,
                                     MultiPolygonOut& multi_polygon_out)
    {
        typedef typename boost::range_iterator
            <
                MultiPolygon const
            >::type iterator_type;

        typename boost::range_value<MultiPolygonOut>::type polygon_out;

        int polygon_index = 0;
        for (iterator_type it = boost::begin(multi_polygon);
             it != boost::end(multi_polygon);
             ++it, ++polygon_index)
        {
            geometry::clear(polygon_out);

            first = insert_maa_turns
                <
                    typename boost::range_value<MultiPolygon>::type
                >::apply(*it, first, last, polygon_out, polygon_index);

            geometry::traits::push_back
                <
                    MultiPolygonOut
                >::apply(multi_polygon_out, polygon_out);
        }
        return first;
    }
};

// returns true if the input geometry has been modified (in which case
// the modified geometry is stored in geometry_out), false otherwise
template <typename GeometryIn, typename GeometryOut, typename RobustPolicy>
inline bool insert_touch_interior_turns(GeometryIn const& geometry_in,
                                        GeometryOut& geometry_out,
                                        RobustPolicy const& robust_policy)
{
    typedef turn_info
        <
            typename point_type<GeometryIn>::type,
            typename geometry::segment_ratio_type
                <
                    typename point_type<GeometryIn>::type, RobustPolicy
                >::type
        > turn_type;

    typedef std::deque<turn_type> turns_container_type;

    self_turns_no_interrupt_policy interrupt_policy;

    // compute self turns
    turns_container_type turns;
    geometry::self_turns
        <
            get_turn_info<assign_null_policy>
        >(geometry_in, robust_policy, turns, interrupt_policy);

    // select touch interior turns
    typedef std::set<turn_type, maa_turn_less<turn_type> > maa_turn_set;

    maa_turn_set maa_turns;
    for (typename turns_container_type::const_iterator it = turns.begin();
         it != turns.end();
         ++it)
    {
        if (it->method == method_touch_interior)
        {
            maa_turns.insert(*it);
        }
    }

    // if not such turns indicate that the input geometry need not change
    if (maa_turns.empty())
    {
        return false;
    }

    // insert the touch interior turns
    insert_maa_turns
        <
            GeometryIn
        >::apply(geometry_in, maa_turns.begin(), maa_turns.end(), geometry_out);

    // return that the input geometry needed change
    return true;
}

}} // detail::overlay

}} // boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_INSERT_TOUCH_INTERIOR_TURNS_HPP


text:
//
// Created by dchansen on 3/25/19.
//

#include "SocketStreamBuf.h"

#include "Types.h"

#include <boost/asio.hpp>
namespace {
    using boost::asio::ip::tcp;

    std::unique_ptr<tcp::socket> connect_socket(
        const std::string& host, const std::string& service, boost::asio::io_service& context) {
        tcp::resolver resolver{ context };
        auto endpoint = *resolver.resolve(tcp::resolver::query(host, service));
        auto socket   = std::make_unique<tcp::socket>(context);
        socket->connect(endpoint);
        return std::move(socket);
    }

    class SocketStreamBuf : public std::streambuf {
    public:
        explicit SocketStreamBuf(std::unique_ptr<boost::asio::ip::tcp::socket> socket, size_t buffer_size = 1024);

    protected:
        std::streamsize xsputn(const char_type* data, std::streamsize length) override;

        int sync() override;
        int underflow() override;
        int overflow(int ch = traits_type::eof()) override;

    private:
        std::unique_ptr<boost::asio::ip::tcp::socket> socket;
        std::vector<char> input_buffer;
        std::vector<char> output_buffer;

        /* Other members */
    };

    int SocketStreamBuf::sync() {
        return this->overflow() != traits_type::eof() ? 0 : -1;
    }
    int SocketStreamBuf::underflow() {

        auto elements_read = socket->read_some(boost::asio::buffer(this->eback(), input_buffer.size()));

        this->setg(this->eback(), this->eback(), this->eback() + elements_read);
        return traits_type::to_int_type(*this->gptr());
    }
    int SocketStreamBuf::overflow(int ch) {
        if (this->pptr() != this->pbase()) {
            boost::asio::write(*socket, boost::asio::buffer(this->pbase(), std::distance(this->pbase(), this->pptr())));
            this->setp(this->pbase(), this->epptr());
        }
        if (ch != traits_type::eof()) {
            this->sputc(ch);
        }

        return 0;
    }

    std::streamsize SocketStreamBuf::xsputn(const char* data, std::streamsize length) {
        this->overflow();
        return boost::asio::write(*socket, boost::asio::buffer(data, length));
    }
    SocketStreamBuf::SocketStreamBuf(std::unique_ptr<boost::asio::ip::tcp::socket> socket, size_t buffer_size)
        : socket(std::move(socket)), input_buffer(buffer_size), output_buffer(buffer_size) {
        this->setg(input_buffer.data(), input_buffer.data() + buffer_size, input_buffer.data() + buffer_size);
        this->setp(output_buffer.data(), output_buffer.data() + buffer_size);
    }

    using namespace Gadgetron::Connection;
    class SocketStream : public std::iostream {
    public:
        explicit SocketStream(std::unique_ptr<boost::asio::ip::tcp::socket> socket)
            : std::iostream(new SocketStreamBuf(std::move(socket))) {
            buffer = std::unique_ptr<SocketStreamBuf>(static_cast<SocketStreamBuf*>(this->rdbuf()));
        }

        SocketStream(const std::string& host, const std::string& service,
            std::shared_ptr<boost::asio::io_service> io_service = std::make_shared<boost::asio::io_service>())
            : SocketStream(connect_socket(host, service, *io_service)) {
            this->io_service = io_service;
        }

        ~SocketStream() override = default;

    private:
        std::shared_ptr<boost::asio::io_service> io_service;
        std::unique_ptr<SocketStreamBuf> buffer;
    };
}

std::unique_ptr<std::iostream> Gadgetron::Connection::stream_from_socket(
    std::unique_ptr<boost::asio::ip::tcp::socket> socket) {
    return std::make_unique<SocketStream>(std::move(socket));
}

std::unique_ptr<std::iostream> Gadgetron::Connection::remote_stream(
    const std::string& host, const std::string& service) {
    return std::make_unique<SocketStream>(host, service);
}

max_stars_repo_name: roopchansinghv/gadgetron