text:
/**************************************************************************
** Copyright (C) 2015 Christian Manning
**
** This software may be modified and distributed under the terms
** of the MIT license.  See the LICENSE file for details.
**************************************************************************/

#include <openssl/md5.h>

#include <boost/hana/ext/std.hpp>
#include <boost/algorithm/hex.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#include <boost/range/adaptors.hpp>

#include <jbson/json_reader.hpp>

#include <lastfmpp/detail/service_impl.hpp>
#include <lastfmpp/detail/transform.hpp>
#include <lastfmpp/detail/error.hpp>

namespace lastfmpp {

namespace hana = boost::hana;

namespace {
struct to_doc_impl {
    jbson::document operator()(std::string body) const {
        auto doc = jbson::read_json(body);
        detail::check_error(doc);
        return doc;
    }
};
}
static constexpr to_doc_impl to_doc{};

service::impl::impl(std::experimental::string_view api_key, std::experimental::string_view shared_secret,
                    std::experimental::optional<std::experimental::string_view> session_key)
    : cas_client(uri_t{base_url.to_string()}), api_key(api_key), shared_secret(shared_secret) {
    assert(!api_key.empty());
    assert(!shared_secret.empty());
    if(session_key) {
        this->session_key = session_key->to_string();
    }
}

pplx::task<jbson::document> service::impl::get(std::experimental::string_view method, params_t params) {
    auto query = uri_builder().set_query(make_query(make_params(method, std::move(params), false))).to_string();
    return cas_client.request(web::http::methods::GET, query).then(response_to_u8).then(to_doc);
}

pplx::task<jbson::document> service::impl::post_session(std::experimental::string_view method, params_t params) {
    params.emplace_back("sk", get_session_key());
    return post(method, std::move(params));
}

pplx::task<jbson::document> service::impl::post(std::experimental::string_view method, params_t params) {
    auto query = make_query(make_params(method, std::move(params), true));
    return cas_client.request(web::http::methods::POST, "", query, U("application/x-www-form-urlencoded"))
        .then(response_to_u8)
        .then(to_doc);
}

encoded_params_t service::impl::make_params(std::experimental::string_view method, params_t params,
                                            bool needs_signature) {
    params.emplace_back("api_key", api_key);
    params.emplace_back("method", method.to_string());

    auto encoded_params = transform_copy(std::move(params), [](auto&& param) {
        return hana::transform(std::forward<decltype(param)>(param), [](auto&& query) {
            return uri_t::encode_uri(to_string_t(std::forward<decltype(query)>(query)), uri_t::components::query);
        });
    });

    boost::sort(encoded_params, [](auto&& a, auto&& b) { return std::get<0>(a) < std::get<0>(b); });

    if(needs_signature) {
        encoded_params.emplace_back("api_sig", sign(encoded_params));
    }

    return encoded_params;
}

utility::string_t service::impl::make_query(encoded_params_t params) {
    params.emplace_back(U("format"), U("json"));
    auto joined_pairs = boost::adaptors::transform(params, [](auto&& param) {
        return hana::unpack(std::forward<decltype(param)>(param), [](auto&& a, auto&& b) { return a + U("=") + b; });
    });
    return boost::algorithm::join(joined_pairs, "&");
}

utility::string_t service::impl::sign(params_t params) {
    auto sig = flatten((params.emplace_back(shared_secret, ""), params));

    std::array<uint8_t, MD5_DIGEST_LENGTH> sigp;
    MD5(reinterpret_cast<const uint8_t*>(sig.c_str()), sig.length(), sigp.data());

    utility::string_t hex_sig;
    hex_sig.reserve(sigp.size() * 2);
    boost::algorithm::hex(sigp, std::back_inserter(hex_sig));
    assert(hex_sig.size() == MD5_DIGEST_LENGTH * 2);

    return hex_sig;
}

std::string service::impl::flatten(const params_t& params) {
    return boost::accumulate(params, std::string{}, [](auto&& out, auto&& param) -> decltype(auto) {
        out += std::get<0>(param) + std::get<1>(param);
        return std::move(out);
    });
}

void service::impl::set_session_key(std::experimental::string_view sk) {
    std::lock_guard<decltype(session_mu)> l(session_mu);
    session_key = sk.to_string();
}

std::string service::impl::get_session_key() const {
    std::shared_lock<std::remove_cv_t<decltype(session_mu)>> l(session_mu);
    return session_key;
}

} // namespace lastfmpp

max_stars_repo_name: chrismanning/lastfmpp

max_issues_repo_name: chrismanning/lastfmpp

max_forks_repo_name: chrismanning/lastfmpp


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <array>
#include <boost/functional/hash.hpp>
#include <cstddef>
#include <utility>
#include <vector>

#include "DataStructures/DataVector.hpp"
#include "DataStructures/FixedHashMap.hpp"
#include "DataStructures/Index.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "DataStructures/Variables.hpp"
#include "Domain/Structure/Direction.hpp"
#include "Domain/Structure/DirectionMap.hpp"
#include "Domain/Structure/Element.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "Domain/Structure/MaxNumberOfNeighbors.hpp"
#include "Evolution/Systems/NewtonianEuler/ConservativeFromPrimitive.hpp"
#include "Evolution/Systems/NewtonianEuler/Tags.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/Gsl.hpp"

namespace NewtonianEuler::fd {
template <typename PrimsTags, typename TagsList, size_t Dim,
          size_t ThermodynamicDim, typename F>
void reconstruct_prims_work(
    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>
        vars_on_lower_face,
    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>
        vars_on_upper_face,
    const F& reconstruct, const Variables<PrimsTags>& volume_prims,
    const EquationsOfState::EquationOfState<false, ThermodynamicDim>& eos,
    const Element<Dim>& element,
    const FixedHashMap<
        maximum_number_of_neighbors(Dim),
        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,
        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,
    const Mesh<Dim>& subcell_mesh, const size_t ghost_zone_size) {
  // Conservative vars tags
  using MassDensityCons = Tags::MassDensityCons;
  using EnergyDensity = Tags::EnergyDensity;
  using MomentumDensity = Tags::MomentumDensity<Dim>;

  // Primitive vars tags
  using MassDensity = Tags::MassDensity<DataVector>;
  using Velocity = Tags::Velocity<DataVector, Dim>;
  using SpecificInternalEnergy = Tags::SpecificInternalEnergy<DataVector>;
  using Pressure = Tags::Pressure<DataVector>;

  using prim_tags_for_reconstruction =
      tmpl::list<MassDensity, Velocity, Pressure>;

  ASSERT(Mesh<Dim>(subcell_mesh.extents(0), subcell_mesh.basis(0),
                   subcell_mesh.quadrature(0)) == subcell_mesh,
         "The subcell mesh should be isotropic but got " << subcell_mesh);
  const size_t volume_num_pts = subcell_mesh.number_of_grid_points();
  const size_t reconstructed_num_pts =
      (subcell_mesh.extents(0) + 1) *
      subcell_mesh.extents().slice_away(0).product();
  const size_t neighbor_num_pts =
      ghost_zone_size * subcell_mesh.extents().slice_away(0).product();
  size_t vars_in_neighbor_count = 0;
  tmpl::for_each<prim_tags_for_reconstruction>(
      [&element, &neighbor_data, neighbor_num_pts, &reconstruct,
       reconstructed_num_pts, volume_num_pts, &volume_prims,
       &vars_in_neighbor_count, &vars_on_lower_face, &vars_on_upper_face,
       &subcell_mesh](auto tag_v) {
        using tag = tmpl::type_from<decltype(tag_v)>;
        auto& volume_tensor = get<tag>(volume_prims);

        const size_t number_of_components = volume_tensor.size();
        const gsl::span<const double> volume_vars = gsl::make_span(
            volume_tensor[0].data(), number_of_components * volume_num_pts);
        std::array<gsl::span<double>, Dim> upper_face_vars{};
        std::array<gsl::span<double>, Dim> lower_face_vars{};
        for (size_t i = 0; i < Dim; ++i) {
          gsl::at(upper_face_vars, i) = gsl::make_span(
              get<tag>(gsl::at(*vars_on_upper_face, i))[0].data(),
              number_of_components * reconstructed_num_pts);
          gsl::at(lower_face_vars, i) = gsl::make_span(
              get<tag>(gsl::at(*vars_on_lower_face, i))[0].data(),
              number_of_components * reconstructed_num_pts);
        }

        DirectionMap<Dim, gsl::span<const double>> ghost_cell_vars{};
        for (const auto& direction : Direction<Dim>::all_directions()) {
          const auto& neighbors_in_direction =
              element.neighbors().at(direction);
          ASSERT(neighbors_in_direction.size() == 1,
                 "Currently only support one neighbor in each direction, but "
                 "got "
                     << neighbors_in_direction.size() << " in direction "
                     << direction);
          ghost_cell_vars[direction] = gsl::make_span(
              &neighbor_data.at(std::pair{
                  direction,
                  *neighbors_in_direction
                       .begin()})[vars_in_neighbor_count * neighbor_num_pts],
              number_of_components * neighbor_num_pts);
        }

        reconstruct(make_not_null(&upper_face_vars),
                    make_not_null(&lower_face_vars), volume_vars,
                    ghost_cell_vars, subcell_mesh.extents(),
                    number_of_components);

        vars_in_neighbor_count += number_of_components;
      });

  for (size_t i = 0; i < Dim; ++i) {
    auto& vars_upper_face = gsl::at(*vars_on_upper_face, i);
    auto& vars_lower_face = gsl::at(*vars_on_lower_face, i);

    if constexpr (ThermodynamicDim == 2) {
      get<SpecificInternalEnergy>(vars_upper_face) =
          eos.specific_internal_energy_from_density_and_pressure(
              get<MassDensity>(vars_upper_face),
              get<Pressure>(vars_upper_face));
      get<SpecificInternalEnergy>(vars_lower_face) =
          eos.specific_internal_energy_from_density_and_pressure(
              get<MassDensity>(vars_lower_face),
              get<Pressure>(vars_lower_face));
    } else {
      get<SpecificInternalEnergy>(vars_upper_face) =
          eos.specific_internal_energy_from_density(
              get<MassDensity>(vars_upper_face));
      get<SpecificInternalEnergy>(vars_lower_face) =
          eos.specific_internal_energy_from_density(
              get<MassDensity>(vars_lower_face));
    }

    // Compute conserved variables on faces
    NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(
        make_not_null(&get<MassDensityCons>(vars_upper_face)),
        make_not_null(&get<MomentumDensity>(vars_upper_face)),
        make_not_null(&get<EnergyDensity>(vars_upper_face)),
        get<MassDensity>(vars_upper_face), get<Velocity>(vars_upper_face),
        get<SpecificInternalEnergy>(vars_upper_face));
    NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(
        make_not_null(&get<MassDensityCons>(vars_lower_face)),
        make_not_null(&get<MomentumDensity>(vars_lower_face)),
        make_not_null(&get<EnergyDensity>(vars_lower_face)),
        get<MassDensity>(vars_lower_face), get<Velocity>(vars_lower_face),
        get<SpecificInternalEnergy>(vars_lower_face));
  }
}

template <typename TagsList, typename PrimsTags, size_t Dim,
          size_t ThermodynamicDim, typename F0, typename F1>
void reconstruct_fd_neighbor_work(
    const gsl::not_null<Variables<TagsList>*> vars_on_face,
    const F0& reconstruct_lower_neighbor, const F1& reconstruct_upper_neighbor,
    const Variables<PrimsTags>& subcell_volume_prims,
    const EquationsOfState::EquationOfState<false, ThermodynamicDim>& eos,
    const Element<Dim>& element,
    const FixedHashMap<
        maximum_number_of_neighbors(Dim),
        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,
        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,
    const Mesh<Dim>& subcell_mesh,
    const Direction<Dim>& direction_to_reconstruct,
    const size_t ghost_zone_size) {
  // Conservative vars tags
  using MassDensityCons = Tags::MassDensityCons;
  using EnergyDensity = Tags::EnergyDensity;
  using MomentumDensity = Tags::MomentumDensity<Dim>;

  // Primitive vars tags
  using MassDensity = Tags::MassDensity<DataVector>;
  using Velocity = Tags::Velocity<DataVector, Dim>;
  using SpecificInternalEnergy = Tags::SpecificInternalEnergy<DataVector>;
  using Pressure = Tags::Pressure<DataVector>;

  using prim_tags_for_reconstruction =
      tmpl::list<MassDensity, Velocity, Pressure>;

  const std::pair mortar_id{
      direction_to_reconstruct,
      *element.neighbors().at(direction_to_reconstruct).begin()};
  Index<Dim> ghost_data_extents = subcell_mesh.extents();
  ghost_data_extents[direction_to_reconstruct.dimension()] = ghost_zone_size;
  Variables<prim_tags_for_reconstruction> neighbor_prims{
      ghost_data_extents.product()};
  {
    ASSERT(neighbor_data.contains(mortar_id),
           "The neighbor data does not contain the mortar: ("
               << mortar_id.first << ',' << mortar_id.second << ")");
    const auto& neighbor_data_in_direction = neighbor_data.at(mortar_id);
    std::copy(neighbor_data_in_direction.begin(),
              std::next(neighbor_data_in_direction.begin(),
                        static_cast<std::ptrdiff_t>(
                            neighbor_prims.number_of_independent_components *
                            ghost_data_extents.product())),
              neighbor_prims.data());
  }

  tmpl::for_each<prim_tags_for_reconstruction>(
      [&direction_to_reconstruct, &ghost_data_extents, &neighbor_prims,
       &reconstruct_lower_neighbor, &reconstruct_upper_neighbor, &subcell_mesh,
       &subcell_volume_prims, &vars_on_face](auto tag_v) {
        using tag = tmpl::type_from<decltype(tag_v)>;
        const auto& tensor_volume = get<tag>(subcell_volume_prims);
        const auto& tensor_neighbor = get<tag>(neighbor_prims);
        auto& tensor_on_face = get<tag>(*vars_on_face);
        if (direction_to_reconstruct.side() == Side::Upper) {
          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();
               ++tensor_index) {
            reconstruct_upper_neighbor(
                make_not_null(&tensor_on_face[tensor_index]),
                tensor_volume[tensor_index], tensor_neighbor[tensor_index],
                subcell_mesh.extents(), ghost_data_extents,
                direction_to_reconstruct);
          }
        } else {
          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();
               ++tensor_index) {
            reconstruct_lower_neighbor(
                make_not_null(&tensor_on_face[tensor_index]),
                tensor_volume[tensor_index], tensor_neighbor[tensor_index],
                subcell_mesh.extents(), ghost_data_extents,
                direction_to_reconstruct);
          }
        }
      });

  if constexpr (ThermodynamicDim == 2) {
    get<SpecificInternalEnergy>(*vars_on_face) =
        eos.specific_internal_energy_from_density_and_pressure(
            get<MassDensity>(*vars_on_face), get<Pressure>(*vars_on_face));
  } else {
    get<SpecificInternalEnergy>(*vars_on_face) =
        eos.specific_internal_energy_from_density(
            get<MassDensity>(*vars_on_face));
  }
  NewtonianEuler::ConservativeFromPrimitive<Dim>::apply(
      make_not_null(&get<MassDensityCons>(*vars_on_face)),
      make_not_null(&get<MomentumDensity>(*vars_on_face)),
      make_not_null(&get<EnergyDensity>(*vars_on_face)),
      get<MassDensity>(*vars_on_face), get<Velocity>(*vars_on_face),
      get<SpecificInternalEnergy>(*vars_on_face));
}
}  // namespace NewtonianEuler::fd

