text:
#ifndef EMBEDPYTHON_HPP_INCLUDED
#define EMBEDPYTHON_HPP_INCLUDED

#include <boost/python.hpp>

////////////////////////////////////////////////////////////////////////
// Declarations
////////////////////////////////////////////////////////////////////////

// routines

void initializePython();

#endif  // EMBEDPYTHON_HPP_INCLUDED

ext: hpp

max_stars_repo_name: pavoljuhas/liga

max_issues_repo_name: pavoljuhas/liga

max_forks_repo_name: pavoljuhas/liga


text:
/* Copyright (c) 2015, 2020, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License, version 2.0,
   as published by the Free Software Foundation.

   This program is also distributed with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have included with MySQL.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License, version 2.0, for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include "sql/item_geofunc_internal.h"

#include <algorithm>
#include <cstring>
#include <iterator>
#include <memory>

#include <boost/concept/usage.hpp>
#include <boost/geometry/algorithms/centroid.hpp>
#include <boost/geometry/algorithms/is_valid.hpp>
#include <boost/geometry/algorithms/overlaps.hpp>
#include <boost/geometry/core/exception.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/index/predicates.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/iterator/iterator_facade.hpp>

#include "m_ctype.h"
#include "m_string.h"
#include "my_byteorder.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "sql/current_thd.h"
#include "sql/dd/cache/dictionary_client.h"
#include "sql/item_func.h"
#include "sql/mdl.h"
#include "sql/parse_location.h"  // POS
#include "sql/sql_class.h"       // THD
#include "sql/srs_fetcher.h"
#include "sql/system_variables.h"
#include "sql_string.h"
#include "template_utils.h"

namespace dd {
class Spatial_reference_system;
}  // namespace dd

bool Srs_fetcher::lock(gis::srid_t srid, enum_mdl_type lock_type) {
  DBUG_TRACE;
  DBUG_ASSERT(srid != 0);

  char id_str[11];  // uint32 => max 10 digits + \0
  longlong10_to_str(srid, id_str, 10);

  MDL_request mdl_request;
  mdl_request.init_with_source(MDL_key::SRID, "", id_str, lock_type,
                               MDL_TRANSACTION, __FILE__, __LINE__);
  if (m_thd->mdl_context.acquire_lock(&mdl_request,
                                      m_thd->variables.lock_wait_timeout)) {
    /* purecov: begin inspected */
    // If locking fails, an error has already been flagged.
    return true;
    /* purecov: end */
  }

  return false;
}

bool Srs_fetcher::acquire(gis::srid_t srid,
                          const dd::Spatial_reference_system **srs) {
  if (lock(srid, MDL_SHARED_READ)) return true; /* purecov: inspected */

  if (m_thd->dd_client()->acquire(srid, srs))
    return true; /* purecov: inspected */
  return false;
}

bool Srs_fetcher::acquire_for_modification(gis::srid_t srid,
                                           dd::Spatial_reference_system **srs) {
  if (lock(srid, MDL_EXCLUSIVE)) return true; /* purecov: inspected */

  if (m_thd->dd_client()->acquire_for_modification(srid, srs))
    return true; /* purecov: inspected */
  return false;
}

bool Srs_fetcher::srs_exists(THD *thd, gis::srid_t srid, bool *exists) {
  DBUG_ASSERT(exists);
  std::unique_ptr<dd::cache::Dictionary_client::Auto_releaser> releaser(
      new dd::cache::Dictionary_client::Auto_releaser(thd->dd_client()));
  Srs_fetcher fetcher(thd);
  const dd::Spatial_reference_system *srs = nullptr;
  if (fetcher.acquire(srid, &srs)) return true; /* purecov: inspected */
  *exists = (srs != nullptr);
  return false;
}

template <typename Coordsys>
void BG_geometry_collection::merge_components(bool *pnull_value) {
  if (is_comp_no_overlapped()) return;

  POS pos;
  Item_func_st_union ifsu(pos, nullptr, nullptr);
  bool do_again = true;
  uint32 last_composition[6] = {0}, num_unchanged_composition = 0;
  size_t last_num_geos = 0;

  /*
    After each merge_one_run call, see whether the two indicators change:
    1. total number of geometry components;
    2. total number of each of the 6 types of geometries

    If they don't change for N*N/4 times, break out of the loop. Here N is
    the total number of geometry components.

    There is the rationale:

    Given a geometry collection, it's likely that one effective merge_one_run
    merges a polygon P and the linestring that crosses it (L) to a
    polygon P'(the same one) and another linestring L', the 2 indicators above
    don't change but the merge is actually done. If we merge P'
    and L' again, they should not be considered cross, but given certain data
    BG somehow believes L` still crosses P` even the P and P` are valid, and
    it will give us a L'' and P'' which is different from L' and P'
    respectively, and L'' is still considered crossing P'',
    hence the loop here never breaks out.

    If the collection has N components, and we have X [multi]linestrings and
    N-X polygons, the number of pairs that can be merged is Y = X * (N-X),
    so the largest Y is N*N/4. If the above 2 indicators stay unchanged more
    than N*N/4 times the loop runs, we believe all possible combinations in
    the collection are enumerated and no effective merge is being done any more.

    Note that the L'' and P'' above is different from L' and P' so we can't
    compare GEOMETRY byte string, and geometric comparison is expensive and may
    still compare unequal and we would still be stuck in the endless loop.
  */
  while (!*pnull_value && do_again) {
    do_again = merge_one_run<Coordsys>(&ifsu, pnull_value);
    if (!*pnull_value && do_again) {
      const size_t num_geos = m_geos.size();
      uint32 composition[6] = {0};

      for (size_t i = 0; i < num_geos; ++i)
        composition[m_geos[i]->get_type() - 1]++;

      if (num_geos != last_num_geos ||
          memcmp(composition, last_composition, sizeof(composition))) {
        memcpy(last_composition, composition, sizeof(composition));
        last_num_geos = num_geos;
        num_unchanged_composition = 0;
      } else
        num_unchanged_composition++;

      if (num_unchanged_composition > (last_num_geos * last_num_geos / 4 + 2))
        break;
    }
  }
}

// Explicit template instantiation
template void BG_geometry_collection::merge_components<
    boost::geometry::cs::cartesian>(bool *);

template <typename Coordsys>
inline bool linestring_overlaps_polygon_outerring(const Gis_line_string &ls,
                                                  const Gis_polygon &plgn) {
  Gis_polygon_ring &oring = plgn.outer();
  Gis_line_string ls2(oring.get_ptr(), oring.get_nbytes(), oring.get_flags(),
                      oring.get_srid());
  return boost::geometry::overlaps(ls, ls2);
}

template <typename Coordsys>
bool linear_areal_intersect_infinite(Geometry *g1, Geometry *g2,
                                     bool *pnull_value) {
  bool res = false;

  /*
    If crosses check succeeds, make sure g2 is a valid [multi]polygon, invalid
    ones can be accepted by BG and the cross check would be considered true,
    we should reject such result and return false in this case.
  */
  if (Item_func_spatial_rel::bg_geo_relation_check(
          g1, g2, Item_func::SP_CROSSES_FUNC, pnull_value) &&
      !*pnull_value) {
    Geometry::wkbType g2_type = g2->get_type();
    if (g2_type == Geometry::wkb_polygon) {
      Gis_polygon plgn(g2->get_data_ptr(), g2->get_data_size(), g2->get_flags(),
                       g2->get_srid());
      res = bg::is_valid(plgn);
    } else if (g2_type == Geometry::wkb_multipolygon) {
      Gis_multi_polygon mplgn(g2->get_data_ptr(), g2->get_data_size(),
                              g2->get_flags(), g2->get_srid());
      res = bg::is_valid(mplgn);
    } else
      DBUG_ASSERT(false);

    return res;
  }

  if (*pnull_value) return false;

  if (g1->get_type() == Geometry::wkb_linestring) {
    Gis_line_string ls(g1->get_data_ptr(), g1->get_data_size(), g1->get_flags(),
                       g1->get_srid());
    if (g2->get_type() == Geometry::wkb_polygon) {
      Gis_polygon plgn(g2->get_data_ptr(), g2->get_data_size(), g2->get_flags(),
                       g2->get_srid());
      res = linestring_overlaps_polygon_outerring<Coordsys>(ls, plgn);
    } else {
      Gis_multi_polygon mplgn(g2->get_data_ptr(), g2->get_data_size(),
                              g2->get_flags(), g2->get_srid());
      for (size_t i = 0; i < mplgn.size(); i++) {
        if (linestring_overlaps_polygon_outerring<Coordsys>(ls, mplgn[i]))
          return true;
      }
    }
  } else {
    Gis_multi_line_string mls(g1->get_data_ptr(), g1->get_data_size(),
                              g1->get_flags(), g1->get_srid());
    if (g2->get_type() == Geometry::wkb_polygon) {
      Gis_polygon plgn(g2->get_data_ptr(), g2->get_data_size(), g2->get_flags(),
                       g2->get_srid());
      for (size_t i = 0; i < mls.size(); i++) {
        if (linestring_overlaps_polygon_outerring<Coordsys>(mls[i], plgn))
          return true;
      }
    } else {
      Gis_multi_polygon mplgn(g2->get_data_ptr(), g2->get_data_size(),
                              g2->get_flags(), g2->get_srid());
      for (size_t j = 0; j < mls.size(); j++) {
        for (size_t i = 0; i < mplgn.size(); i++) {
          if (linestring_overlaps_polygon_outerring<Coordsys>(mls[j], mplgn[i]))
            return true;
        }
      }
    }
  }

  return res;
}