ext: tpp

max_stars_repo_name: nilsvu/spectre

max_issues_repo_name: nilsvu/spectre

max_forks_repo_name: nilsvu/spectre


text:
#include <fcntl.h>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#endif  // USE_OPENCV
#include <stdint.h>

#include <algorithm>
#include <fstream>  // NOLINT(readability/streams)
#include <string>
#include <vector>

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"

const int kProtoReadBytesLimit = INT_MAX;  // Max size of 2 GB minus 1 byte.

namespace caffe {

using namespace boost::property_tree;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;

bool ReadProtoFromTextFile(const char* filename, Message* proto) {
  int fd = open(filename, O_RDONLY);
  CHECK_NE(fd, -1) << "File not found: " << filename;
  FileInputStream* input = new FileInputStream(fd);
  bool success = google::protobuf::TextFormat::Parse(input, proto);
  delete input;
  close(fd);
  return success;
}

void WriteProtoToTextFile(const Message& proto, const char* filename) {
  int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  FileOutputStream* output = new FileOutputStream(fd);
  CHECK(google::protobuf::TextFormat::Print(proto, output));
  delete output;
  close(fd);
}

bool ReadProtoFromBinaryFile(const char* filename, Message* proto) {
  int fd = open(filename, O_RDONLY);
  CHECK_NE(fd, -1) << "File not found: " << filename;
  ZeroCopyInputStream* raw_input = new FileInputStream(fd);
  CodedInputStream* coded_input = new CodedInputStream(raw_input);
  coded_input->SetTotalBytesLimit(kProtoReadBytesLimit, 536870912);

  bool success = proto->ParseFromCodedStream(coded_input);

  delete coded_input;
  delete raw_input;
  close(fd);
  return success;
}

void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
  fstream output(filename, ios::out | ios::trunc | ios::binary);
  CHECK(proto.SerializeToOstream(&output));
}

#ifdef USE_OPENCV
cv::Mat LetterboxImageToCVMat(const string& filename, int width, int height,
    int *ori_w, int *ori_h) {
  cv::Mat cv_img;
  cv::Mat cv_img_origin = cv::imread(filename, CV_LOAD_IMAGE_COLOR);
  if (!cv_img_origin.data) {
    LOG(ERROR) << "Could not open or find file " << filename;
    return cv_img_origin;
  }
  *ori_w = cv_img_origin.cols;
  *ori_h = cv_img_origin.rows;

  // letterbox image size
  int new_w = 0;
  int new_h = 0;
  if (((float)width / *ori_w) < ((float)height / *ori_h)) {
    new_w = width;
    new_h = (int)((float)*ori_h * width / *ori_w);
  } else {
    new_h = height;
    new_w = (int)((float)*ori_w * height / *ori_h);
  }

  // letterbox image
  cv::Mat resized;
  if (new_w != *ori_w || new_h != *ori_h) {
    resize(cv_img_origin, resized, cv::Size(new_w, new_h));
  } else {
    resized = cv_img_origin;
  }
  cv::Mat boxed = cv::Mat::ones(height, width, CV_8UC3);
  boxed.setTo(cv::Scalar(127, 127, 127));
  resized.copyTo(boxed(cv::Rect((width - new_w) / 2, (height - new_h) / 2, new_w, new_h)));

  return boxed;
}

cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width, const bool is_color,
    int* ori_w, int* ori_h) {
  cv::Mat cv_img;
  int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
    CV_LOAD_IMAGE_GRAYSCALE);
  cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
  if (!cv_img_origin.data) {
    LOG(ERROR) << "Could not open or find file " << filename;
    return cv_img_origin;
  }
  *ori_w = cv_img_origin.cols;
  *ori_h = cv_img_origin.rows;
  if (height > 0 && width > 0) {
    cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
  } else {
    cv_img = cv_img_origin;
  }
  return cv_img;
}

cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width, const bool is_color) {
  cv::Mat cv_img;
  int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
    CV_LOAD_IMAGE_GRAYSCALE);
  cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
  if (!cv_img_origin.data) {
    LOG(ERROR) << "Could not open or find file " << filename;
    return cv_img_origin;
  }
  if (height > 0 && width > 0) {
    cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
  } else {
    cv_img = cv_img_origin;
  }
  return cv_img;
}

cv::Mat ReadImageToCVMat(const string& filename,
    const int height, const int width) {
  return ReadImageToCVMat(filename, height, width, true);
}

cv::Mat ReadImageToCVMat(const string& filename,
    const bool is_color) {
  return ReadImageToCVMat(filename, 0, 0, is_color);
}

cv::Mat ReadImageToCVMat(const string& filename) {
  return ReadImageToCVMat(filename, 0, 0, true);
}

// Do the file extension and encoding match?
static bool matchExt(const std::string & fn,
                     std::string en) {
  size_t p = fn.rfind('.');
  std::string ext = p != fn.npos ? fn.substr(p) : fn;
  std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  std::transform(en.begin(), en.end(), en.begin(), ::tolower);
  if ( ext == en )
    return true;
  if ( en == "jpg" && ext == "jpeg" )
    return true;
  return false;
}

bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, const bool is_color,
    const std::string & encoding, Datum* datum) {
  cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color);
  if (cv_img.data) {
    if (encoding.size()) {
      if ( (cv_img.channels() == 3) == is_color && !height && !width &&
          matchExt(filename, encoding) )
        return ReadFileToDatum(filename, label, datum);
      std::vector<uchar> buf;
      cv::imencode("."+encoding, cv_img, buf);
      datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]),
                      buf.size()));
      datum->set_label(label);
      datum->set_encoded(true);
      return true;
    }
    CVMatToDatum(cv_img, datum);
    datum->set_label(label);
    return true;
  } else {
    return false;
  }
}

bool ReadBoxDataToDatum(const string& filename, const string& annoname,
    const map<string, int>& label_map, const int height, const int width,
    const std::string & encoding, Datum* datum) {
  int ori_w, ori_h;
  cv::Mat cv_img = LetterboxImageToCVMat(filename, width, height, &ori_w, &ori_h);
  if (cv_img.data) {
    if (encoding.size()) {
      std::vector<uchar> buf;
      cv::imencode("." + encoding, cv_img, buf);
      datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]), buf.size()));
      datum->set_encoded(true);
    } else {
      CVMatToDatum(cv_img, datum);
    }
    // read xml anno data
    ParseXmlToDatum(annoname, label_map, ori_w, ori_h, width, height, datum);
    return true;
  } else {
    return false;
  }
}
#endif  // USE_OPENCV

int name_to_label(const string& name, const map<string, int>& label_map) {
  map<string, int>::const_iterator it = label_map.find(name);
  if (it == label_map.end())
    return -1;
  else
    return it->second;
}

void pos_to_letterbox(int ori_w, int ori_h, int new_w, int new_h, vector<float> &box) {
  if (((float)new_w / ori_w) < ((float)new_h / ori_h)) {
    int win_h = (int)((float)ori_h * new_w / ori_w);
    // keep x/w ratio, change y/h ratio
    box[1] = (box[1] * win_h + (new_h - win_h) / 2) / new_h;
    box[3] = box[3] * win_h / new_h;
  } else {
    int win_w = (int)((float)ori_w * new_h / ori_h);
    // keep y/h ratio, change x/w ratio
    box[0] = (box[0] * win_w + (new_w - win_w) / 2) / new_w;
    box[2] = box[2] * win_w / new_w;
  }
}

void ParseXmlToDatum(const string& annoname, const map<string, int>& label_map,
    int ori_w, int ori_h, int new_w, int new_h, Datum* datum) {
  ptree pt;
  read_xml(annoname, pt);
  int width(0), height(0);
  try {
    height = pt.get<int>("annotation.size.height");
    width = pt.get<int>("annotation.size.width");
    CHECK_EQ(ori_w, width);
    CHECK_EQ(ori_h, height);
  } catch (const ptree_error &e) {
    LOG(WARNING) << "When paring " << annoname << ": " << e.what();
  }
  datum->clear_float_data();
  BOOST_FOREACH(ptree::value_type &v1, pt.get_child("annotation")) {
    if (v1.first == "object") {
      ptree object = v1.second;
      int label(-1);
      vector<float> box(4, 0);
      int difficult(0);
      BOOST_FOREACH(ptree::value_type &v2, object.get_child("")) {
        ptree pt2 = v2.second;
        if (v2.first == "name") {
          string name = pt2.data();
          // map name to label
          label = name_to_label(name, label_map);
          if (label < 0) {
            LOG(FATAL) << "Anno file " << annoname << " -> unknown name: " << name;
          }
        } else if (v2.first == "bndbox") {
          int xmin = pt2.get("xmin", 0);
          int ymin = pt2.get("ymin", 0);
          int xmax = pt2.get("xmax", 0);
          int ymax = pt2.get("ymax", 0);
          LOG_IF(WARNING, xmin < 0 || xmin > ori_w) << annoname <<
              " bounding box exceeds image boundary";
          LOG_IF(WARNING, xmax < 0 || xmax > ori_w) << annoname <<
              " bounding box exceeds image boundary";
          LOG_IF(WARNING, ymin < 0 || ymin > ori_h) << annoname <<
              " bounding box exceeds image boundary";
          LOG_IF(WARNING, ymax < 0 || ymax > ori_h) << annoname <<
              " bounding box exceeds image boundary";
          LOG_IF(WARNING, xmin > xmax) << annoname <<
              " bounding box exceeds image boundary";
          LOG_IF(WARNING, ymin > ymax) << annoname <<
              " bounding box exceeds image boundary";
          box[0] = float(xmin + (xmax - xmin) / 2.) / ori_w;
          box[1] = float(ymin + (ymax - ymin) / 2.) / ori_h;
          box[2] = float(xmax - xmin) / ori_w;
          box[3] = float(ymax - ymin) / ori_h;
        } else if (v2.first == "difficult") {
          difficult = atoi(pt2.data().c_str());
        }
      }
      pos_to_letterbox(ori_w, ori_h, new_w, new_h, box);
      CHECK_GE(label, 0) << "label must start at 0";
      datum->add_float_data(float(label));
      datum->add_float_data(float(difficult));
      for (int i = 0; i < 4; ++i) {
        datum->add_float_data(box[i]);
      }
    }
  }
}

bool ReadFileToDatum(const string& filename, const int label,
    Datum* datum) {
  std::streampos size;

  fstream file(filename.c_str(), ios::in|ios::binary|ios::ate);
  if (file.is_open()) {
    size = file.tellg();
    std::string buffer(size, ' ');
    file.seekg(0, ios::beg);
    file.read(&buffer[0], size);
    file.close();
    datum->set_data(buffer);
    datum->set_label(label);
    datum->set_encoded(true);
    return true;
  } else {
    return false;
  }
}

#ifdef USE_OPENCV
cv::Mat DecodeDatumToCVMatNative(const Datum& datum) {
  cv::Mat cv_img;
  CHECK(datum.encoded()) << "Datum not encoded";
  const string& data = datum.data();
  std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
  cv_img = cv::imdecode(vec_data, -1);
  if (!cv_img.data) {
    LOG(ERROR) << "Could not decode datum ";
  }
  return cv_img;
}
cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color) {
  cv::Mat cv_img;
  CHECK(datum.encoded()) << "Datum not encoded";
  const string& data = datum.data();
  std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
  int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
    CV_LOAD_IMAGE_GRAYSCALE);
  cv_img = cv::imdecode(vec_data, cv_read_flag);
  if (!cv_img.data) {
    LOG(ERROR) << "Could not decode datum ";
  }
  return cv_img;
}

// If Datum is encoded will decoded using DecodeDatumToCVMat and CVMatToDatum
// If Datum is not encoded will do nothing
bool DecodeDatumNative(Datum* datum) {
  if (datum->encoded()) {
    cv::Mat cv_img = DecodeDatumToCVMatNative((*datum));
    CVMatToDatum(cv_img, datum);
    return true;
  } else {
    return false;
  }
}
bool DecodeDatum(Datum* datum, bool is_color) {
  if (datum->encoded()) {
    cv::Mat cv_img = DecodeDatumToCVMat((*datum), is_color);
    CVMatToDatum(cv_img, datum);
    return true;
  } else {
    return false;
  }
}

void CVMatToDatum(const cv::Mat& cv_img, Datum* datum) {
  CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
  datum->set_channels(cv_img.channels());
  datum->set_height(cv_img.rows);
  datum->set_width(cv_img.cols);
  datum->clear_data();
  datum->clear_float_data();
  datum->set_encoded(false);
  int datum_channels = datum->channels();
  int datum_height = datum->height();
  int datum_width = datum->width();
  int datum_size = datum_channels * datum_height * datum_width;
  std::string buffer(datum_size, ' ');
  for (int h = 0; h < datum_height; ++h) {
    const uchar* ptr = cv_img.ptr<uchar>(h);
    int img_index = 0;
    for (int w = 0; w < datum_width; ++w) {
      for (int c = 0; c < datum_channels; ++c) {
        int datum_index = (c * datum_height + h) * datum_width + w;
        buffer[datum_index] = static_cast<char>(ptr[img_index++]);
      }
    }
  }
  datum->set_data(buffer);
}
#endif  // USE_OPENCV
}  // namespace caffe

ext: cpp


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop

#include <eosio/testing/tester.hpp>
#include <eosio/chain/abi_serializer.hpp>

#include <Runtime/Runtime.h>

#include <fc/variant_object.hpp>
#include <fc/io/json.hpp>
#include <fc/crypto/sha256.hpp>

#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/x509.h>

#include <boost/algorithm/string/predicate.hpp>

#include <contracts.hpp>

#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::testing;
using namespace fc;

using mvo = fc::mutable_variant_object;
using bytes = std::vector<char>;

using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
using BIO_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
using EVP_PKEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;

class rsa_tester : public TESTER {
public:
    void deploy_contract() {
        create_accounts( {N(rsa)} );
        set_code( N(rsa), contracts::rsa_wasm() );
        set_abi( N(rsa), contracts::rsa_abi().data() );
    }

    RSA_ptr new_keys() {
        static bool init = true;
        if( init ) {
            ERR_load_crypto_strings();
            init = false;
        }

        auto rsa = RSA_ptr(RSA_generate_key(2048, 65537, NULL, NULL), ::RSA_free);
        return rsa;
    }

    std::string sign(const RSA_ptr& rsa, const sha256& digest) {
        bytes signature;
        signature.resize(RSA_size(rsa.get()));
        uint32_t len;
        RSA_sign(NID_sha256, (uint8_t*)digest.data(), 32,
                 (unsigned char*)signature.data(), &len, rsa.get());
        return fc::base64_encode(signature.data(), signature.size());
    }

    std::string pem_pubkey(const RSA_ptr& rsa) {
        auto pkey = EVP_PKEY_ptr(EVP_PKEY_new(), ::EVP_PKEY_free);
        EVP_PKEY_set1_RSA(pkey.get(), rsa.get());

        auto mem = BIO_ptr(BIO_new(BIO_s_mem()), ::BIO_free);
        PEM_write_bio_PUBKEY(mem.get(), pkey.get());

        BUF_MEM *bio_buf;
        BIO_get_mem_ptr(mem.get(), &bio_buf);

        std::stringstream ss({bio_buf->data, bio_buf->length});
        std::string pem;

        while (ss) {
            std::string tmp;
            std::getline(ss, tmp);
            if (tmp[0] != '-') {
                pem += tmp;
            }
        }

        return pem;
    }
};

BOOST_AUTO_TEST_SUITE(rsa_tests)

BOOST_FIXTURE_TEST_CASE( success, rsa_tester ) {
    deploy_contract();

    std::string message = "I'm message";
    fc::sha256 digest = fc::sha256::hash(message);
    auto keys = new_keys();
    auto signature = sign(keys, digest);

    push_action(N(rsa), N(verify), N(rsa), mvo()
        ("digest", digest)
        ("sig", signature)
        ("pubkey", pem_pubkey(keys))
    );
}

BOOST_FIXTURE_TEST_CASE( invalid_signature, rsa_tester ) {
    deploy_contract();

    std::string message = "I'm new message";
    fc::sha256 digest = fc::sha256::hash(message);
    auto keys = new_keys();
    auto keys2 = new_keys();
    auto signature = sign(keys2, digest); // <- signature by another key

    BOOST_CHECK_THROW(push_action(N(rsa), N(verify), N(rsa), mvo()
        ("digest", digest)
        ("sig", signature)
        ("pubkey", pem_pubkey(keys))
    ), fc::exception);
}

BOOST_FIXTURE_TEST_CASE( invalid_key, rsa_tester ) {
    deploy_contract();

    std::string message = "I'm new message";
    fc::sha256 digest = fc::sha256::hash(message);
    auto keys = new_keys();
    auto keys2 = new_keys();
    auto signature = sign(keys, digest);
    auto pem = pem_pubkey(keys2); // <- another key

    BOOST_CHECK_THROW(push_action(N(rsa), N(verify), N(rsa), mvo()
        ("digest", digest)
        ("sig", signature)
        ("pubkey", pem)
    ), fc::exception);
}

BOOST_FIXTURE_TEST_CASE( invalid_digest, rsa_tester ) {
    deploy_contract();

    std::string message = "I'm new message";
    std::string message2 = "I'm another new message";

    fc::sha256 digest = fc::sha256::hash(message);
    fc::sha256 digest2 = fc::sha256::hash(message2); // <- digest from another message

    auto keys = new_keys();
    auto signature = sign(keys, digest);

    BOOST_CHECK_THROW(push_action(N(rsa), N(verify), N(rsa), mvo()
        ("digest", digest2)
        ("sig", signature)
        ("pubkey", pem_pubkey(keys))
    ), fc::exception);
}