/**
  Create this class for exception safety --- destroy the objects referenced
  by the pointers in the set when destroying the container.
 */
template <typename T>
class Pointer_vector : public std::vector<T *> {
  typedef std::vector<T *> parent;

 public:
  ~Pointer_vector() {
    for (typename parent::iterator i = this->begin(); i != this->end(); ++i)
      delete (*i);
  }
};

// A unary predicate to locate a target Geometry object pointer from a sequence.
class Is_target_geometry {
  Geometry *m_target;

 public:
  Is_target_geometry(Geometry *t) : m_target(t) {}

  bool operator()(Geometry *g) { return g == m_target; }
};

class Rtree_entry_compare {
 public:
  Rtree_entry_compare() {}

  bool operator()(const BG_rtree_entry &re1, const BG_rtree_entry &re2) const {
    return re1.second < re2.second;
  }
};

/**
  One run of merging components.

  @tparam Coordsys Coordinate system type, specified using those defined in
          boost::geometry::cs.
  @param ifsu the Item_func_spatial_operation object, we here rely on it to
         do union operation.
  @param[out] pnull_value takes back null_value set during the operation.
  @return whether need another call of this function.
 */
template <typename Coordsys>
bool BG_geometry_collection::merge_one_run(Item_func_st_union *ifsu,
                                           bool *pnull_value) {
  Geometry *gres = nullptr;
  bool has_new = false;
  bool &null_value = *pnull_value;
  Pointer_vector<Geometry> added;
  std::vector<String> added_wkbbufs;

  added.reserve(16);
  added_wkbbufs.reserve(16);

  Rtree_index rtree;
  make_rtree(m_geos, &rtree);
  Rtree_result rtree_result;

  for (Geometry_list::iterator i = m_geos.begin(); i != m_geos.end(); ++i) {
    if (*i == NULL) continue;

    BG_box box;
    make_bg_box(*i, &box);
    if (!is_box_valid(box)) continue;

    rtree_result.clear();
    rtree.query(bgi::intersects(box), std::back_inserter(rtree_result));
    /*
      Normally the rtree should be non-empty because at least there is *i
      itself. But if box has NaN coordinates, the rtree can be empty since
      all coordinate comparisons with NaN numbers are false. also if the
      min corner point have greater coordinates than the max corner point,
      the box isn't valid and the rtree can be empty.
     */
    DBUG_ASSERT(rtree_result.size() != 0);

    // Sort rtree_result by Rtree_entry::second in order to make
    // components in fixed order.
    Rtree_entry_compare rtree_entry_compare;
    std::sort(rtree_result.begin(), rtree_result.end(), rtree_entry_compare);

    // Used to stop the nested loop.
    bool stop_it = false;

    for (Rtree_result::iterator j = rtree_result.begin();
         j != rtree_result.end(); ++j) {
      Geometry *geom2 = m_geos[j->second];
      if (*i == geom2 || geom2 == nullptr) continue;

      // Equals is much easier and faster to check, so check it first.
      if (Item_func_spatial_rel::bg_geo_relation_check(
              geom2, *i, Item_func::SP_EQUALS_FUNC, &null_value) &&
          !null_value) {
        *i = NULL;
        break;
      }

      if (null_value) {
        stop_it = true;
        break;
      }

      if (Item_func_spatial_rel::bg_geo_relation_check(
              *i, geom2, Item_func::SP_WITHIN_FUNC, &null_value) &&
          !null_value) {
        *i = NULL;
        break;
      }

      if (null_value) {
        stop_it = true;
        break;
      }

      if (Item_func_spatial_rel::bg_geo_relation_check(
              geom2, *i, Item_func::SP_WITHIN_FUNC, &null_value) &&
          !null_value) {
        m_geos[j->second] = nullptr;
        continue;
      }

      if (null_value) {
        stop_it = true;
        break;
      }

      /*
        If *i and geom2 is a polygon and a linestring that intersect only
        finite number of points, the union result is the same as the two
        geometries, and we would be stuck in an infinite loop. So we must
        detect and exclude this case. All other argument type combinations
        always will get a geometry different from the two arguments.
      */
      char d11 = (*i)->feature_dimension();
      char d12 = geom2->feature_dimension();
      Geometry *geom_d1 = nullptr;
      Geometry *geom_d2 = nullptr;
      bool is_linear_areal = false;

      if (((d11 == 1 && d12 == 2) || (d12 == 1 && d11 == 2))) {
        geom_d1 = (d11 == 1 ? *i : geom2);
        geom_d2 = (d11 == 2 ? *i : geom2);
        if (d11 != 1) {
          const char tmp_dim = d11;
          d11 = d12;
          d12 = tmp_dim;
        }
        is_linear_areal = true;
      }

      /*
        As said above, if one operand is linear, the other is areal, then we
        only proceed the union of them if they intersect infinite number of
        points, i.e. L crosses A or L touches A's outer ring. Note that if L
        touches some of A's inner rings, L must be crossing A, so not gonna
        check the inner rings.
      */
      if ((!is_linear_areal &&
           Item_func_spatial_rel::bg_geo_relation_check(
               *i, geom2, Item_func::SP_INTERSECTS_FUNC, &null_value) &&
           !null_value) ||
          (is_linear_areal && linear_areal_intersect_infinite<Coordsys>(
                                  geom_d1, geom_d2, &null_value))) {
        String wkbres;

        if (null_value) {
          stop_it = true;
          break;
        }

        gres = ifsu->bg_geo_set_op<Coordsys>(*i, geom2, &wkbres);
        null_value = ifsu->null_value;

        if (null_value) {
          if (gres != nullptr && gres != *i && gres != geom2) delete gres;
          stop_it = true;
          break;
        }

        if (gres != *i) *i = NULL;
        if (gres != geom2) m_geos[j->second] = nullptr;
        if (gres != nullptr && gres != *i && gres != geom2) {
          added.push_back(gres);
          String tmp_wkbbuf;
          added_wkbbufs.push_back(tmp_wkbbuf);
          added_wkbbufs.back().takeover(wkbres);
          has_new = true;
          gres = nullptr;
        }
        /*
          Done with *i, it's either adopted, or removed or merged to a new
          geometry.
         */
        break;
      }  // intersects

      if (null_value) {
        stop_it = true;
        break;
      }

    }  // for (*j)

    if (stop_it) break;

  }  // for (*i)

  // Remove deleted Geometry object pointers, then append new components if any.
  Is_target_geometry pred(nullptr);
  Geometry_list::iterator jj =
      std::remove_if(m_geos.begin(), m_geos.end(), pred);
  m_geos.resize(jj - m_geos.begin());

  for (Pointer_vector<Geometry>::iterator i = added.begin(); i != added.end();
       ++i) {
    /*
      Fill rather than directly use *i for consistent memory management.
      The objects pointed by pointers in added will be automatically destroyed.
     */
    fill(*i);
  }

  // The added and added_wkbbufs arrays are destroyed and the Geometry objects
  // in 'added' are freed, and memory buffers in added_wkbbufs are freed too.
  return has_new;
}

inline void reassemble_geometry(Geometry *g) {
  Geometry::wkbType gtype = g->get_geotype();
  if (gtype == Geometry::wkb_polygon)
    down_cast<Gis_polygon *>(g)->to_wkb_unparsed();
  else if (gtype == Geometry::wkb_multilinestring)
    down_cast<Gis_multi_line_string *>(g)->reassemble();
  else if (gtype == Geometry::wkb_multipolygon)
    down_cast<Gis_multi_polygon *>(g)->reassemble();
}

template <typename BG_geotype>
bool post_fix_result(BG_result_buf_mgr *resbuf_mgr, BG_geotype &geout,
                     String *res) {
  DBUG_ASSERT(geout.has_geom_header_space());
  reassemble_geometry(&geout);

  // Such objects returned by BG never have overlapped components.
  if (geout.get_type() == Geometry::wkb_multilinestring ||
      geout.get_type() == Geometry::wkb_multipolygon)
    geout.set_components_no_overlapped(true);
  if (geout.get_ptr() == nullptr) return true;
  if (res) {
    char *resptr = geout.get_cptr() - GEOM_HEADER_SIZE;
    size_t len = geout.get_nbytes();

    /*
      The resptr buffer is now owned by resbuf_mgr and used by res, resptr
      will be released properly by resbuf_mgr.
     */
    resbuf_mgr->add_buffer(resptr);
    /*
      The memory for the result is owned by a BG_result_buf_mgr,
      so use String::set(char*, size_t, const CHARSET_INFO)
      which points the internall buffer to the input argument,
      and sets m_is_alloced = false, signifying the String object
      does not own the buffer.
    */
    res->set(resptr, len + GEOM_HEADER_SIZE, &my_charset_bin);

    // Prefix the GEOMETRY header.
    write_geometry_header(resptr, geout.get_srid(), geout.get_geotype());

    /*
      Give up ownership because the buffer may have to live longer than
      the object.
    */
    geout.set_ownmem(false);
  }

  return false;
}

// Explicit template instantiation
template bool post_fix_result<Gis_line_string>(BG_result_buf_mgr *,
                                               Gis_line_string &, String *);
template bool post_fix_result<Gis_multi_line_string>(BG_result_buf_mgr *,
                                                     Gis_multi_line_string &,
                                                     String *);
template bool post_fix_result<Gis_multi_point>(BG_result_buf_mgr *,
                                               Gis_multi_point &, String *);
template bool post_fix_result<Gis_multi_polygon>(BG_result_buf_mgr *,
                                                 Gis_multi_polygon &, String *);
template bool post_fix_result<Gis_point>(BG_result_buf_mgr *, Gis_point &,
                                         String *);
template bool post_fix_result<Gis_polygon>(BG_result_buf_mgr *, Gis_polygon &,
                                           String *);

class Is_empty_geometry : public WKB_scanner_event_handler {
 public:
  bool is_empty;

  Is_empty_geometry() : is_empty(true) {}

  void on_wkb_start(Geometry::wkbByteOrder, Geometry::wkbType geotype,
                    const void *, uint32, bool) override {
    if (is_empty && geotype != Geometry::wkb_geometrycollection)
      is_empty = false;
  }

  void on_wkb_end(const void *) override {}

  bool continue_scan() const override { return is_empty; }
};

bool is_empty_geocollection(const Geometry *g) {
  if (g->get_geotype() != Geometry::wkb_geometrycollection) return false;

  uint32 num = uint4korr(g->get_cptr());
  if (num == 0) return true;

  Is_empty_geometry checker;
  uint32 len = g->get_data_size();
  wkb_scanner(current_thd, g->get_cptr(), &len,
              Geometry::wkb_geometrycollection, false, &checker);
  return checker.is_empty;
}

bool is_empty_geocollection(const String &wkbres) {
  if (wkbres.ptr() == nullptr) return true;

  uint32 geotype = uint4korr(wkbres.ptr() + SRID_SIZE + 1);

  if (geotype != static_cast<uint32>(Geometry::wkb_geometrycollection))
    return false;

  if (uint4korr(wkbres.ptr() + SRID_SIZE + WKB_HEADER_SIZE) == 0) return true;

  Is_empty_geometry checker;
  uint32 len = static_cast<uint32>(wkbres.length()) - GEOM_HEADER_SIZE;
  wkb_scanner(current_thd, wkbres.ptr() + GEOM_HEADER_SIZE, &len,
              Geometry::wkb_geometrycollection, false, &checker);
  return checker.is_empty;
}

ext: cc


text:
#include <boost/thread.hpp>

#include "SearchManager.h"

using namespace std;
using namespace realcore;

const bool SearchManager::IsTerminate()
{
  if(node_limit_ != 0 && node_ > node_limit_){
    return true;
  }

  if(elapsed_time_limit_ != 0){
    auto elapsed_time_ms = GetSearchTime();

    if(elapsed_time_ms > elapsed_time_limit_){
      return true;
    }
  }

  if(interruption_){
    return true;
  }

  try{
    if(catch_interrupt_exception_){
      boost::this_thread::interruption_point();
    }
  }catch(boost::thread_interrupted){
    interruption_ = true;
    return true;
  }

  return false;
}

SearchCounter SearchManager::GetSearchTime() const
{
  auto elapsed_time = chrono::system_clock::now() - search_start_time_;
  auto elapsed_time_ms = chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();

  return elapsed_time_ms;
}

max_stars_repo_name: starpentagon/realcore

max_issues_repo_name: starpentagon/realcore

max_forks_repo_name: starpentagon/realcore


text:
/* integrate.hpp header file
 *
 * Copyright Jens Maurer 2000
 * 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)
 *
 * $Id$
 *
 * Revision history
 *   01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock)
 */

#ifndef INTEGRATE_HPP
#define INTEGRATE_HPP

#include <boost/limits.hpp>

template<class UnaryFunction>
inline typename UnaryFunction::result_type
trapezoid(UnaryFunction f, typename UnaryFunction::argument_type a,
          typename UnaryFunction::argument_type b, int n)
{
  typename UnaryFunction::result_type tmp = 0;
  for(int i = 1; i <= n-1; ++i)
    tmp += f(a+(b-a)/n*i);
  return (b-a)/2/n * (f(a) + f(b) + 2*tmp);
}

template<class UnaryFunction>
inline typename UnaryFunction::result_type
simpson(UnaryFunction f, typename UnaryFunction::argument_type a,
        typename UnaryFunction::argument_type b, int n)
{
  typename UnaryFunction::result_type tmp1 = 0;
  for(int i = 1; i <= n-1; ++i)
    tmp1 += f(a+(b-a)/n*i);
  typename UnaryFunction::result_type tmp2 = 0;
  for(int i = 1; i <= n ; ++i)
    tmp2 += f(a+(b-a)/2/n*(2*i-1));

  return (b-a)/6/n * (f(a) + f(b) + 2*tmp1 + 4*tmp2);
}

// compute b so that f(b) = y; assume f is monotone increasing
template<class UnaryFunction, class T>
inline T
invert_monotone_inc(UnaryFunction f, typename UnaryFunction::result_type y,
                    T lower = -1,
                    T upper = 1)
{
  while(upper-lower > 1e-6) {
    double middle = (upper+lower)/2;
    if(f(middle) > y)
      upper = middle;
    else
      lower = middle;
  }
  return (upper+lower)/2;
}

// compute b so that  I(f(x), a, b) == y
template<class UnaryFunction>
inline typename UnaryFunction::argument_type
quantil(UnaryFunction f, typename UnaryFunction::argument_type a,
        typename UnaryFunction::result_type y,
        typename UnaryFunction::argument_type step)
{
  typedef typename UnaryFunction::result_type result_type;
  if(y >= 1.0)
    return std::numeric_limits<result_type>::infinity();
  typename UnaryFunction::argument_type b = a;
  for(result_type result = 0; result < y; b += step)
    result += step*f(b);
  return b;
}

#endif /* INTEGRATE_HPP */

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*******************************************************************************
 Author: Bogdan Nicolae
 Copyright (C) 2013 IBM Corp.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*******************************************************************************/

#ifndef __DEDUP_ENGINE
#define __DEDUP_ENGINE

#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/functional/hash.hpp>
#include <boost/pool/pool_alloc.hpp>
#include <boost/mpi.hpp>

#include "cow_allocator.hpp"

class page_hashes_entry_t;
typedef boost::unordered_set<page_hashes_entry_t,
			     boost::hash<page_hashes_entry_t>, std::equal_to<page_hashes_entry_t>,
			     boost::fast_pool_allocator<page_hashes_entry_t, no_reclaim_allocator>
			     > page_hashes_t;

class stats_t {
public:
    unsigned int local, global, total;
    stats_t(unsigned int l, unsigned int g, unsigned int t) : local(l), global(g), total(t) { }
    stats_t() : local(0), global(0), total(0) { }
private:
    friend class boost::serialization::access;
    template <class Archive> void serialize(Archive &ar, unsigned int /*version*/) {
    	ar & local & global & total;
    }
};

class dedup_engine {
private:
    typedef std::pair<char *, bool> page_ptr_map_entry_t;
    typedef boost::unordered_map<char *, bool,
				 boost::hash<char *>, std::equal_to<char *>,
				 boost::fast_pool_allocator<page_ptr_map_entry_t, no_reclaim_allocator>
			       > page_ptr_map_t;

    page_hashes_t page_hashes;
    page_ptr_map_t page_ptr_map;