BOOST_FIXTURE_TEST_CASE( long_message, rsa_tester ) {
    deploy_contract();

    std::string message;
    for (auto i = 0; i < 1024; ++i) { // <- generate long message
        message += "A";
    }

    auto digest = fc::sha256::hash(message);
    auto keys = new_keys();
    auto signature = sign(keys, digest);

    push_action(N(rsa), N(verify), N(rsa), mvo()
        ("digest", digest)
        ("sig", signature)
        ("pubkey", pem_pubkey(keys))
    );
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DaoCasino/dc-blockchain

max_issues_repo_name: DaoCasino/dc-blockchain

max_forks_repo_name: DaoCasino/dc-blockchain


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "arith_uint256.h"
#include "base58.h"
#include "pot.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "main.h"
#include "pubkey.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "streams.h"
#include "sync.h"
#include "txmempool.h"
#include "util.h"
#include "utilstrencodings.h"
#include "hash.h"
#include "tool.h"
#include <stdint.h>
#include <univalue.h>
#include <boost/thread/thread.hpp> // boost::thread::interrupt
#include "wallet/wallet.h"
#include "script/script.h"
#include <secp256k1.h>
#include <secp256k1_recovery.h>

#define MAXRATIO 67
#define MINRATIO 53
#define GAMMA 0.64

const uint256 DiffAdjustNumerator = uint256S("0x010000000000000000");
const arith_uint256 Arith256DiffAdjustNumerator = UintToArith256(DiffAdjustNumerator);
const uint256 DiffAdjustNumeratorHalf = uint256S("0x0100000000");
const uint256 DiffAdjustNumeratorfor55 = uint256S("0x80000000000000");
const arith_uint256 Arith256DiffAdjustNumeratorHalf = UintToArith256(DiffAdjustNumeratorHalf);

const static bool fDebugPODS = true;

#if 1
std::string getLatestBlockGenerationSignature(){
    //LOCK(cs_main);
    uint32_t nHeight = chainActive.Height();
    CBlockIndex* pblockindex = chainActive[nHeight];
    return pblockindex->GetBlockGenerationSignature();
}
int64_t getPastTimeFromLastestBlock(){
   //LOCK(cs_main);
    uint32_t nHeight = chainActive.Height();
    CBlockIndex* pblockindex = chainActive[nHeight];
    int64_t timeNow = GetTime();
    int64_t pos_s = timeNow - pblockindex->GetBlockTime();
    return pos_s;
}

uint64_t getLatestBlockBaseTarget(){
    LOCK(cs_main);
    uint32_t nHeight = chainActive.Height();
    CBlockIndex* pblockindex = chainActive[nHeight];
    return pblockindex->GetBlockBaseTarget();
}

uint256 getPotHash(std::string generationSignature,std::string pubKey){
    uint256 ret = Hash(generationSignature.begin(),generationSignature.end(),pubKey.begin(),pubKey.end());
    return ret;
}

std::string raiseGenerationSignature(std::string pukstr){
    std::string pSignature = getLatestBlockGenerationSignature();
    CPubKey pubkey(pukstr.begin(), pukstr.end());
    std::string strPubKey;
    if (pubkey.IsCompressed() && pubkey.Decompress()) {
        strPubKey = HexStr(ToByteVector(pubkey));
    } else if (!pubkey.IsCompressed()) {
        strPubKey = pukstr;
    }
    uint256 ret = Hash(pSignature.begin(),pSignature.end(),strPubKey.begin(),strPubKey.end());
    return HexStr(ret);
}

bool verifyGenerationSignature(std::string pGS,std::string generationSignature,std::string pukstr){
    CPubKey pubkey(pukstr.begin(), pukstr.end());
    std::string strPubKey;
    if (pubkey.IsCompressed() && pubkey.Decompress()) {
        strPubKey = HexStr(ToByteVector(pubkey));
    } else if (!pubkey.IsCompressed()) {
        strPubKey = pukstr;
    }
    uint256 ret = Hash(pGS.begin(),pGS.end(),strPubKey.begin(),strPubKey.end());
    return generationSignature == HexStr(ret);
}

std::string GetPubKeyForPackage(){
    boost::shared_ptr<CReserveScript> coinbaseScript;
    GetMainSignals().ScriptForPackage(coinbaseScript);

    // If the keypool is exhausted, no script is returned at all.  Catch this.
    if (!coinbaseScript || coinbaseScript->reserveScript.empty()){
        //std::cout<<" error please check your wallet"<<std::endl;
    }
    CPubKey pubkey;
    pubkey = coinbaseScript->Packagerpubkey;
    std::string pukstr;
    if(pubkey.Decompress()){
       std::vector<unsigned char> ret = ToByteVector(pubkey);
       pukstr = HexStr(ret);
    }
    return pukstr;
}
uint64_t calculateHitOfPOT(const uint256 &phash){
    //LogPrintf("Generation Signature Hash is %s\n",HexStr(phash));
    uint64_t hit=0;
    memcpy(&hit,phash.begin(),8);
    arith_uint256 temp = hit+1;
    double logarithm = log(temp.getdouble()) - 2 * log(Arith256DiffAdjustNumeratorHalf.getdouble());
    logarithm = fabs(logarithm);
    uint64_t ulogarithm =  logarithm * 1000;
    arith_uint256 arihit = UintToArith256(DiffAdjustNumeratorfor55) * arith_uint256(ulogarithm) / 1000;
    return ArithToUint256(arihit).GetUint64(0);
}

uint64_t getNextPotRequired(const CBlockIndex* pindexLast){
   uint64_t baseTargetLimt = 0x369D0369D036978; //genesis block base target
   const CBlockIndex* ancestor = NULL;
   if(pindexLast -> nHeight < 3){
       return baseTargetLimt;
   }else{
       ancestor = pindexLast->GetAncestor((pindexLast->nHeight) - 3);
   }
   uint64_t lastTime = pindexLast -> GetBlockTime();
   uint64_t lastBlockParentTime = ancestor->GetBlockTime();
   uint64_t Sa = 0;
   if (lastTime > lastBlockParentTime)
       Sa = (lastTime - lastBlockParentTime)/3;
   uint64_t newBaseTarget = 0;
   if (Sa >= 60){
       uint64_t min = 0;
       if(Sa < MAXRATIO){
           min = Sa;
       }else{
           min = MAXRATIO;
       }
       newBaseTarget = (min * pindexLast->baseTarget) / 60;
   }else{
       uint64_t max = 0;
       if(Sa > MINRATIO){
           max = Sa;
       }else{
           max = MINRATIO;
       }
       newBaseTarget = pindexLast->baseTarget - (pindexLast->baseTarget / 375) * (60 - max) * 4;
       //newBaseTarget = pindexLast->baseTarget - ((60 - max) * 4 * pindexLast->baseTarget) / 375;
   }
   //LogPrintf("NewBaseTarget is %s last time is %s lastBlockParentTime %s\n",newBaseTarget,lastTime,lastBlockParentTime);
   return newBaseTarget;
}

uint256 GetNextCumulativeDifficulty(const CBlockIndex* pindexLast, uint64_t baseTarget, const Consensus::Params& consensusParams)
{
    if (pindexLast == NULL) {
        // return genesis cumulative difficulty
        return consensusParams.genesisCumulativeDifficulty;
    }

    if (baseTarget == 0) {
        return pindexLast->cumulativeDifficulty;
    }

    assert(baseTarget);
    const arith_uint256 prevCumDiff = UintToArith256(pindexLast->cumulativeDifficulty);
    const arith_uint256 denominator(baseTarget);
    arith_uint256 temp(Arith256DiffAdjustNumerator);
    arith_uint256 ret(prevCumDiff);

    temp /= denominator;
    ret  += temp;

    return ArithToUint256(ret);
}

bool CheckProofOfTransaction(const std::string& prevGenerationSignature, const std::string& currPubKey,
        int nHeight, int64_t nTime, uint64_t baseTarget, uint64_t harverstPower, const Consensus::Params& consensusParams, PotErr& checkErr)
{
    checkErr = POT_NO_ERR;

    if (prevGenerationSignature.empty() || currPubKey.empty() || nHeight < 0 || nTime <= 0
            || harverstPower == 0) {
        LogPrintf("POT failed, incorrect args, signatrue:%s, pubkey:%s, height:%d, time:%d, hp:%d\n",
            prevGenerationSignature, currPubKey, nHeight, nTime, harverstPower);
        checkErr = POT_ARGS_ERR;
        return false;
    }

    if (fDebugPODS) {
        LogPrint("pot", "signature:%s, pubkey:%s\n", prevGenerationSignature, currPubKey);
        LogPrint("pot", "height:%d, time:%d, baseTarget:%d\n", nHeight, nTime, baseTarget);
    }

    // Note: in block header public key is compressed, but get hit value with uncompressed
    // public key. So here firstly, we decompress publickey.
    CPubKey pubkey(currPubKey.begin(), currPubKey.end());
    std::string strPubKey;
    if (pubkey.IsCompressed() && pubkey.Decompress()) {
        strPubKey = HexStr(ToByteVector(pubkey));
    } else if (!pubkey.IsCompressed()) {
        strPubKey = currPubKey;
    }

    uint256 geneSignatureHash = getPotHash(prevGenerationSignature, strPubKey);
    uint64_t hit = calculateHitOfPOT(geneSignatureHash);

    arith_uint256 thresold(baseTarget);
    thresold *= arith_uint256((uint64_t)nTime);
    thresold *= arith_uint256((uint64_t)harverstPower);

    LogPrint("pot", "harvest Power:%d\n", harverstPower);
    LogPrint("pot", "hit     :%s\n", arith_uint256(hit).ToString());
    LogPrint("pot", "thresold:%s\n", thresold.ToString());
    if (thresold.CompareTo(arith_uint256(hit)) > 0) {
        return true;
    }

    return false;
}
#endif

max_stars_repo_name: iceXCN/Taucoin

max_issues_repo_name: iceXCN/Taucoin

max_forks_repo_name: iceXCN/Taucoin


text:
 //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. 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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP
#define BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP

#if (defined _MSC_VER) && (_MSC_VER >= 1200)
#  pragma once
#endif

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/permissions.hpp>
#include <boost/interprocess/detail/interprocess_tester.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>
#include <boost/interprocess/sync/windows/named_sync.hpp>
#include <boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp>
#include <boost/interprocess/sync/detail/condition_algorithm_8a.hpp>

namespace boost {
namespace interprocess {
namespace ipcdetail {

class windows_named_condition
{
   /// @cond

   //Non-copyable
   windows_named_condition();
   windows_named_condition(const windows_named_condition &);
   windows_named_condition &operator=(const windows_named_condition &);
   /// @endcond

   public:
   windows_named_condition(create_only_t, const char *name, const permissions &perm = permissions());

   windows_named_condition(open_or_create_t, const char *name, const permissions &perm = permissions());

   windows_named_condition(open_only_t, const char *name);

   ~windows_named_condition();

   //!If there is a thread waiting on *this, change that
   //!thread's state to ready. Otherwise there is no effect.*/
   void notify_one();

   //!Change the state of all threads waiting on *this to ready.
   //!If there are no waiting threads, notify_all() has no effect.
   void notify_all();

   //!Releases the lock on the named_mutex object associated with lock, blocks
   //!the current thread of execution until readied by a call to
   //!this->notify_one() or this->notify_all(), and then reacquires the lock.
   template <typename L>
   void wait(L& lock);

   //!The same as:
   //!while (!pred()) wait(lock)
   template <typename L, typename Pr>
   void wait(L& lock, Pr pred);

   //!Releases the lock on the named_mutex object associated with lock, blocks
   //!the current thread of execution until readied by a call to
   //!this->notify_one() or this->notify_all(), or until time abs_time is reached,
   //!and then reacquires the lock.
   //!Returns: false if time abs_time is reached, otherwise true.
   template <typename L>
   bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time);

   //!The same as:   while (!pred()) {
   //!                  if (!timed_wait(lock, abs_time)) return pred();
   //!               } return true;
   template <typename L, typename Pr>
   bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred);

   static bool remove(const char *name);

   /// @cond
   private:
   friend class interprocess_tester;
   void dont_close_on_destruction();

   template <class InterprocessMutex>
   void do_wait(InterprocessMutex& lock);

   template <class InterprocessMutex>
   bool do_timed_wait(const boost::posix_time::ptime &abs_time, InterprocessMutex& lock);

   struct condition_data
   {
      typedef boost::int32_t           integer_type;
      typedef winapi_semaphore_wrapper semaphore_type;
      typedef winapi_mutex_wrapper     mutex_type;

      integer_type    &get_nwaiters_blocked()
      {  return m_nwaiters_blocked;  }

      integer_type    &get_nwaiters_gone()
      {  return m_nwaiters_gone;  }

      integer_type    &get_nwaiters_to_unblock()
      {  return m_nwaiters_to_unblock;  }

      semaphore_type  &get_sem_block_queue()
      {  return m_sem_block_queue;  }

      semaphore_type  &get_sem_block_lock()
      {  return m_sem_block_lock;  }

      mutex_type      &get_mtx_unblock_lock()
      {  return m_mtx_unblock_lock;  }

      integer_type               m_nwaiters_blocked;
      integer_type               m_nwaiters_gone;
      integer_type               m_nwaiters_to_unblock;
      winapi_semaphore_wrapper   m_sem_block_queue;
      winapi_semaphore_wrapper   m_sem_block_lock;
      winapi_mutex_wrapper       m_mtx_unblock_lock;
   } m_condition_data;

   typedef condition_algorithm_8a<condition_data> algorithm_type;

   class named_cond_callbacks : public windows_named_sync_interface
   {
      typedef __int64 sem_count_t;
      mutable sem_count_t sem_counts [2];

      public:
      named_cond_callbacks(condition_data &cond_data)
         : m_condition_data(cond_data)
      {}

      virtual std::size_t get_data_size() const
      {  return sizeof(sem_counts);   }

      virtual const void *buffer_with_final_data_to_file()
      {
         sem_counts[0] = m_condition_data.m_sem_block_queue.value();
         sem_counts[1] = m_condition_data.m_sem_block_lock.value();
         return &sem_counts;
      }

      virtual const void *buffer_with_init_data_to_file()
      {
         sem_counts[0] = 0;
         sem_counts[1] = 1;
         return &sem_counts;
      }

      virtual void *buffer_to_store_init_data_from_file()
      {  return &sem_counts; }

      virtual bool open(create_enum_t, const char *id_name)
      {
         m_condition_data.m_nwaiters_blocked = 0;
         m_condition_data.m_nwaiters_gone = 0;
         m_condition_data.m_nwaiters_to_unblock = 0;

         //Now open semaphores and mutex.
         //Use local variables + swap to guarantee consistent
         //initialization and cleanup in case any opening fails
         permissions perm;
         perm.set_unrestricted();
         std::string aux_str  = "Global\\bipc.cond.";
         aux_str += id_name;
         std::size_t pos = aux_str.size();

         //sem_block_queue
         aux_str += "_bq";
         winapi_semaphore_wrapper sem_block_queue;
         bool created;
         if(!sem_block_queue.open_or_create
            (aux_str.c_str(), sem_counts[0], winapi_semaphore_wrapper::MaxCount, perm, created))
            return false;
         aux_str.erase(pos);

         //sem_block_lock
         aux_str += "_bl";
         winapi_semaphore_wrapper sem_block_lock;
         if(!sem_block_lock.open_or_create
            (aux_str.c_str(), sem_counts[1], winapi_semaphore_wrapper::MaxCount, perm, created))
            return false;
         aux_str.erase(pos);

         //mtx_unblock_lock
         aux_str += "_ul";
         winapi_mutex_wrapper mtx_unblock_lock;
         if(!mtx_unblock_lock.open_or_create(aux_str.c_str(), perm))
            return false;

         //All ok, commit data
         m_condition_data.m_sem_block_queue.swap(sem_block_queue);
         m_condition_data.m_sem_block_lock.swap(sem_block_lock);
         m_condition_data.m_mtx_unblock_lock.swap(mtx_unblock_lock);
         return true;
      }

      virtual void close()
      {
         m_condition_data.m_sem_block_queue.close();
         m_condition_data.m_sem_block_lock.close();
         m_condition_data.m_mtx_unblock_lock.close();
         m_condition_data.m_nwaiters_blocked = 0;
         m_condition_data.m_nwaiters_gone = 0;
         m_condition_data.m_nwaiters_to_unblock = 0;
      }

      virtual ~named_cond_callbacks()
      {}

      private:
      condition_data &m_condition_data;
   };

   windows_named_sync   m_named_sync;
   /// @endcond
};

inline windows_named_condition::~windows_named_condition()
{
   named_cond_callbacks callbacks(m_condition_data);
   m_named_sync.close(callbacks);
}

inline void windows_named_condition::dont_close_on_destruction()
{}

inline windows_named_condition::windows_named_condition
   (create_only_t, const char *name, const permissions &perm)
   : m_condition_data()
{
   named_cond_callbacks callbacks(m_condition_data);
   m_named_sync.open_or_create(DoCreate, name, perm, callbacks);
}

inline windows_named_condition::windows_named_condition
   (open_or_create_t, const char *name, const permissions &perm)
   : m_condition_data()
{
   named_cond_callbacks callbacks(m_condition_data);
   m_named_sync.open_or_create(DoOpenOrCreate, name, perm, callbacks);
}

inline windows_named_condition::windows_named_condition(open_only_t, const char *name)
   : m_condition_data()
{
   named_cond_callbacks callbacks(m_condition_data);
   m_named_sync.open_or_create(DoOpen, name, permissions(), callbacks);
}

inline void windows_named_condition::notify_one()
{  algorithm_type::signal(m_condition_data, false);  }

inline void windows_named_condition::notify_all()
{  algorithm_type::signal(m_condition_data, true);  }

template<class InterprocessMutex>
inline void windows_named_condition::do_wait(InterprocessMutex &mut)
{  algorithm_type::wait(m_condition_data, false, boost::posix_time::ptime(), mut);  }

template<class InterprocessMutex>
inline bool windows_named_condition::do_timed_wait
   (const boost::posix_time::ptime &abs_time, InterprocessMutex &mut)
{  return algorithm_type::wait(m_condition_data, true, abs_time, mut);  }

template <typename L>
inline void windows_named_condition::wait(L& lock)
{
   if (!lock)
      throw lock_exception();
   this->do_wait(*lock.mutex());
}

template <typename L, typename Pr>
inline void windows_named_condition::wait(L& lock, Pr pred)
{
   if (!lock)
      throw lock_exception();
   while (!pred())
      this->do_wait(*lock.mutex());
}

template <typename L>
inline bool windows_named_condition::timed_wait
   (L& lock, const boost::posix_time::ptime &abs_time)
{
   if(abs_time == boost::posix_time::pos_infin){
      this->wait(lock);
      return true;
   }
   if (!lock)
      throw lock_exception();
   return this->do_timed_wait(abs_time, *lock.mutex());
}

template <typename L, typename Pr>
inline bool windows_named_condition::timed_wait
   (L& lock, const boost::posix_time::ptime &abs_time, Pr pred)
{
   if(abs_time == boost::posix_time::pos_infin){
      this->wait(lock, pred);
      return true;
   }
   if (!lock)
      throw lock_exception();

   while (!pred()){
      if(!this->do_timed_wait(abs_time, *lock.mutex())){
         return pred();
      }
   }
   return true;
}

inline bool windows_named_condition::remove(const char *name)
{
   return windows_named_sync::remove(name);
}

}  //namespace ipcdetail {
}  //namespace interprocess {
}  //namespace boost {