    stats_t stats;
    boost::mpi::communicator *mpi_comm_world;

public:
    dedup_engine(boost::mpi::communicator *comm);
    ~dedup_engine();
    void process_page(char *buff);
    bool check_page(char *buff);
    void global_dedup();
    void clear();

    void finalize_local();
    std::string get_stats();
};

#endif

max_stars_repo_name: bnicolae/ac-fte

max_issues_repo_name: bnicolae/ac-fte

max_forks_repo_name: bnicolae/ac-fte


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "any_of.h"
#include <Eigen/Core>
template <typename Mat>
IGL_INLINE bool igl::any_of(const Mat & S)
{
  return std::any_of(S.data(),S.data()+S.size(),[](bool s){return s;});
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template bool igl::any_of<Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::Matrix<int, -1, 1, 0, -1, 1> const&);
#endif

ext: cpp

max_stars_repo_name: FabianRepository/SinusProject

max_issues_repo_name: FabianRepository/SinusProject

max_forks_repo_name: FabianRepository/SinusProject


text:
// Copyright (c) 2010-2020 The F44RedCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <ui_interface.h>

#include <boost/signals2/last_value.hpp>
#include <boost/signals2/signal.hpp>

CClientUIInterface uiInterface;

struct UISignals {
    boost::signals2::signal<CClientUIInterface::ThreadSafeMessageBoxSig, boost::signals2::last_value<bool>> ThreadSafeMessageBox;
    boost::signals2::signal<CClientUIInterface::ThreadSafeQuestionSig, boost::signals2::last_value<bool>> ThreadSafeQuestion;
    boost::signals2::signal<CClientUIInterface::InitMessageSig> InitMessage;
    boost::signals2::signal<CClientUIInterface::NotifyNumConnectionsChangedSig> NotifyNumConnectionsChanged;
    boost::signals2::signal<CClientUIInterface::NotifyNetworkActiveChangedSig> NotifyNetworkActiveChanged;
    boost::signals2::signal<CClientUIInterface::NotifyAlertChangedSig> NotifyAlertChanged;
    boost::signals2::signal<CClientUIInterface::ShowProgressSig> ShowProgress;
    boost::signals2::signal<CClientUIInterface::NotifyBlockTipSig> NotifyBlockTip;
    boost::signals2::signal<CClientUIInterface::NotifyHeaderTipSig> NotifyHeaderTip;
    boost::signals2::signal<CClientUIInterface::BannedListChangedSig> BannedListChanged;
};
static UISignals g_ui_signals;

#define ADD_SIGNALS_IMPL_WRAPPER(signal_name)                                                                 \
    boost::signals2::connection CClientUIInterface::signal_name##_connect(std::function<signal_name##Sig> fn) \
    {                                                                                \
        return g_ui_signals.signal_name.connect(fn);                                                          \
    }

ADD_SIGNALS_IMPL_WRAPPER(ThreadSafeMessageBox);
ADD_SIGNALS_IMPL_WRAPPER(ThreadSafeQuestion);
ADD_SIGNALS_IMPL_WRAPPER(InitMessage);
ADD_SIGNALS_IMPL_WRAPPER(NotifyNumConnectionsChanged);
ADD_SIGNALS_IMPL_WRAPPER(NotifyNetworkActiveChanged);
ADD_SIGNALS_IMPL_WRAPPER(NotifyAlertChanged);
ADD_SIGNALS_IMPL_WRAPPER(ShowProgress);
ADD_SIGNALS_IMPL_WRAPPER(NotifyBlockTip);
ADD_SIGNALS_IMPL_WRAPPER(NotifyHeaderTip);
ADD_SIGNALS_IMPL_WRAPPER(BannedListChanged);

bool CClientUIInterface::ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { return g_ui_signals.ThreadSafeMessageBox(message, caption, style); }
bool CClientUIInterface::ThreadSafeQuestion(const std::string& message, const std::string& non_interactive_message, const std::string& caption, unsigned int style) { return g_ui_signals.ThreadSafeQuestion(message, non_interactive_message, caption, style); }
void CClientUIInterface::InitMessage(const std::string& message) { return g_ui_signals.InitMessage(message); }
void CClientUIInterface::NotifyNumConnectionsChanged(int newNumConnections) { return g_ui_signals.NotifyNumConnectionsChanged(newNumConnections); }
void CClientUIInterface::NotifyNetworkActiveChanged(bool networkActive) { return g_ui_signals.NotifyNetworkActiveChanged(networkActive); }
void CClientUIInterface::NotifyAlertChanged() { return g_ui_signals.NotifyAlertChanged(); }
void CClientUIInterface::ShowProgress(const std::string& title, int nProgress, bool resume_possible) { return g_ui_signals.ShowProgress(title, nProgress, resume_possible); }
void CClientUIInterface::NotifyBlockTip(bool b, const CBlockIndex* i) { return g_ui_signals.NotifyBlockTip(b, i); }
void CClientUIInterface::NotifyHeaderTip(bool b, const CBlockIndex* i) { return g_ui_signals.NotifyHeaderTip(b, i); }
void CClientUIInterface::BannedListChanged() { return g_ui_signals.BannedListChanged(); }

bool InitError(const std::string& str)
{
    uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
    return false;
}

void InitWarning(const std::string& str)
{
    uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
}


text:
/**
*   LineString.hpp
*
*   Copyright 2015 The Climate Corporation
*   Copyright 2015 Tony Stone
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*
*   Created by Tony Stone on 6/9/15.
*
*   MODIFIED 2015 BY Tony Stone. Modifications licensed under Apache License, Version 2.0.
*
*/
#pragma once

#ifndef __LineString_HPP_
#define __LineString_HPP_

#include "GFGeometry.hpp"
#include "GFPoint.hpp"
#include "GFCollection.hpp"

#include <boost/concept/assert.hpp>
#include <boost/range.hpp>

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

#include <boost/geometry/geometries/concepts/point_concept.hpp>

namespace geofeatures {

    /**
    * @class       LineString
    *
    * @brief       A Line of Points.
    *
    * @author      Tony Stone
    * @date        6/9/15
    */
    class LineString : public Geometry, public Collection <geofeatures::Point> {

    private:
        typedef Collection <geofeatures::Point> BaseType;

    public:
        inline LineString() noexcept : Geometry(), BaseType() {}
        LineString(LineString &other) noexcept : Geometry(), BaseType(other) {}
        LineString(LineString const &other) noexcept : Geometry(), BaseType(other) {}
        LineString(BaseType &other) noexcept : Geometry(), BaseType(other) {}
        LineString(BaseType const &other) noexcept : Geometry(), BaseType(other) {}

        inline virtual ~LineString() noexcept {};
    };

}   // namespace geofeatures

namespace geofeatures_boost {
    namespace geometry {
        namespace traits
        {
            template<>
            struct tag<geofeatures::LineString> {
                typedef linestring_tag type;
            };
        }
    } // namespace geometry::traits
} // namespace boost

#endif //__LineString_HPP_

max_stars_repo_name: tonystone/geofeatures

max_issues_repo_name: tonystone/geofeatures

max_forks_repo_name: tonystone/geofeatures


text:
//  Copyright Neil Groves 2009. 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)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_REMOVE_IF_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_REMOVE_IF_HPP_INCLUDED

#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/detail/range_return.hpp>
#include <algorithm>

namespace boost
{
    namespace range
    {

/// \brief template function remove_if
///
/// range-based version of the remove_if std algorithm
///
/// \pre ForwardRange is a model of the ForwardRangeConcept
/// \pre UnaryPredicate is a model of the UnaryPredicateConcept
template< class ForwardRange, class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME boost::range_iterator<ForwardRange>::type
remove_if(ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
    return std::remove_if(boost::begin(rng), boost::end(rng), pred);
}

/// \overload
template< class ForwardRange, class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME boost::range_iterator<const ForwardRange>::type
remove_if(const ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
    return std::remove_if(boost::begin(rng),boost::end(rng),pred);
}

// range_return overloads

/// \overload
template< range_return_value re, class ForwardRange, class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<ForwardRange,re>::type
remove_if(ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
    return range_return<ForwardRange,re>::pack(
        std::remove_if(boost::begin(rng), boost::end(rng), pred),
        rng);
}

/// \overload
template< range_return_value re, class ForwardRange, class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<const ForwardRange,re>::type
remove_if(const ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
    return range_return<const ForwardRange,re>::pack(
        std::remove_if(boost::begin(rng), boost::end(rng), pred),
        rng);
}

    } // namespace range
    using range::remove_if;
} // namespace boost

#endif // include guard

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman
    Copyright (c) 2001-2009 Hartmut Kaiser
    Copyright (c) 2006 Stephen Nutt

    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)
=============================================================================*/
#if !defined(SPIRIT_NUMERIC_UTILS_APR_17_2006_0816AM)
#define SPIRIT_NUMERIC_UTILS_APR_17_2006_0816AM

#include <boost/detail/iterator.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/char_class/ascii.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>

#include <limits>
#include <boost/limits.hpp>

#if !defined(SPIRIT_NUMERICS_LOOP_UNROLL)
# define SPIRIT_NUMERICS_LOOP_UNROLL 3
#endif

namespace boost { namespace spirit { namespace qi { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////
    //
    //  Traits class for radix specific number conversion
    //
    //      Test the validity of a single character:
    //
    //          template<typename Char> static bool is_valid(Char ch);
    //
    //      Convert a digit from character representation to binary
    //      representation:
    //
    //          template<typename Char> static int digit(Char ch);
    //
    //      The maximum radix digits that can be represented without
    //      overflow:
    //
    //          template<typename T> struct digits::value;
    //
    ///////////////////////////////////////////////////////////////////////////
    template <unsigned Radix>
    struct radix_traits;

    // Binary
    template <>
    struct radix_traits<2>
    {
        template<typename Char>
        static bool is_valid(Char ch)
        {
            return ('0' == ch || '1' == ch);
        }

        template<typename Char>
        static unsigned digit(Char ch)
        {
            return ch - '0';
        }

        template<typename T>
        struct digits
        {
            typedef std::numeric_limits<T> numeric_limits_;
            BOOST_STATIC_CONSTANT(int, value = numeric_limits_::digits);
        };
    };

    // Octal
    template <>
    struct radix_traits<8>
    {
        template<typename Char>
        static bool is_valid(Char ch)
        {
            return ch >= '0' && ch <= '7';
        }

        template<typename Char>
        static unsigned digit(Char ch)
        {
            return ch - '0';
        }

        template<typename T>
        struct digits
        {
            typedef std::numeric_limits<T> numeric_limits_;
            BOOST_STATIC_CONSTANT(int, value = numeric_limits_::digits / 3);
        };
    };

    // Decimal
    template <>
    struct radix_traits<10>
    {
        template<typename Char>
        static bool is_valid(Char ch)
        {
            return ch >= '0' && ch <= '9';
        }

        template<typename Char>
        static unsigned digit(Char ch)
        {
            return ch - '0';
        }

        template<typename T>
        struct digits
        {
            typedef std::numeric_limits<T> numeric_limits_;
            BOOST_STATIC_CONSTANT(int, value = numeric_limits_::digits10);
        };
    };

    // Hexadecimal
    template <>
    struct radix_traits<16>
    {
        template<typename Char>
        static bool is_valid(Char ch)
        {
            return (ch >= '0' && ch <= '9')
            || (ch >= 'a' && ch <= 'f')
            || (ch >= 'A' && ch <= 'F');
        }

        template<typename Char>
        static unsigned digit(Char ch)
        {
            if (ch >= '0' && ch <= '9')
                return ch - '0';
            return spirit::char_class::ascii::tolower(ch) - 'a' + 10;
        }

        template<typename T>
        struct digits
        {
            typedef std::numeric_limits<T> numeric_limits_;
            BOOST_STATIC_CONSTANT(int, value = numeric_limits_::digits / 4);
        };
    };

    ///////////////////////////////////////////////////////////////////////////
    //  positive_accumulator/negative_accumulator: Accumulator policies for
    //  extracting integers. Use positive_accumulator if number is positive.
    //  Use negative_accumulator if number is negative.
    ///////////////////////////////////////////////////////////////////////////
    template <unsigned Radix>
    struct positive_accumulator
    {
        template <typename T, typename Char>
        static void add(T& n, Char ch, mpl::false_) // unchecked add
        {
            const int digit = radix_traits<Radix>::digit(ch);
            n = n * Radix + digit;
        }

        template <typename T, typename Char>
        static bool add(T& n, Char ch, mpl::true_) // checked add
        {
            // Ensure n *= Radix will not overflow
            static T const max = (std::numeric_limits<T>::max)();
            static T const val = (max - 1) / Radix;
            if (n > val)
                return false;

            n *= Radix;

            // Ensure n += digit will not overflow
            const int digit = radix_traits<Radix>::digit(ch);
            if (n > max - digit)
                return false;

            n += digit;
            return true;
        }
    };

    template <unsigned Radix>
    struct negative_accumulator
    {
        template <typename T, typename Char>
        static void add(T& n, Char ch, mpl::false_) // unchecked subtract
        {
            const int digit = radix_traits<Radix>::digit(ch);
            n = n * Radix - digit;
        }