#include <boost/interprocess/detail/config_end.hpp>

#endif   //BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP

ext: hpp

max_stars_repo_name: newcommerdontblame/ionlib

max_issues_repo_name: newcommerdontblame/ionlib

max_forks_repo_name: newcommerdontblame/ionlib


text:
/****************************************************************************
 *  hipipe library
 *  Copyright (c) 2017, Cognexa Solutions s.r.o.
 *  Copyright (c) 2018, Iterait a.s.
 *  Author(s) Filip Matzner
 *
 *  This file is distributed under the MIT License.
 *  See the accompanying file LICENSE.txt for the complete license agreement.
 ****************************************************************************/

#pragma once
#include <hipipe/build_config.hpp>
#ifdef HIPIPE_BUILD_PYTHON

#include <boost/python.hpp>

#include <experimental/filesystem>

namespace hipipe::python::utility {

struct fs_path_to_python_str {
    static PyObject* convert(const std::experimental::filesystem::path& path);
};

struct fs_path_from_python_str {
    fs_path_from_python_str();

    static void* convertible(PyObject* obj_ptr);

    static void construct(PyObject* obj_ptr,
                          boost::python::converter::rvalue_from_python_stage1_data* data);
};

}  // namespace hipipe::python::utility

#endif  // HIPIPE_BUILD_PYTHON

max_stars_repo_name: iterait/hipipe

max_issues_repo_name: iterait/hipipe

max_forks_repo_name: iterait/hipipe


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#include <algorithm>
#include <iostream>
#include <numeric>

#include <boost/utility.hpp>

#include "testutil/gtest-util.h"
#include "util/bit-util.h"
#include "util/cpu-info.h"

#include "common/names.h"
#include "runtime/multi-precision.h"