        template <typename T, typename Char>
        static bool add(T& n, Char ch, mpl::true_) // checked subtract
        {
            // Ensure n *= Radix will not underflow
            static T const min = (std::numeric_limits<T>::min)();
            static T const val = (min + 1) / T(Radix);
            if (n < val)
                return false;

            n *= Radix;

            // Ensure n -= digit will not underflow
            int const digit = radix_traits<Radix>::digit(ch);
            if (n < min + digit)
                return false;

            n -= digit;
            return true;
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  Common code for extract_int::parse specializations
    ///////////////////////////////////////////////////////////////////////////
    template <unsigned Radix, typename Accumulator, int MaxDigits>
    struct int_extractor
    {
        template <typename Char, typename T>
        static bool
        call(Char ch, std::size_t count, T& n, mpl::true_)
        {
            static std::size_t const
                overflow_free = radix_traits<Radix>::template digits<T>::value - 1;

            if (count < overflow_free)
            {
                Accumulator::add(n, ch, mpl::false_());
            }
            else
            {
                if (!Accumulator::add(n, ch, mpl::true_()))
                    return false; //  over/underflow!
            }
            return true;
        }

        template <typename Char, typename T>
        static bool
        call(Char ch, std::size_t /*count*/, T& n, mpl::false_)
        {
            // no need to check for overflow
            Accumulator::add(n, ch, mpl::false_());
            return true;
        }

        template <typename Char>
        static bool
        call(Char /*ch*/, std::size_t /*count*/, unused_type, mpl::false_)
        {
            return true;
        }

        template <typename Char, typename T>
        static bool
        call(Char ch, std::size_t count, T& n)
        {
            return call(ch, count, n
              , mpl::bool_<
                    (   (MaxDigits < 0)
                    ||  (MaxDigits > radix_traits<Radix>::template digits<T>::value)
                    )
                  && std::numeric_limits<T>::is_modulo
                >()
            );
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  End of loop checking: check if the number of digits
    //  being parsed exceeds MaxDigits. Note: if MaxDigits == -1
    //  we don't do any checking.
    ///////////////////////////////////////////////////////////////////////////
    template <int MaxDigits>
    struct check_max_digits
    {
        static bool
        call(std::size_t count)
        {
            return count < MaxDigits; // bounded
        }
    };

    template <>
    struct check_max_digits<-1>
    {
        static bool
        call(std::size_t /*count*/)
        {
            return true; // unbounded
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  extract_int: main code for extracting integers
    ///////////////////////////////////////////////////////////////////////////
#define SPIRIT_NUMERIC_INNER_LOOP(z, x, data)                                   \
        if (!check_max_digits<MaxDigits>::call(count + leading_zeros)           \
            || it == last)                                                      \
            break;                                                              \
        ch = *it;                                                               \
        if (!radix_check::is_valid(ch) || !extractor::call(ch, count, val))     \
            break;                                                              \
        ++it;                                                                   \
        ++count;                                                                \
    /**/

    template <
        typename T, unsigned Radix, unsigned MinDigits, int MaxDigits
      , typename Accumulator = positive_accumulator<Radix>
      , bool Accumulate = false
    >
    struct extract_int
    {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(push)
# pragma warning(disable: 4127)   // conditional expression is constant
#endif
        template <typename Iterator, typename Attribute>
        static bool
        parse_main(
            Iterator& first
          , Iterator const& last
          , Attribute& attr)
        {
            typedef radix_traits<Radix> radix_check;
            typedef int_extractor<Radix, Accumulator, MaxDigits> extractor;
            typedef typename
                boost::detail::iterator_traits<Iterator>::value_type
            char_type;

            Iterator it = first;
            std::size_t leading_zeros = 0;
            if (!Accumulate)
            {
                // skip leading zeros
                while (it != last && *it == '0' && leading_zeros < MaxDigits)
                {
                    ++it;
                    ++leading_zeros;
                }
            }

            Attribute val = Accumulate ? attr : 0;
            std::size_t count = 0;
            char_type ch;

            while (true)
            {
                BOOST_PP_REPEAT(
                    SPIRIT_NUMERICS_LOOP_UNROLL
                  , SPIRIT_NUMERIC_INNER_LOOP, _)
            }

            if (count + leading_zeros >= MinDigits)
            {
                attr = val;
                first = it;
                return true;
            }
            return false;
        }
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(pop)
#endif

        template <typename Iterator>
        static bool
        parse(
            Iterator& first
          , Iterator const& last
          , unused_type)
        {
            T n = 0; // must calculate value to detect over/underflow
            return parse_main(first, last, n);
        }

        template <typename Iterator, typename Attribute>
        static bool
        parse(
            Iterator& first
          , Iterator const& last
          , Attribute& attr)
        {
            return parse_main(first, last, attr);
        }
    };
#undef SPIRIT_NUMERIC_INNER_LOOP

    ///////////////////////////////////////////////////////////////////////////
    //  extract_int: main code for extracting integers
    //  common case where MinDigits == 1 and MaxDigits = -1
    ///////////////////////////////////////////////////////////////////////////
#define SPIRIT_NUMERIC_INNER_LOOP(z, x, data)                                   \
        if (it == last)                                                         \
            break;                                                              \
        ch = *it;                                                               \
        if (!radix_check::is_valid(ch) || !extractor::call(ch, count, val))     \
            break;                                                              \
        ++it;                                                                   \
        ++count;                                                                \
    /**/

    template <typename T, unsigned Radix, typename Accumulator, bool Accumulate>
    struct extract_int<T, Radix, 1, -1, Accumulator, Accumulate>
    {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(push)
# pragma warning(disable: 4127)   // conditional expression is constant
#endif
        template <typename Iterator, typename Attribute>
        static bool
        parse_main(
            Iterator& first
          , Iterator const& last
          , Attribute& attr)
        {
            typedef radix_traits<Radix> radix_check;
            typedef int_extractor<Radix, Accumulator, -1> extractor;
            typedef typename
                boost::detail::iterator_traits<Iterator>::value_type
            char_type;

            Iterator it = first;
            std::size_t count = 0;
            if (!Accumulate)
            {
                // skip leading zeros
                while (it != last && *it == '0')
                {
                    ++it;
                    ++count;
                }

                if (it == last)
                {
                    if (count == 0) // must have at least one digit
                        return false;
                    attr = 0;
                    first = it;
                    return true;
                }
            }

            Attribute val = Accumulate ? attr : 0;
            char_type ch = *it;

            if (!radix_check::is_valid(ch) || !extractor::call(ch, 0, val))
            {
                if (count == 0) // must have at least one digit
                    return false;
                attr = val;
                first = it;
                return true;
            }

            count = 0;
            ++it;
            while (true)
            {
                BOOST_PP_REPEAT(
                    SPIRIT_NUMERICS_LOOP_UNROLL
                  , SPIRIT_NUMERIC_INNER_LOOP, _)
            }

            attr = val;
            first = it;
            return true;
        }
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(pop)
#endif

        template <typename Iterator>
        static bool
        parse(
            Iterator& first
          , Iterator const& last
          , unused_type)
        {
            T n = 0; // must calculate value to detect over/underflow
            return parse_main(first, last, n);
        }

        template <typename Iterator, typename Attribute>
        static bool
        parse(
            Iterator& first
          , Iterator const& last
          , Attribute& attr)
        {
            return parse_main(first, last, attr);
        }
    };

#undef SPIRIT_NUMERIC_INNER_LOOP

}}}}

#endif


text:
/*
 * Copyright (C) 1999-2011 Insight Software Consortium
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef otbPersistentImageToOGRLayerFilter_hxx
#define otbPersistentImageToOGRLayerFilter_hxx

#include "otbPersistentImageToOGRLayerFilter.h"
#include "otbStopwatch.h"
#include <boost/foreach.hpp>
#include <stdio.h>
#include "otbMacro.h"
#include "otbOGRHelpers.h"

namespace otb
{

template<class TImage>
PersistentImageToOGRLayerFilter<TImage>
::PersistentImageToOGRLayerFilter() : m_OGRLayer(nullptr, false)
{
   m_StreamSize.Fill(0);
}

template<class TImage>
PersistentImageToOGRLayerFilter<TImage>
::~PersistentImageToOGRLayerFilter()
{
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::SetOGRLayer(const OGRLayerType & ogrLayer)
{
  m_OGRLayer = ogrLayer;
  this->Modified();
}

template<class TImage>
const typename PersistentImageToOGRLayerFilter<TImage>::OGRLayerType&
PersistentImageToOGRLayerFilter<TImage>
::GetOGRLayer( void ) const
{
  return m_OGRLayer;
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::AllocateOutputs()
{
  // Nothing that needs to be allocated for the outputs : the output is not meant to be used
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::Reset()
{
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::Synthetize()
{
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::Initialize()
{
  // Make sure input projection ref is set
  const_cast<InputImageType*> (this->GetInput())->UpdateOutputInformation();

  // Ensure that spatial reference of the output layer matches with
  // the spatial reference of the input image
  OGRSpatialReference oSRS(this->GetInput()->GetProjectionRef().c_str());

  // when dealing with .shp OGRSPatialreference is morphed to ESRI WKT,
  // which results in small difference in WKT with some projection reference
  // so the comparison must be done with WKT and ESRI WKT Mantis #ref567
  OGRSpatialReference oSRSESRI(this->GetInput()->GetProjectionRef().c_str());

  oSRSESRI.morphToESRI();
  oSRSESRI.morphFromESRI();
  if (m_OGRLayer.GetSpatialRef() && (!oSRS.IsSame(m_OGRLayer.GetSpatialRef())
      && !oSRSESRI.IsSame(m_OGRLayer.GetSpatialRef())))
    {
    if ((oSRS.Validate() != OGRERR_NONE) && (oSRSESRI.Validate() != OGRERR_NONE))
      {
      itkExceptionMacro(<<"Input projection ref is not valid");
      }
    itkExceptionMacro(<<"Spatial reference of input image and target layer do not match! "<< std::endl
                      << "Input image : "<< this->GetInput()->GetProjectionRef()<< std::endl
                      << "Target layer : "<<m_OGRLayer.GetProjectionRef());
    }
}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::GenerateData()
{
  if(!m_OGRLayer)
    {
    itkExceptionMacro(<<"Output OGRLayer is null.");
    }

  if (this->GetStreamSize()[0]==0 && this->GetStreamSize()[1]==0)
  {
     this->m_StreamSize = this->GetInput()->GetRequestedRegion().GetSize();
  }

  // call the processing function for this tile
  OGRDataSourcePointerType currentTileVD = this->ProcessTile();
  OGRLayerType srcLayer = currentTileVD->GetLayerChecked(0);

  // Check spatial reference matches
  if(srcLayer.GetSpatialRef() && m_OGRLayer.GetSpatialRef() && !srcLayer.GetSpatialRef()->IsSame(m_OGRLayer.GetSpatialRef()))
     {
     itkExceptionMacro(<<"Spatial reference of internal and target layers do not match!");
     }

  //Copy features contained in the memory layer (srcLayer) in the output layer
  otb::Stopwatch chrono = otb::Stopwatch::StartNew();

  OGRErr err = m_OGRLayer.ogr().StartTransaction();
  if (err != OGRERR_NONE)
    {
    itkExceptionMacro(<< "Unable to start transaction for OGR layer " << m_OGRLayer.ogr().GetName() << ".");
    }

  OGRLayerType::const_iterator featIt = srcLayer.begin();
  for(; featIt!=srcLayer.end(); ++featIt)
    {
    OGRFeatureType dstFeature(m_OGRLayer.GetLayerDefn());
    dstFeature.SetFrom( *featIt, TRUE );
    m_OGRLayer.CreateFeature( dstFeature );
    }

  err = m_OGRLayer.ogr().CommitTransaction();

  if (err != OGRERR_NONE)
    {
    itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << m_OGRLayer.ogr().GetName() << ".");
    }

  chrono.Stop();
  otbMsgDebugMacro(<< "Writing OGR tile took " << chrono.GetElapsedMilliseconds() << " ms");

}

template<class TImage>
void
PersistentImageToOGRLayerFilter<TImage>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

} // end namespace otb
#endif

ext: hxx

max_stars_repo_name: kikislater/OTB

max_issues_repo_name: ThomasWangWeiHong/OTB

max_forks_repo_name: ThomasWangWeiHong/OTB


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_HDF5IArchive.cpp
//! \author Alex Robinson
//! \brief  HDF5 input archive class definition
//!
//---------------------------------------------------------------------------//

// Boost Includes
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/impl/archive_serializer_map.ipp>

// FRENSIE Includes
#include "Utility_HDF5IArchive.hpp"

namespace Utility{

template void HDF5IArchiveImpl<HDF5IArchive>::load( bool& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( char& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( unsigned char& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( signed char& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( short& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( unsigned short& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( int& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( unsigned& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( long& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( unsigned long& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( long long& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( unsigned long long& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( float& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( double& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( long double& );
template void HDF5IArchiveImpl<HDF5IArchive>::load( std::string& );

#ifdef BOOST_SERIALIZATION_ARRAY_WRAPPER_AVAILABLE
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<bool>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<char>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<unsigned char>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<signed char>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<short>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<unsigned short>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<int>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<unsigned>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<long>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<unsigned long>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<long long>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<unsigned long long>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<float>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<double>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<long double>&, unsigned int );
template void HDF5IArchiveImpl<HDF5IArchive>::load_array( boost::serialization::array_wrapper<std::string>&, unsigned int );
#endif

} // end Utility namespace

namespace boost{
namespace archive{
namespace detail{

template class archive_serializer_map<Utility::HDF5IArchive>;

} // end detail namespace
} // end archive namespace
} // end boost namespace

//---------------------------------------------------------------------------//
// end Utility_HDF5IArchive.cpp
//---------------------------------------------------------------------------//


text:
// Autogenerated from KST: please remove this line if doing any edits by hand!

#include <boost/test/unit_test.hpp>
#include "bits_seq_endian_combo.h"
#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_bits_seq_endian_combo) {
    std::ifstream ifs("src/process_xor_4.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    bits_seq_endian_combo_t* r = new bits_seq_endian_combo_t(&ks);

    BOOST_CHECK_EQUAL(r->be1(), 59);
    BOOST_CHECK_EQUAL(r->be2(), 187);
    BOOST_CHECK_EQUAL(r->le3(), 163);
    BOOST_CHECK_EQUAL(r->be4(), 20);
    BOOST_CHECK_EQUAL(r->le5(), 10);
    BOOST_CHECK_EQUAL(r->le6(), 36);
    BOOST_CHECK_EQUAL(r->le7(), 26);
    BOOST_CHECK_EQUAL(r->be8(), true);

    delete r;
}


text:
/*=============================================================================
    Copyright (c) 2001-2014 Joel de Guzman

    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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_X3_DETAIL_RULE_JAN_08_2012_0326PM)
#define BOOST_SPIRIT_X3_DETAIL_RULE_JAN_08_2012_0326PM

#include <boost/core/ignore_unused.hpp>
#include <boost/spirit/home/x3/auxiliary/guard.hpp>
#include <boost/spirit/home/x3/core/parser.hpp>
#include <boost/spirit/home/x3/core/skip_over.hpp>
#include <boost/spirit/home/x3/directive/expect.hpp>
#include <boost/spirit/home/x3/nonterminal/detail/transform_attribute.hpp>
#include <boost/spirit/home/x3/support/utility/sfinae.hpp>
#include <boost/utility/addressof.hpp>

#if defined(BOOST_SPIRIT_X3_DEBUG)
#include <boost/spirit/home/x3/nonterminal/simple_trace.hpp>
#endif

#include <type_traits>

namespace boost {
namespace spirit {
namespace x3 {
template <typename ID> struct identity;

template <typename ID, typename Attribute = unused_type,
          bool force_attribute = false>
struct rule;

struct parse_pass_context_tag;

namespace detail {
// we use this so we can detect if the default parse_rule
// is the being called.
struct default_parse_rule_result {
  default_parse_rule_result(bool r) : r(r) {}
  operator bool() const { return r; }
  bool r;
};
} // namespace detail

// default parse_rule implementation
template <typename ID, typename Attribute, typename Iterator, typename Context,
          typename ActualAttribute>
inline detail::default_parse_rule_result
parse_rule(rule<ID, Attribute> rule_, Iterator &first, Iterator const &last,
           Context const &context, ActualAttribute &attr);
} // namespace x3
} // namespace spirit
} // namespace boost

namespace boost {
namespace spirit {
namespace x3 {
namespace detail {
#if defined(BOOST_SPIRIT_X3_DEBUG)
template <typename Iterator, typename Attribute> struct context_debug {
  context_debug(char const *rule_name, Iterator const &first,
                Iterator const &last, Attribute const &attr,
                bool const &ok_parse // was parse successful?
                )
      : ok_parse(ok_parse), rule_name(rule_name), first(first), last(last),
        attr(attr), f(detail::get_simple_trace()) {
    f(first, last, attr, pre_parse, rule_name);
  }

  ~context_debug() {
    auto status = ok_parse ? successful_parse : failed_parse;
    f(first, last, attr, status, rule_name);
  }

  bool const &ok_parse;
  char const *rule_name;
  Iterator const &first;
  Iterator const &last;
  Attribute const &attr;
  detail::simple_trace_type &f;
};
#endif

template <typename ID, typename Iterator, typename Context,
          typename Enable = void>
struct has_on_error : mpl::false_ {};

template <typename ID, typename Iterator, typename Context>
struct has_on_error<
    ID, Iterator, Context,
    typename disable_if_substitution_failure<decltype(
        std::declval<ID>().on_error(
            std::declval<Iterator &>(), std::declval<Iterator>(),
            std::declval<expectation_failure<Iterator>>(),
            std::declval<Context>()))>::type> : mpl::true_ {};

template <typename ID, typename Iterator, typename Attribute, typename Context,
          typename Enable = void>
struct has_on_success : mpl::false_ {};

template <typename ID, typename Iterator, typename Attribute, typename Context>
struct has_on_success<
    ID, Iterator, Context, Attribute,
    typename disable_if_substitution_failure<decltype(
        std::declval<ID>().on_success(
            std::declval<Iterator &>(), std::declval<Iterator>(),
            std::declval<Attribute &>(), std::declval<Context>()))>::type>
    : mpl::true_ {};

template <typename ID> struct make_id { typedef identity<ID> type; };

template <typename ID> struct make_id<identity<ID>> {
  typedef identity<ID> type;
};

template <typename ID, typename RHS, typename Context>
Context const &make_rule_context(RHS const & /* rhs */, Context const &context,
                                 mpl::false_ /* is_default_parse_rule */) {
  return context;
}

template <typename ID, typename RHS, typename Context>
auto make_rule_context(RHS const &rhs, Context const &context,
                       mpl::true_ /* is_default_parse_rule */) {
  return make_unique_context<ID>(rhs, context);
}

template <typename Attribute, typename ID> struct rule_parser {
  template <typename Iterator, typename Context, typename ActualAttribute>
  static bool
  call_on_success(Iterator & /* first */, Iterator const & /* last */
                  ,
                  Context const & /* context */, ActualAttribute & /* attr */
                  ,
                  mpl::false_ /* No on_success handler */) {
    return true;
  }

  template <typename Iterator, typename Context, typename ActualAttribute>
  static bool call_on_success(Iterator &first, Iterator const &last,
                              Context const &context, ActualAttribute &attr,
                              mpl::true_ /* Has on_success handler */) {
    bool pass = true;
    ID().on_success(first, last, attr,
                    make_context<parse_pass_context_tag>(pass, context));
    return pass;
  }

  template <typename RHS, typename Iterator, typename Context,
            typename RContext, typename ActualAttribute>
  static bool parse_rhs_main(RHS const &rhs, Iterator &first,
                             Iterator const &last, Context const &context,
                             RContext &rcontext, ActualAttribute &attr,
                             mpl::false_) {
    // see if the user has a BOOST_SPIRIT_DEFINE for this rule
    typedef decltype(parse_rule(rule<ID, Attribute>(), first, last,
                                make_unique_context<ID>(rhs, context),
                                std::declval<Attribute &>())) parse_rule_result;

    // If there is no BOOST_SPIRIT_DEFINE for this rule,
    // we'll make a context for this rule tagged by its ID
    // so we can extract the rule later on in the default
    // (generic) parse_rule function.
    typedef is_same<parse_rule_result, default_parse_rule_result>
        is_default_parse_rule;

    Iterator i = first;
    bool r = rhs.parse(
        i, last, make_rule_context<ID>(rhs, context, is_default_parse_rule()),
        rcontext, attr);

    if (r) {
      auto first_ = first;
      x3::skip_over(first_, last, context);
      r = call_on_success(
          first_, i, context, attr,
          has_on_success<ID, Iterator, Context, ActualAttribute>());
    }

    if (r)
      first = i;
    return r;
  }

  template <typename RHS, typename Iterator, typename Context,
            typename RContext, typename ActualAttribute>
  static bool parse_rhs_main(RHS const &rhs, Iterator &first,
                             Iterator const &last, Context const &context,
                             RContext &rcontext, ActualAttribute &attr,
                             mpl::true_ /* on_error is found */) {
    for (;;) {
      try {
        return parse_rhs_main(rhs, first, last, context, rcontext, attr,
                              mpl::false_());
      } catch (expectation_failure<Iterator> const &x) {
        switch (ID().on_error(first, last, x, context)) {
        case error_handler_result::fail:
          return false;
        case error_handler_result::retry:
          continue;
        case error_handler_result::accept:
          return true;
        case error_handler_result::rethrow:
          throw;
        }
      }
    }
  }

  template <typename RHS, typename Iterator, typename Context,
            typename RContext, typename ActualAttribute>
  static bool parse_rhs_main(RHS const &rhs, Iterator &first,
                             Iterator const &last, Context const &context,
                             RContext &rcontext, ActualAttribute &attr) {
    return parse_rhs_main(rhs, first, last, context, rcontext, attr,
                          has_on_error<ID, Iterator, Context>());
  }

  template <typename RHS, typename Iterator, typename Context,
            typename RContext, typename ActualAttribute>
  static bool parse_rhs(RHS const &rhs, Iterator &first, Iterator const &last,
                        Context const &context, RContext &rcontext,
                        ActualAttribute &attr, mpl::false_) {
    return parse_rhs_main(rhs, first, last, context, rcontext, attr);
  }

  template <typename RHS, typename Iterator, typename Context,
            typename RContext, typename ActualAttribute>
  static bool parse_rhs(RHS const &rhs, Iterator &first, Iterator const &last,
                        Context const &context, RContext &rcontext,
                        ActualAttribute & /* attr */
                        ,
                        mpl::true_) {
    return parse_rhs_main(rhs, first, last, context, rcontext, unused);
  }

  template <typename RHS, typename Iterator, typename Context,
            typename ActualAttribute, typename ExplicitAttrPropagation>
  static bool
  call_rule_definition(RHS const &rhs, char const *rule_name, Iterator &first,
                       Iterator const &last, Context const &context,
                       ActualAttribute &attr, ExplicitAttrPropagation) {
    boost::ignore_unused(rule_name);

    // do down-stream transformation, provides attribute for
    // rhs parser
    typedef traits::transform_attribute<ActualAttribute, Attribute, parser_id>
        transform;

    typedef typename transform::type transform_attr;
    transform_attr attr_ = transform::pre(attr);

    bool ok_parse
        // Creates a place to hold the result of parse_rhs
        // called inside the following scope.
        ;
    {
      // Create a scope to cause the dbg variable below (within
      // the #if...#endif) to call it's DTOR before any
      // modifications are made to the attribute, attr_ passed
      // to parse_rhs (such as might be done in
      // transform::post when, for example,
      // ActualAttribute is a recursive variant).
#if defined(BOOST_SPIRIT_X3_DEBUG)
      context_debug<Iterator, transform_attr> dbg(rule_name, first, last, attr_,
                                                  ok_parse);
#endif
      ok_parse = parse_rhs(
          rhs, first, last, context, attr_, attr_,
          mpl::bool_<(RHS::has_action && !ExplicitAttrPropagation::value)>());
    }
    if (ok_parse) {
      // do up-stream transformation, this integrates the results
      // back into the original attribute value, if appropriate
      transform::post(attr, std::forward<transform_attr>(attr_));
    }
    return ok_parse;
  }
};
} // namespace detail
} // namespace x3
} // namespace spirit
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "HttpServer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"
#include <archive_entry.h>
#include "Base/Error.h"
#include <boost/asio/ip/tcp.hpp>
using tcp = boost::asio::ip::tcp;

HttpServer::Request::Request(int nbpage) : mNbPage(nbpage), mSemaphore(new Semaphore(0)), mBuff(new char[mBuffLen]), mArchive(archive_write_new())
{
	archive_write_set_format_zip(mArchive);
	//archive_write_set_format_pax_restricted(mArchive);
	archive_write_open_memory(mArchive, mBuff, mBuffLen, &mSize);

}

HttpServer::Request::~Request()
{
	delete mSemaphore;
	if (mIsDelete == false)
	{
		archive_write_close(mArchive);
		archive_write_free(mArchive);
		delete mBuff;
	}
}

std::unique_ptr<Docapost::IA::Tesseract::MemoryFileBuffer> HttpServer::Request::GetOutput()
{
	archive_write_close(mArchive);
	archive_write_free(mArchive);
	auto mem = std::make_unique<Docapost::IA::Tesseract::ArrayMemoryFileBuffer>((unsigned char*)mBuff, mSize);
	mIsDelete = true;
	return mem;
}

void HttpServer::Request::AddEntry(MasterFileStatus* file, void* data, size_t len, std::string ext)
{
	if (mIsDelete)
		return;
	struct archive_entry *entry = archive_entry_new();
	auto filenameNoExt = boost::filesystem::change_extension(file->name, "").string();
	if(file->filePosition >= 0)
	{
		archive_entry_set_pathname(entry, (boost::format("%s/%s-%i%s") % filenameNoExt % filenameNoExt % file->filePosition % ext).str().c_str());
	}
	else
	{
		archive_entry_set_pathname(entry, (boost::format("%s/%s%s") % filenameNoExt % filenameNoExt % ext).str().c_str());
	}
	archive_entry_set_size(entry, len);
	archive_entry_set_filetype(entry, AE_IFREG);
	archive_write_header(mArchive, entry);
	archive_write_data(mArchive, data, len);
	archive_entry_free(entry);
}

void HttpServer::FileProcessed(MasterFileStatus* file)
{
	auto re = mRequests[file->uid];

	if (re == nullptr)
		return;

	re->AddEntry(file, file->buffer->data(), file->buffer->len(), mTesseractRunner.ocrFactory().GetExtension());
	for(int i = 0; i < file->result->size(); i++)
	{
		auto& text = (*file->result)[i];
		re->AddEntry(file, (char*)text.data(), text.size(), mTesseractRunner.ocrFactory().GetTextExtension()[i]);
	}
	re->Release();
	mRequests.erase(file->uid);
}

HttpServer::HttpServer(Docapost::IA::Tesseract::MasterProcessingWorker& tessR, std::wstring u, int p) : mTesseractRunner(tessR)
{
	onEndProcessFile = mTesseractRunner.onEndProcessFile.connect(boost::bind(&HttpServer::FileProcessed, this, _1));
	std::thread t { [&] ()
	{
		CatchAllErrorSignals();
		CatchAllExceptions();
		svr.get("/", [&](const httplib::Request& req, httplib::Response& res) {
			rapidjson::StringBuffer s;
			rapidjson::Writer<rapidjson::StringBuffer> writer(s);
			writer.StartObject();
			writer.Key("Total");
			writer.Uint(mTesseractRunner.Total());
			writer.Key("Done");
			writer.Uint(mTesseractRunner.Done());
			writer.Key("Remote");
			writer.Uint(mTesseractRunner.TotalRemoteThreads());
			writer.Key("Local");
			writer.Uint(mTesseractRunner.NbThreads());
			writer.EndObject();
			res.set_content(s.GetString(), "text/plain");
		});
		svr.post ("/", [&](const httplib::Request& req, httplib::Response& res) {
			CatchAllErrorSignals();
			CatchAllExceptions();
			int i = 0;
			for(auto& f : req.files)
			{
				auto file = boost::filesystem::path(f.second.filename);
				if(f.first == "image" && file.has_extension() && mTesseractRunner.extensions.count(file.extension().string()))
				{
					if(file.extension().string() == ".pdf")
					{
						char* img = new char[f.second.length];
						memcpy(img, req.body.data() + f.second.offset, f.second.length);

						std::vector<boost::uuids::uuid> uids;
						auto nbPage = mTesseractRunner.AddPdfFile(f.second.filename, img, f.second.length, uids);

						Request* re = new Request(nbPage);
						for (auto& uid : uids)
							mRequests[uid] = re;

						re->Wait();

						auto buff = re->GetOutput();
						res.set_content((char*)buff->data(), buff->len(), "application/zip");
						delete re;
						continue;
					}
					else
					{
						char* img = new char[f.second.length];
						memcpy(img, req.body.data() + f.second.offset, f.second.length);

						boost::uuids::uuid uid;
						mTesseractRunner.AddImageFile(f.second.filename, img, f.second.length, uid);

						Request* re = new Request(1);
						mRequests[uid] = re;

						re->Wait();

						auto buff = re->GetOutput();
						res.set_content((char*)buff->data(), buff->len(), "application/zip");
						delete re;
						continue;
					}
				}
			}

		});

		svr.listen("0.0.0.0", 8888);
		svr.stop();
	}};
	t.detach();
}

HttpServer::~HttpServer()
{
	onEndProcessFile.disconnect();
	svr.stop();
}

max_stars_repo_name: labinnovationdocapost/ocrAutomator

max_issues_repo_name: labinnovationdocapost/ocrAutomator

max_forks_repo_name: labinnovationdocapost/ocrAutomator