namespace impala {

TEST(BitUtil, UnsignedWidth) {
  EXPECT_EQ(BitUtil::UnsignedWidth<signed char>(), 7);
  EXPECT_EQ(BitUtil::UnsignedWidth<unsigned char>(), 8);
  EXPECT_EQ(BitUtil::UnsignedWidth<volatile long long>(), 63);
  EXPECT_EQ(BitUtil::UnsignedWidth<unsigned long long&>(), 64);
  EXPECT_EQ(BitUtil::UnsignedWidth<const int128_t&>(), 127);
  EXPECT_EQ(BitUtil::UnsignedWidth<const volatile unsigned __int128&>(), 128);
}

TEST(BitUtil, Sign) {
  EXPECT_EQ(BitUtil::Sign<int>(0), 1);
  EXPECT_EQ(BitUtil::Sign<int>(1), 1);
  EXPECT_EQ(BitUtil::Sign<int>(-1), -1);
  EXPECT_EQ(BitUtil::Sign<int>(200), 1);
  EXPECT_EQ(BitUtil::Sign<int>(-200), -1);
  EXPECT_EQ(BitUtil::Sign<unsigned int>(0), 1);
  EXPECT_EQ(BitUtil::Sign<unsigned int>(1), 1);
  EXPECT_EQ(BitUtil::Sign<unsigned int>(-1U), 1);
  EXPECT_EQ(BitUtil::Sign<unsigned int>(200), 1);
  EXPECT_EQ(BitUtil::Sign<unsigned int>(-200), 1);
  EXPECT_EQ(BitUtil::Sign<int128_t>(0), 1);
  EXPECT_EQ(BitUtil::Sign<int128_t>(1), 1);
  EXPECT_EQ(BitUtil::Sign<int128_t>(-1), -1);
  EXPECT_EQ(BitUtil::Sign<int128_t>(200), 1);
  EXPECT_EQ(BitUtil::Sign<int128_t>(-200), -1);
}

TEST(BitUtil, Ceil) {
  EXPECT_EQ(BitUtil::Ceil(0, 1), 0);
  EXPECT_EQ(BitUtil::Ceil(1, 1), 1);
  EXPECT_EQ(BitUtil::Ceil(1, 2), 1);
  EXPECT_EQ(BitUtil::Ceil(1, 8), 1);
  EXPECT_EQ(BitUtil::Ceil(7, 8), 1);
  EXPECT_EQ(BitUtil::Ceil(8, 8), 1);
  EXPECT_EQ(BitUtil::Ceil(9, 8), 2);
  EXPECT_EQ(BitUtil::Ceil(9, 9), 1);
  EXPECT_EQ(BitUtil::Ceil(10000000000, 10), 1000000000);
  EXPECT_EQ(BitUtil::Ceil(10, 10000000000), 1);
  EXPECT_EQ(BitUtil::Ceil(100000000000, 10000000000), 10);
}

TEST(BitUtil, RoundUp) {
  EXPECT_EQ(BitUtil::RoundUp(0, 1), 0);
  EXPECT_EQ(BitUtil::RoundUp(1, 1), 1);
  EXPECT_EQ(BitUtil::RoundUp(1, 2), 2);
  EXPECT_EQ(BitUtil::RoundUp(6, 2), 6);
  EXPECT_EQ(BitUtil::RoundUp(7, 3), 9);
  EXPECT_EQ(BitUtil::RoundUp(9, 9), 9);
  EXPECT_EQ(BitUtil::RoundUp(10000000001, 10), 10000000010);
  EXPECT_EQ(BitUtil::RoundUp(10, 10000000000), 10000000000);
  EXPECT_EQ(BitUtil::RoundUp(100000000000, 10000000000), 100000000000);
}

TEST(BitUtil, RoundDown) {
  EXPECT_EQ(BitUtil::RoundDown(0, 1), 0);
  EXPECT_EQ(BitUtil::RoundDown(1, 1), 1);
  EXPECT_EQ(BitUtil::RoundDown(1, 2), 0);
  EXPECT_EQ(BitUtil::RoundDown(6, 2), 6);
  EXPECT_EQ(BitUtil::RoundDown(7, 3), 6);
  EXPECT_EQ(BitUtil::RoundDown(9, 9), 9);
  EXPECT_EQ(BitUtil::RoundDown(10000000001, 10), 10000000000);
  EXPECT_EQ(BitUtil::RoundDown(10, 10000000000), 0);
  EXPECT_EQ(BitUtil::RoundDown(100000000000, 10000000000), 100000000000);
}

TEST(BitUtil, Popcount) {
  EXPECT_EQ(BitUtil::Popcount(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4);
  EXPECT_EQ(BitUtil::PopcountNoHw(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4);
  EXPECT_EQ(BitUtil::Popcount(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6);
  EXPECT_EQ(BitUtil::PopcountNoHw(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6);
  EXPECT_EQ(BitUtil::Popcount(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8);
  EXPECT_EQ(BitUtil::PopcountNoHw(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8);
  EXPECT_EQ(BitUtil::Popcount(0), 0);
  EXPECT_EQ(BitUtil::PopcountNoHw(0), 0);
}

TEST(BitUtil, TrailingBits) {
  EXPECT_EQ(BitUtil::TrailingBits(BOOST_BINARY(1 1 1 1 1 1 1 1), 0), 0);
  EXPECT_EQ(BitUtil::TrailingBits(BOOST_BINARY(1 1 1 1 1 1 1 1), 1), 1);
  EXPECT_EQ(BitUtil::TrailingBits(BOOST_BINARY(1 1 1 1 1 1 1 1), 64),
            BOOST_BINARY(1 1 1 1 1 1 1 1));
  EXPECT_EQ(BitUtil::TrailingBits(BOOST_BINARY(1 1 1 1 1 1 1 1), 100),
            BOOST_BINARY(1 1 1 1 1 1 1 1));
  EXPECT_EQ(BitUtil::TrailingBits(0, 1), 0);
  EXPECT_EQ(BitUtil::TrailingBits(0, 64), 0);
  EXPECT_EQ(BitUtil::TrailingBits(1ULL << 63, 0), 0);
  EXPECT_EQ(BitUtil::TrailingBits(1ULL << 63, 63), 0);
  EXPECT_EQ(BitUtil::TrailingBits(1ULL << 63, 64), 1ULL << 63);
}

// Test different SIMD functionality units with an input/output buffer.
// CpuFlag parameter indicates SIMD routine to be tested:
//   CpuInfo::SSSE3 for ByteSwapSSE_Unit;
//   CpuInfo::AVX2 for ByteSwapAVX2_Unit;
void TestByteSwapSimd_Unit(const int64_t CpuFlag) {
  void (*bswap_fptr)(const uint8_t* src, uint8_t* dst) = NULL;
  int buf_size = 0;
  if (CpuFlag == CpuInfo::SSSE3) {
    buf_size = 16;
    bswap_fptr = SimdByteSwap::ByteSwap128;
  } else {
    static const int64_t AVX2_MASK = CpuInfo::AVX2;
    ASSERT_EQ(CpuFlag, AVX2_MASK);
    buf_size = 32;
    bswap_fptr = SimdByteSwap::ByteSwap256;
  }

  DCHECK(bswap_fptr != NULL);
  // IMPALA-4058: test that bswap_fptr works when it reads to o writes from memory with
  // any alignment.
  static const size_t MAX_ALIGNMENT = 64;
  uint8_t src_buf[buf_size + MAX_ALIGNMENT];
  uint8_t dst_buf[buf_size + MAX_ALIGNMENT];
  std::iota(src_buf, src_buf + buf_size + MAX_ALIGNMENT, 1);
  for (size_t i = 0; i < MAX_ALIGNMENT; ++i) {
    for (size_t j = 0; j < MAX_ALIGNMENT; ++j) {
      std::fill(dst_buf, dst_buf + buf_size + MAX_ALIGNMENT, 0);
      bswap_fptr(src_buf + i, dst_buf + j);

      // Validate the swap results.
      for (int k = 0; k < buf_size; ++k) {
        EXPECT_EQ(dst_buf[k + j], 1 + i + buf_size - k - 1);
        EXPECT_EQ(dst_buf[k + j], src_buf[i + buf_size - k - 1]);
      }
    }
  }
}

// Test the logic of ByteSwapSimd control flow using specified SIMD routine with an
// input/output buffer.
// CpuFlag parameter indicates SIMD routine to be tested:
//   CpuInfo::SSSE3 for SimdByteSwap::ByteSwapSSE_Unit;
//   CpuInfo::AVX2 for SimdByteSwap::ByteSwapAVX2_Unit;
//   CpuFlag == 0 for BitUtil::ByteSwap;
// buf_size parameter indicates the size of input/output buffer.
void TestByteSwapSimd(const int64_t CpuFlag, const int buf_size) {
  if (buf_size <= 0) return;
  uint8_t src_buf[buf_size];
  uint8_t dst_buf[buf_size];
  std::iota(src_buf, src_buf + buf_size, 0);

  int start_size = 0;
  if (CpuFlag == CpuInfo::SSSE3) {
    start_size = 16;
  } else if (CpuFlag == CpuInfo::AVX2) {
    start_size = 32;
  }

  for (int i = start_size; i < buf_size; ++i) {
    // Initialize dst buffer and swap i bytes.
    memset(dst_buf, 0, buf_size);
    if (CpuFlag == CpuInfo::SSSE3) {
      SimdByteSwap::ByteSwapSimd<16>(src_buf, i, dst_buf);
    } else if (CpuFlag == CpuInfo::AVX2) {
      SimdByteSwap::ByteSwapSimd<32>(src_buf, i, dst_buf);
    } else {
      // CpuFlag == 0: test the internal logic of BitUtil::ByteSwap
      ASSERT_EQ(CpuFlag, 0);
      BitUtil::ByteSwap(dst_buf, src_buf, i);
    }

    // Validate the swap results.
    for (int j = 0; j < i; ++j) {
      EXPECT_EQ(dst_buf[j], i - j - 1);
      EXPECT_EQ(dst_buf[j], src_buf[i - j - 1]);
    }
    // Check that the dst buffer is otherwise unmodified.
    for (int j = i; j < buf_size; ++j) {
      EXPECT_EQ(dst_buf[j], 0);
    }
  }
}

TEST(BitUtil, ByteSwap) {
  EXPECT_EQ(BitUtil::ByteSwap(static_cast<uint32_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(static_cast<uint32_t>(0x11223344)), 0x44332211);

  EXPECT_EQ(BitUtil::ByteSwap(static_cast<int32_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(static_cast<int32_t>(0x11223344)), 0x44332211);

  EXPECT_EQ(BitUtil::ByteSwap(static_cast<uint64_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(
      static_cast<uint64_t>(0x1122334455667788)), 0x8877665544332211);

  EXPECT_EQ(BitUtil::ByteSwap(static_cast<int64_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(
      static_cast<int64_t>(0x1122334455667788)), 0x8877665544332211);

  EXPECT_EQ(BitUtil::ByteSwap(static_cast<int16_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(static_cast<int16_t>(0x1122)), 0x2211);

  EXPECT_EQ(BitUtil::ByteSwap(static_cast<uint16_t>(0)), 0);
  EXPECT_EQ(BitUtil::ByteSwap(static_cast<uint16_t>(0x1122)), 0x2211);

  // Tests for ByteSwap SIMD functions
  if (CpuInfo::IsSupported(CpuInfo::SSSE3)) {
    // Test SSSE3 functionality unit
    TestByteSwapSimd_Unit(CpuInfo::SSSE3);
    // Test ByteSwapSimd() using SSSE3;
    TestByteSwapSimd(CpuInfo::SSSE3, 64);
  }

  if (CpuInfo::IsSupported(CpuInfo::AVX2)) {
    // Test AVX2 functionality unit
    TestByteSwapSimd_Unit(CpuInfo::AVX2);
    // Test ByteSwapSimd() using AVX2;
    TestByteSwapSimd(CpuInfo::AVX2, 64);
  }

  // Test BitUtil::ByteSwap(Black Box Testing)
  for (int i = 0; i <= 32; ++i) TestByteSwapSimd(0, i);
}

TEST(BitUtil, Log2) {
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(1), 0);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(2), 1);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(3), 2);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(4), 2);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(5), 3);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(INT_MAX), 31);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(UINT_MAX), 32);
  EXPECT_EQ(BitUtil::Log2CeilingNonZero64(ULLONG_MAX), 64);
}

TEST(BitUtil, RoundUpToPowerOf2) {
  EXPECT_EQ(BitUtil::RoundUpToPowerOf2(7, 8), 8);
  EXPECT_EQ(BitUtil::RoundUpToPowerOf2(8, 8), 8);
  EXPECT_EQ(BitUtil::RoundUpToPowerOf2(9, 8), 16);
}

TEST(BitUtil, RoundDownToPowerOf2) {
  EXPECT_EQ(BitUtil::RoundDownToPowerOf2(7, 8), 0);
  EXPECT_EQ(BitUtil::RoundDownToPowerOf2(8, 8), 8);
  EXPECT_EQ(BitUtil::RoundDownToPowerOf2(9, 8), 8);
}

TEST(BitUtil, RoundUpDown) {
  EXPECT_EQ(BitUtil::RoundUpNumBytes(7), 1);
  EXPECT_EQ(BitUtil::RoundUpNumBytes(8), 1);
  EXPECT_EQ(BitUtil::RoundUpNumBytes(9), 2);
  EXPECT_EQ(BitUtil::RoundDownNumBytes(7), 0);
  EXPECT_EQ(BitUtil::RoundDownNumBytes(8), 1);
  EXPECT_EQ(BitUtil::RoundDownNumBytes(9), 1);

  EXPECT_EQ(BitUtil::RoundUpNumi32(31), 1);
  EXPECT_EQ(BitUtil::RoundUpNumi32(32), 1);
  EXPECT_EQ(BitUtil::RoundUpNumi32(33), 2);
  EXPECT_EQ(BitUtil::RoundDownNumi32(31), 0);
  EXPECT_EQ(BitUtil::RoundDownNumi32(32), 1);
  EXPECT_EQ(BitUtil::RoundDownNumi32(33), 1);

  EXPECT_EQ(BitUtil::RoundUpNumi64(63), 1);
  EXPECT_EQ(BitUtil::RoundUpNumi64(64), 1);
  EXPECT_EQ(BitUtil::RoundUpNumi64(65), 2);
  EXPECT_EQ(BitUtil::RoundDownNumi64(63), 0);
  EXPECT_EQ(BitUtil::RoundDownNumi64(64), 1);
  EXPECT_EQ(BitUtil::RoundDownNumi64(65), 1);
}

// Prevent inlining so that the compiler can't optimize out the check.
__attribute__((noinline))
int CpuInfoIsSupportedHoistHelper(int64_t cpu_info_flag, int arg) {
  if (CpuInfo::IsSupported(cpu_info_flag)) {
    // Assembly follows similar pattern to popcnt instruction but executes
    // illegal instruction.
    int64_t result;
    __asm__ __volatile__("ud2" : "=a"(result): "mr"(arg): "cc");
    return result;
  } else {
    return 12345;
  }
}

// Regression test for IMPALA-6882 - make sure illegal instruction isn't hoisted out of
// CpuInfo::IsSupported() checks. This doesn't test the bug precisely but is a canary for
// this kind of optimization happening.
TEST(BitUtil, CpuInfoIsSupportedHoist) {
  constexpr int64_t CPU_INFO_FLAG = CpuInfo::SSSE3;
  CpuInfo::TempDisable disable_sssse3(CPU_INFO_FLAG);
  EXPECT_EQ(12345, CpuInfoIsSupportedHoistHelper(CPU_INFO_FLAG, 0));
}

}

IMPALA_TEST_MAIN();

ext: cc

max_stars_repo_name: caofanCPU/Impala

max_issues_repo_name: Pandinosaurus/Impala

max_forks_repo_name: Pandinosaurus/Impala


text:
#include <algorithm>
#include <armadillo>
#include "constants.hpp"
#include "conversion.hpp"

Conversion::Conversion(const double mass, const double length, const double time) {
    const double internal_length = AU2SI_LEN;
    const double internal_mass =   AU2SI_MASS;
    const double internal_time =   AU2SI_TIME;
    const double internal_velocity =  internal_length/internal_time;  // m/s
    const double internal_energy = internal_mass * internal_length * internal_length /
                                    (internal_time * internal_time);
    const double internal_gradient = internal_energy/internal_length;
    //
    const double energy = mass * length * length/(time * time);
    const double gradient = energy/length;
    const double velocity = length/time;
    //
    _energy_au2md = internal_energy/energy;
    _energy_md2au = energy/internal_energy;
    // coordinates
    _crd_au2md = internal_length/length;
    _crd_md2au = length/internal_length;
    // velocities
    _veloc_au2md = internal_velocity/velocity;
    _veloc_md2au = velocity/internal_velocity;
    // gradient
    _grd_au2md = internal_gradient/gradient;
    _grd_md2au = gradient/internal_gradient;
    // mass
    _mass_au2md = internal_mass/mass;
    _mass_md2au = mass/internal_mass;
    //
};


text:
// Use, modification and distribution are 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)

// Copyright Paul A. Bristow 2015 - 2016.
// Copyright Christopher Kormanyos 2015 - 2016.

// This program computes fixed-point negatable limits for various
// precisions and stores them in partial format for a Quickbook table.

#include <iomanip>
#include <iostream>
#include <limits>

#include <boost/fixed_point/fixed_point.hpp>

template<typename fixed_point_type>
void print_limits()
{
  std::cout << std::setprecision(4)
            << "["
            << "[<" << fixed_point_type::range << ", " << fixed_point_type::resolution << ">] "
            << "["  << fixed_point_type::range << "] "
            << "["  << fixed_point_type::resolution << "] "
            << "["  << std::numeric_limits<fixed_point_type>::digits << "] "
            << "["  << std::numeric_limits<fixed_point_type>::digits +1 << "] "
            << "["  << std::numeric_limits<fixed_point_type>::epsilon() << "] "
            << "["  << std::numeric_limits<fixed_point_type>::lowest() << "] "
            << "["  << (std::numeric_limits<fixed_point_type>::min)() << "] "
            << "["  << (std::numeric_limits<fixed_point_type>::max)() << "]"
            << "]"
            << std::endl
            ;
}

int main()
{
  print_limits<boost::fixed_point::negatable< 15,  -16>>();
  print_limits<boost::fixed_point::negatable< 11,  -20>>();
  print_limits<boost::fixed_point::negatable<  0,  -31>>();
  print_limits<boost::fixed_point::negatable< 30,   -1>>();
  print_limits<boost::fixed_point::negatable< 15, -240>>();
  print_limits<boost::fixed_point::negatable<  0, -255>>();
  print_limits<boost::fixed_point::negatable<200,  -55>>();
  print_limits<boost::fixed_point::negatable<  7,   -8>>();
  print_limits<boost::fixed_point::negatable<  0,   -7>>();
  print_limits<boost::fixed_point::negatable<  2,   -5>>();
  print_limits<boost::fixed_point::negatable<  4,  -11>>();
  print_limits<boost::fixed_point::negatable<  7,  -24>>();
  print_limits<boost::fixed_point::negatable< 10,  -53>>();
  print_limits<boost::fixed_point::negatable< 14, -113>>();
}


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/program_options.hpp>
#include <base/logging.h>
#include <base/contrail_ports.h>

#include <pugixml/pugixml.hpp>

#include <base/task.h>
#include <io/event_manager.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/vns_constants.h>
#include <base/misc_utils.h>

#include <cmn/buildinfo.h>
#include <cmn/agent_cmn.h>

#include <cfg/cfg_init.h>
#include <cfg/cfg_mirror.h>

#include <init/agent_param.h>

#include <oper/operdb_init.h>
#include <oper/vrf.h>
#include <oper/multicast.h>
#include <oper/mirror_table.h>
#include <controller/controller_init.h>
#include <controller/controller_vrf_export.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <vrouter/ksync/ksync_init.h>
#include <uve/agent_uve.h>
#include <kstate/kstate.h>
#include <pkt/proto.h>
#include <diag/diag.h>
#include <boost/functional/factory.hpp>
#include <cmn/agent_factory.h>

#include "contrail_agent_init.h"
#define MAX_RETRY 60
namespace opt = boost::program_options;

void RouterIdDepInit(Agent *agent) {
    // Parse config and then connect
    Agent::GetInstance()->controller()->Connect();
    LOG(DEBUG, "Router ID Dependent modules (Nova and BGP) INITIALIZED");
}

bool is_vhost_interface_up() {
    struct ifreq ifr;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, "vhost0");
    int err = ioctl(sock, SIOCGIFFLAGS, &ifr);
    if (err < 0 || !(ifr.ifr_flags & IFF_UP)) {
        close(sock);
        LOG(DEBUG, "vhost is down");
        return false;
    }
    err = ioctl(sock, SIOCGIFADDR, &ifr);
    if (err < 0) {
        close(sock);
        LOG(DEBUG, "vhost is up, but ip is not set");
        return false;
    }
    close(sock);
    return true;
}

bool GetBuildInfo(std::string &build_info_str) {
    return MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info_str);
}

int main(int argc, char *argv[]) {
    AgentParam params;
    srand(unsigned(time(NULL)));
    try {
        params.ParseArguments(argc, argv);
    } catch (...) {
        std::cout << "Invalid arguments. ";
        std::cout << params.options() << std::endl;
        exit(0);
    }

    opt::variables_map var_map = params.var_map();
    if (var_map.count("help")) {
        std::cout << params.options() << std::endl;
        exit(0);
    }

    if (var_map.count("version")) {
        string build_info;
        MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info);
        std::cout << params.options() << std::endl;
        exit(0);
    }

    string init_file = "";
    if (var_map.count("config_file")) {
        init_file = var_map["config_file"].as<string>();
        struct stat s;
        if (stat(init_file.c_str(), &s) != 0) {
            std::cout << "Error opening config file <" << init_file
                 << ">. Error number <" << errno << ">";
            exit(EINVAL);
        }
    }

    // Read agent parameters from config file and arguments
    params.Init(init_file, argv[0]);

    if (!params.cat_is_agent_mocked() &&
         params.loopback_ip() == Ip4Address(0)) {

        uint16_t i;

        for (i = 0; i < MAX_RETRY; i++) {
            std::cout << "INFO: wait vhost0 to be initilaized... "
                << i << "/" << MAX_RETRY << std::endl;
            if (is_vhost_interface_up()) {
                std::cout << "INFO: vhost0 is ready." << std::endl;
                break;
            }
            usleep(5000000); //sleep for 5 seconds
        }

        if (i == MAX_RETRY) {
            std::cout << "INFO: vhost0 is not ready." << std::endl;
            exit(0);
        }
    }

    // Initialize TBB
    // Call to GetScheduler::GetInstance() will also create Task Scheduler
    TaskScheduler::Initialize(params.tbb_thread_count());

    // Initialize the agent-init control class
    ContrailAgentInit init;
    if (params.cat_is_agent_mocked()) {
        init.set_create_vhost(false);
    }

    init.set_agent_param(&params);
    // kick start initialization
    int ret = 0;
    if ((ret = init.Start()) != 0) {
        return ret;
    }

    string build_info;
    GetBuildInfo(build_info);
    MiscUtils::LogVersionInfo(build_info, Category::VROUTER);

    Agent *agent = init.agent();
    TaskScheduler::GetInstance()->set_event_manager(agent->event_manager());
    agent->event_manager()->Run();

    return 0;
}

max_stars_repo_name: EWERK-DIGITAL/tf-controller

max_issues_repo_name: EWERK-DIGITAL/tf-controller

max_forks_repo_name: EWERK-DIGITAL/tf-controller


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/erf_inv.hpp>
#include <boost/math/special_functions/erf.hpp>
#include <eve/function/is_negative.hpp>
#include <eve/function/is_positive.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/platform.hpp>
#include <cmath>

TTS_CASE_TPL("Check eve::erf_inv return type", EVE_TYPE)
{
  TTS_EXPR_IS(eve::erf_inv(T(0)), T);
}

TTS_CASE_TPL("Check eve::erf_inv behavior", EVE_TYPE)
{
  auto eve__erf_inv =  [](auto x) { return eve::erf_inv(x); };

  if constexpr( eve::platform::supports_invalids )
  {
    TTS_IEEE_EQUAL(eve__erf_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );
    TTS_IEEE_EQUAL(eve__erf_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );
    TTS_IEEE_EQUAL(eve__erf_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );
  }

  TTS_ULP_EQUAL(eve__erf_inv(T(35)), eve::nan(eve::as<T>()), 0.5);
  TTS_ULP_EQUAL(eve__erf_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);

  TTS_IEEE_EQUAL(eve__erf_inv(T( 0 )),T(0)  );
  TTS_IEEE_EQUAL(eve__erf_inv(T(-0.)), T(0) );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.1 )), T( boost::math::erf_inv(0.1)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.2 )), T( boost::math::erf_inv(0.2)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.3 )), T( boost::math::erf_inv(0.3)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.5 )), T( boost::math::erf_inv(0.5)),  1 );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.15)), T( boost::math::erf_inv(0.15)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( 0.75)), T( boost::math::erf_inv(0.75)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T(- 0.1 )), T( boost::math::erf_inv(-0.1)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( -0.2 )), T( boost::math::erf_inv(-0.2)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( -0.3 )), T( boost::math::erf_inv(-0.3)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( -0.5 )), T( boost::math::erf_inv(-0.5)),  1 );
  TTS_ULP_EQUAL(eve__erf_inv(T( -0.15)), T( boost::math::erf_inv(-0.15)), 0.5 );
  TTS_ULP_EQUAL(eve__erf_inv(T( -0.75)), T( boost::math::erf_inv(-0.75)), 0.5 );
}

max_stars_repo_name: orao/eve

max_issues_repo_name: orao/eve

max_forks_repo_name: orao/eve


text:
//////////////////////////////////////////////////////////////////////////////
// iterator::transform_iterator::deduce_sig_uf.hpp                          //
//                                                                          //
//  (C) Copyright 2010 Erwann Rogard                                        //
//  Use, modification and distribution are 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)        //
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ITERATOR_TRANSFORM_ITERATOR_DEDUCE_SIG_UF_ER_2010_HPP
#define BOOST_ITERATOR_TRANSFORM_ITERATOR_DEDUCE_SIG_UF_ER_2010_HPP
#include <boost/iterator/iterator_traits.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/utility/result_of.hpp>

namespace boost
{

	namespace detail
  	{
		namespace transform_iterator{

   	 		template <class Iterator>
    		struct deduce_sig_uf
    		{
				typedef typename boost::iterator_reference<Iterator>::type arg_;

				template<typename UnaryFunc>
                struct apply{
					typedef typename boost::result_of<
                		UnaryFunc(arg_)>::type result_;

					struct wrapper{
        				wrapper(const UnaryFunc& f):g(f){}

                        typedef result_ result_type;

						template<typename T>
						result_type operator()(const T& x)const{
                        	return g(x);
                        }
						private:
						mutable UnaryFunc g; // MUST be contained
					};

                	typedef boost::transform_iterator<wrapper,Iterator> type;

					static type call(Iterator it,const UnaryFunc& f){
                		return boost::make_transform_iterator(it,wrapper(f));
                	}
                };
    		};

        }// transform_iterator
	}// detail

    // Activated if UnaryFun::result<F(Arg)>::type defined. See:
    // http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#result_of
    template <class UnaryFunc, class Iterator>
    typename detail::transform_iterator::deduce_sig_uf<Iterator>
        ::template apply<UnaryFunc>::type
    make_transform_iterator2(
        Iterator it,
        UnaryFunc fun,
        typename UnaryFunc::template result<UnaryFunc(
            typename detail::transform_iterator::deduce_sig_uf<Iterator>::arg_
        )>::type* = 0
    )
    {
    	typedef typename
        	detail::transform_iterator::deduce_sig_uf<Iterator> meta_;
    	return meta_::template apply<UnaryFunc>::call(it,fun);
    }

    // Activated if UnaryFun::result_type defined. See:
    // http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#result_of
    template <class UnaryFunc, class Iterator>
    boost::transform_iterator<UnaryFunc,Iterator>
    make_transform_iterator2(
        Iterator it,
        UnaryFunc fun,
        typename UnaryFunc::result_type* = 0
    )
    {
    	return boost::make_transform_iterator(it,fun);
    }

}// boost

#endif


text:
#include "NuiPolygonMesh.h"

#include "Foundation/NuiLogger.h"

#include <pcl/filters/voxel_grid.h>
#include <pcl/surface/gp3.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>

#include <boost/make_shared.hpp>

NuiPolygonMesh::NuiPolygonMesh()
	: m_dirty(false)
	, m_numEvaluatedTriangles(0)
{

}

NuiPolygonMesh::~NuiPolygonMesh()
{
	clear();
}

void	NuiPolygonMesh::clear()
{
	m_indices.clear();
	m_cloud.clear();
	//m_mesh.cloud.clear();
	m_numEvaluatedTriangles = 0;
	setDirty();
}

void	NuiPolygonMesh::calculateMesh(pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_with_normals, float leafSize)
{
	LOG4CPLUS_INFO(NuiLogger::instance().consoleLogger(), "Calculating polygon mesh...");

	// Create search tree*
	pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree2(new pcl::search::KdTree<pcl::PointXYZRGBNormal>);
	tree2->setInputCloud(cloud_with_normals);

	// Initialize objects
	pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3;

	// Set the maximum distance between connected points (maximum edge length)
	gp3.setSearchRadius(leafSize * 2.0);

	// Set typical values for the parameters
	gp3.setMu(2);
	gp3.setMaximumNearestNeighbors(100);
	gp3.setMaximumSurfaceAngle(M_PI / 2); // 45 degrees
	gp3.setMinimumAngle(M_PI / 36); // 10 degrees
	gp3.setMaximumAngle(2.5 * M_PI / 3); // 120 degrees
	gp3.setNormalConsistency(false);

	// Get result
	gp3.setInputCloud(cloud_with_normals);
	gp3.setSearchMethod(tree2);

	gp3.reconstruct(m_mesh);
	setDirty();
	LOG4CPLUS_INFO(NuiLogger::instance().consoleLogger(), "Calculate polygon mesh completed.");
}

void	NuiPolygonMesh::save(std::string file)
{
	LOG4CPLUS_INFO(NuiLogger::instance().consoleLogger(), "Saving polygon mesh...");
	std::string filePLY = file;
	filePLY.append(".ply");
	pcl::io::savePLYFile(filePLY, m_mesh, 5);
	LOG4CPLUS_INFO(NuiLogger::instance().consoleLogger(), "Save polygon mesh completed.");
}

void	NuiPolygonMesh::evaluateMesh()
{
	int numTriangles = getTrianglesNum();
	if (m_numEvaluatedTriangles >= numTriangles)
		return;
	for (int i = m_numEvaluatedTriangles; i < numTriangles; i++)
	{
		m_indices.insert(m_indices.end(), m_mesh.polygons.at(i).vertices.begin(), m_mesh.polygons.at(i).vertices.end());
	}
	pcl::fromPCLPointCloud2(m_mesh.cloud, m_cloud);
	m_numEvaluatedTriangles = numTriangles;
}

const pcl::PointXYZRGBNormal*		NuiPolygonMesh::getVerticesBuffer() const
{
	return m_cloud.points.data();
}

UINT		NuiPolygonMesh::getVerticesBufferSize() const
{
	return m_cloud.points.size() * sizeof(pcl::PointXYZRGBNormal);
}

const uint32_t*	NuiPolygonMesh::getIndicesBuffer() const
{
	return m_indices.empty() ? NULL : &m_indices[0];
}

UINT		NuiPolygonMesh::getIndicesBufferSize() const
{
	return m_indices.size() * sizeof(uint32_t);
}

max_stars_repo_name: hustztz/NatureUserInterfaceStudio

max_issues_repo_name: hustztz/NatureUserInterfaceStudio

max_forks_repo_name: hustztz/NatureUserInterfaceStudio


text:
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016 Haggi Krey, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "nodecallbacks.h"

// appleseed-maya headers.
#include "utilities/logging.h"
#include "appleseedutils.h"
#include "mayascene.h"
#include "renderqueue.h"
#include "world.h"

// Maya headers.
#include <maya/MItDag.h>
#include <maya/MPlug.h>

// Boost headers.
#include <boost/shared_ptr.hpp>

//
// basic idea:
//      all important messages like update framebuffer, stop rendering etc. are sent via events to the message queue
//      a timer callback reads the next event and execute it.
// IPR:
//      before IPR rendering starts, callbacks are created.
//      a node dirty callback for every node in the scene will put the the node into a list of modified objects.
//          - because we do need the elements only once but the callbacks are called very often, we throw away the callback
//            from a modified node after putting the node into a list and we later remove duplicate entries
//      a idle callback is created. It will go through all elements from the modified list and update it in the renderer if necessary.
//            then the renderer will be called to update its database or restart render, however a renderer handles interactive rendering.
//          - then the modified list is emptied
//          - because we want to be able to modify the same object again after it is updated, the node dirty callbacks are recreated for
//            all the objects in the list.
//      a scene message is created - we will stop the ipr as soon as a new scene is created or another scene is opened
//      a scene message is created - we have to stop everything as soon as the plugin will be removed, otherwise Maya will crash.
//      IMPORTANT:  We do add dirty callbacks for translated nodes only which are saved in the mayaScene::interactiveUpdateMap.
//                  This map is filled by sceneParsing and shader translation process which are called before rendering and during geometry translation.
//                  So the addIPRCallbacks() has to be called after everything is translated.

void IPRAttributeChangedCallback(MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug, void* userPtr)
{
    Logging::debug(MString("IPRAttributeChangedCallback. attribA: ") + plug.name() + " attribB: " + otherPlug.name());
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;

    if (msg & MNodeMessage::kConnectionMade)
    {
        Logging::debug(MString("IPRAttributeChangedCallback. connection created."));
        MString plugName = plug.name();
        std::string pn = plugName.asChar();
        if (pn.find("instObjGroups[") != std::string::npos)
        {
            Logging::debug(MString("IPRAttributeChangedCallback. InstObjGroups affected, checking other side."));
            if (otherPlug.node().hasFn(MFn::kShadingEngine))
            {
                Logging::debug(MString("IPRAttributeChangedCallback. Found shading group on the other side: ") + getObjectName(otherPlug.node()));
                EditableElement& element = mayaScene->editableElements[MMessage::currentCallbackId()];
                element.isDirty = true;
                mayaScene->isAnyDirty = true;
                element.isDeformed = true; // trigger a complete mesh update
            }
        }
    }
    else if (msg & MNodeMessage::kConnectionBroken)
    {
        Logging::debug(MString("IPRAttributeChangedCallback. connection broken."));
    }
}

void IPRNodeDirtyCallback(void* userPtr)
{
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;

    MCallbackId callbackId = MMessage::currentCallbackId();
    EditableElement& element = mayaScene->editableElements[callbackId];
    element.isDirty = true;

    mayaScene->isAnyDirty = true;
}

namespace
{
    void markTransformsChildrenAsDirty()
    {
        boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;

        for (MayaScene::EditableElementContainer::iterator
            i = mayaScene->editableElements.begin(),
            e = mayaScene->editableElements.end(); i != e; ++i)
        {
            if (i->second.isDirty)
            {
                if (i->second.node.hasFn(MFn::kTransform))
                {
                    MItDag childIter;
                    for (childIter.reset(i->second.node); !childIter.isDone(); childIter.next())
                    {
                        if (childIter.currentItem().hasFn(MFn::kShape))
                        {
                            for (MayaScene::EditableElementContainer::iterator
                                j = mayaScene->editableElements.begin(),
                                f = mayaScene->editableElements.end(); j != f; ++j)
                            {
                                if (childIter.currentItem() == j->second.node)
                                {
                                    j->second.isDirty = true;
                                    j->second.isTransformed = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

void IPRIdleCallback(float time, float lastTime, void* userPtr)
{
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;

    if (!mayaScene->isAnyDirty)
        return;

    stopRendering();

    markTransformsChildrenAsDirty();
    getWorldPtr()->mRenderer->applyInteractiveUpdates(mayaScene->editableElements);

    for (MayaScene::EditableElementContainer::iterator
            i = mayaScene->editableElements.begin(),
            e = mayaScene->editableElements.end(); i != e; ++i)
    {
        i->second.isDirty = false;
        i->second.isTransformed = false;
    }

    mayaScene->isAnyDirty = false;

    startRendering();
}

// Register new created nodes. We need the transform and the shape node to correctly use it in IPR.
// So we simply use the shape node, get it's parent - a shape node and let the scene parser do the rest.
// Then add a node dirty callback for the new elements. By adding the callback ids to the idInteractiveMap, the
// IPR should detect a modification during the netxt update cycle.
// Interestingly, if an object is duplicated, it first receives a prefix called "__PrenotatoPerDuplicare_", then later
// the geometry will be renamed to the correct name.

// Handling of surface shaders is a bit different. A shader is not assigned directly to a surface but it is connected to a shading group
// which is nothing else but a objectSet. If a new surface shader is created, it is not in use until it is assigned to an object what means it is connected
// to a shading group. So I simply add a shadingGroup callback for new shading groups.

void IPRNodeAddedCallback(MObject& node, void* userPtr)
{
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;
    MStatus stat;

    if (node.hasFn(MFn::kTransform))
    {
        MFnDagNode dagNode(node);

        MDagPath dagPath;
        stat = dagNode.getPath(dagPath);
        MString why = stat.errorString();
        stat = dagPath.extendToShape();
        if (!dagPath.node().hasFn(MFn::kMesh))
            return;
    }
    else
    {
        if (!node.hasFn(MFn::kShape))
            return;
    }
    MFnDagNode dagNode(node);
    MDagPath transformPath;
    dagNode.getPath(transformPath);
    MDagPath dagPath = transformPath;
    transformPath.pop();

    // Here the new object and its children are added to the object list and to the interactive object list.
    mayaScene->parseSceneHierarchy(transformPath, 0, boost::shared_ptr<ObjectAttributes>(), boost::shared_ptr<MayaObject>());

    for (MayaScene::EditableElementContainer::iterator
        i = mayaScene->editableElements.begin(),
        e = mayaScene->editableElements.end(); i != e; ++i)
    {
        if (i->second.mayaObject == 0)
            continue;
        if (i->second.mayaObject->dagPath == dagPath)
        {
            i->second.isDirty = true;
            i->second.isDeformed = true;
            mayaScene->isAnyDirty = true;
            break;
        }
    }

}

void IPRNodeRenamedCallback(MObject& node, const MString& oldName, void* userPtr)
{
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;
    for (MayaScene::EditableElementContainer::iterator
        i = mayaScene->editableElements.begin(),
        e = mayaScene->editableElements.end(); i != e; ++i)
    {
        if (i->second.mayaObject != 0)
        {
            if (i->second.node == node)
            {
                break;
            }
        }
    }

}

void IPRNodeRemovedCallback(MObject& node, void* userPtr)
{
    // Find the MayaObject and mark it as removed.
    boost::shared_ptr<MayaScene> mayaScene = getWorldPtr()->mScene;
    std::vector<MCallbackId> removeIds;
    for (MayaScene::EditableElementContainer::iterator
            i = mayaScene->editableElements.begin(),
            e = mayaScene->editableElements.end(); i != e; ++i)
    {
        EditableElement& element = i->second;
        if (element.node == node)
        {
            MNodeMessage::removeCallback(i->first);
            removeIds.push_back(i->first);
            if (element.mayaObject)
            {
                element.mayaObject->removed = true;
                element.isDirty = true;
                element.isDeformed = true; // trigger mesh update
                mayaScene->isAnyDirty = true;
            }
            break;
        }
    }

}

max_stars_repo_name: haggi/appleseed-maya

max_issues_repo_name: haggi/appleseed-maya

max_forks_repo_name: haggi/appleseed-maya


text: #include <boost/geometry/multi/core/interior_rings.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino