text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/usd/notice.h"
#include "pxr/usd/usd/stage.h"
#include "pxr/base/tf/stl.h"

#include <boost/iterator/transform_iterator.hpp>

using boost::make_transform_iterator;

PXR_NAMESPACE_OPEN_SCOPE

// Register the notice class
TF_REGISTRY_FUNCTION(TfType)
{
    TfType::Define<UsdNotice::StageNotice, TfType::Bases<TfNotice> >();

    TfType::Define<
        UsdNotice::StageContentsChanged,
        TfType::Bases<UsdNotice::StageNotice> >();

    TfType::Define<
        UsdNotice::StageEditTargetChanged,
        TfType::Bases<UsdNotice::StageNotice> >();

    TfType::Define<
        UsdNotice::ObjectsChanged,
        TfType::Bases<UsdNotice::StageNotice> >();
}

UsdNotice::StageNotice::StageNotice(const UsdStageWeakPtr& stage) :
    _stage(stage)
{
}

UsdNotice::StageNotice::~StageNotice() {}

UsdNotice::StageContentsChanged::~StageContentsChanged() {}

UsdNotice::StageEditTargetChanged::~StageEditTargetChanged() {}

TfTokenVector
UsdNotice::ObjectsChanged::PathRange::const_iterator::GetChangedFields() const
{
    TfTokenVector fields;
    for (const SdfChangeList::Entry* entry : base()->second) {
        fields.insert(fields.end(),
            make_transform_iterator(entry->infoChanged.begin(), TfGet<0>()),
            make_transform_iterator(entry->infoChanged.end(), TfGet<0>()));
    }

    std::sort(fields.begin(), fields.end());
    fields.erase(std::unique(fields.begin(), fields.end()), fields.end());
    return fields;
}

bool
UsdNotice::ObjectsChanged::PathRange::const_iterator::HasChangedFields() const
{
    for (const SdfChangeList::Entry* entry : base()->second) {
        if (!entry->infoChanged.empty()) {
            return true;
        }
    }
    return false;
}

UsdNotice::ObjectsChanged::~ObjectsChanged() {}

bool
UsdNotice::ObjectsChanged::ResyncedObject(const UsdObject &obj) const
{
    // XXX: We don't need the longest prefix here, we just need to know if
    // a prefix exists in the map.
    return SdfPathFindLongestPrefix(
        *_resyncChanges, obj.GetPath()) != _resyncChanges->end();
}

bool
UsdNotice::ObjectsChanged::ChangedInfoOnly(const UsdObject &obj) const
{
    // XXX: We don't need the longest prefix here, we just need to know if
    // a prefix exists in the map.
    return SdfPathFindLongestPrefix(
        *_infoChanges, obj.GetPath()) != _infoChanges->end();
}

UsdNotice::ObjectsChanged::PathRange
UsdNotice::ObjectsChanged::GetResyncedPaths() const
{
    return PathRange(_resyncChanges);
}

UsdNotice::ObjectsChanged::PathRange
UsdNotice::ObjectsChanged::GetChangedInfoOnlyPaths() const
{
    return PathRange(_infoChanges);
}

TfTokenVector
UsdNotice::ObjectsChanged::GetChangedFields(const UsdObject &obj) const
{
    return GetChangedFields(obj.GetPath());
}

TfTokenVector
UsdNotice::ObjectsChanged::GetChangedFields(const SdfPath &path) const
{
    PathRange range = GetResyncedPaths();
    PathRange::const_iterator it = range.find(path);
    if (it != range.end()) {
        return it.GetChangedFields();
    }

    range = GetChangedInfoOnlyPaths();
    it = range.find(path);
    if (it != range.end()) {
        return it.GetChangedFields();
    }

    return TfTokenVector();
}

bool
UsdNotice::ObjectsChanged::HasChangedFields(const UsdObject &obj) const
{
    return HasChangedFields(obj.GetPath());
}

bool
UsdNotice::ObjectsChanged::HasChangedFields(const SdfPath &path) const
{
    PathRange range = GetResyncedPaths();
    PathRange::const_iterator it = range.find(path);
    if (it != range.end()) {
        return it.HasChangedFields();
    }

    range = GetChangedInfoOnlyPaths();
    it = range.find(path);
    if (it != range.end()) {
        return it.HasChangedFields();
    }

    return false;
}

PXR_NAMESPACE_CLOSE_SCOPE

max_stars_repo_name: YuqiaoZhang/USD

max_issues_repo_name: YuqiaoZhang/USD

max_forks_repo_name: YuqiaoZhang/USD


text:
/*
 * local.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/image/threshold/local.h>

namespace dials { namespace algorithms { namespace boost_python {

  using namespace boost::python;

  template <typename FloatType>
  void local_threshold_suite() {
    def("niblack", &niblack<FloatType>, (arg("image"), arg("size"), arg("n_sigma")));

    def(
      "sauvola", &sauvola<FloatType>, (arg("image"), arg("size"), arg("k"), arg("r")));

    def("index_of_dispersion",
        &index_of_dispersion<FloatType>,
        (arg("image"), arg("size"), arg("n_sigma")));

    def("index_of_dispersion_masked",
        &index_of_dispersion_masked<FloatType>,
        (arg("image"), arg("mask"), arg("size"), arg("min_count"), arg("n_sigma")));

    def("gain",
        &gain<FloatType>,
        (arg("image"),
         arg("mask"),
         arg("gain"),
         arg("size"),
         arg("min_count"),
         arg("n_sigma")));

    def("dispersion",
        &dispersion<FloatType>,
        (arg("image"),
         arg("mask"),
         arg("size"),
         arg("n_sigma_b"),
         arg("n_sigma_s"),
         arg("min_count")));

    def("dispersion_w_gain",
        &dispersion_w_gain<FloatType>,
        (arg("image"),
         arg("mask"),
         arg("gain"),
         arg("size"),
         arg("n_sigma_b"),
         arg("n_sigma_s"),
         arg("min_count")));
  }

  void export_local() {
    local_threshold_suite<float>();
    local_threshold_suite<double>();

    class_<DispersionThreshold>("DispersionThreshold", no_init)
      .def(init<int2, int2, double, double, double, int>())
      .def("__call__", &DispersionThreshold::threshold<int>)
      .def("__call__", &DispersionThreshold::threshold<double>)
      .def("__call__", &DispersionThreshold::threshold_w_gain<int>)
      .def("__call__", &DispersionThreshold::threshold_w_gain<double>);

    class_<DispersionThresholdDebug>("DispersionThresholdDebug", no_init)
      .def(init<const af::const_ref<double, af::c_grid<2> > &,
                const af::const_ref<bool, af::c_grid<2> > &,
                int2,
                double,
                double,
                double,
                int>((arg("image"),
                      arg("mask"),
                      arg("size"),
                      arg("n_sigma_b"),
                      arg("n_sigma_s"),
                      arg("threshold"),
                      arg("min_count"))))
      .def(init<const af::const_ref<double, af::c_grid<2> > &,
                const af::const_ref<bool, af::c_grid<2> > &,
                const af::const_ref<double, af::c_grid<2> > &,
                int2,
                double,
                double,
                double,
                int>((arg("image"),
                      arg("mask"),
                      arg("gain"),
                      arg("size"),
                      arg("n_sigma_b"),
                      arg("n_sigma_s"),
                      arg("threshold"),
                      arg("min_count"))))
      .def("mean", &DispersionThresholdDebug::mean)
      .def("variance", &DispersionThresholdDebug::variance)
      .def("index_of_dispersion", &DispersionThresholdDebug::index_of_dispersion)
      .def("global_mask", &DispersionThresholdDebug::global_mask)
      .def("cv_mask", &DispersionThresholdDebug::cv_mask)
      .def("value_mask", &DispersionThresholdDebug::value_mask)
      .def("final_mask", &DispersionThresholdDebug::final_mask);

    class_<DispersionExtendedThresholdDebug>("DispersionExtendedThresholdDebug",
                                             no_init)
      .def(init<const af::const_ref<double, af::c_grid<2> > &,
                const af::const_ref<bool, af::c_grid<2> > &,
                int2,
                double,
                double,
                double,
                int>((arg("image"),
                      arg("mask"),
                      arg("size"),
                      arg("n_sigma_b"),
                      arg("n_sigma_s"),
                      arg("threshold"),
                      arg("min_count"))))
      .def(init<const af::const_ref<double, af::c_grid<2> > &,
                const af::const_ref<bool, af::c_grid<2> > &,
                const af::const_ref<double, af::c_grid<2> > &,
                int2,
                double,
                double,
                double,
                int>((arg("image"),
                      arg("mask"),
                      arg("gain"),
                      arg("size"),
                      arg("n_sigma_b"),
                      arg("n_sigma_s"),
                      arg("threshold"),
                      arg("min_count"))))
      .def("mean", &DispersionExtendedThresholdDebug::mean)
      .def("variance", &DispersionExtendedThresholdDebug::variance)
      .def("index_of_dispersion",
           &DispersionExtendedThresholdDebug::index_of_dispersion)
      .def("global_mask", &DispersionExtendedThresholdDebug::global_mask)
      .def("cv_mask", &DispersionExtendedThresholdDebug::cv_mask)
      .def("value_mask", &DispersionExtendedThresholdDebug::value_mask)
      .def("final_mask", &DispersionExtendedThresholdDebug::final_mask);

    class_<DispersionExtendedThreshold>("DispersionExtendedThreshold", no_init)
      .def(init<int2, int2, double, double, double, int>())
      /* .def("__call__", &DispersionExtendedThreshold::threshold<int>) */
      .def("__call__", &DispersionExtendedThreshold::threshold<double>)
      /* .def("__call__", &DispersionExtendedThreshold::threshold_w_gain<int>) */
      .def("__call__", &DispersionExtendedThreshold::threshold_w_gain<double>);
  }

}}}  // namespace dials::algorithms::boost_python

ext: cc

max_stars_repo_name: TiankunZhou/dials

max_issues_repo_name: TiankunZhou/dials

max_forks_repo_name: TiankunZhou/dials


text:
#include <dlib/rand.h>
#include <dlib/svm_threaded.h>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
using namespace dlib;

typedef matrix<double,2,1> sample_type;

int main(void){
    ofstream datafile;
    datafile.open ("multi_data_test.txt");

    const long num = 50;

    sample_type m;

    dlib::rand rnd;

    // make some samples near the origin
    double radius = 0.5;
    for (long i = 0; i < num+10; ++i)
    {
        double sign = 1;
        if (rnd.get_random_double() < 0.5)
            sign = -1;
        m(0) = 2*radius*rnd.get_random_double()-radius;
        m(1) = sign*sqrt(radius*radius - m(0)*m(0));

        // add this sample to our set of training samples
//        samples.push_back(m);
 //       labels.push_back(1);
        datafile << m(0) << " " << m(1) << " 1\n";
    }

    // make some samples in a circle around the origin but far away
    radius = 10.0;
    for (long i = 0; i < num+20; ++i)
    {
        double sign = 1;
        if (rnd.get_random_double() < 0.5)
            sign = -1;
        m(0) = 2*radius*rnd.get_random_double()-radius;
        m(1) = sign*sqrt(radius*radius - m(0)*m(0));

        // add this sample to our set of training samples
    //    samples.push_back(m);
     //   labels.push_back(2);
        datafile << m(0) << " " << m(1) << " 2\n";
    }

    // make some samples in a circle around the point (25,25)
    radius = 4.0;
    for (long i = 0; i < num+30; ++i)
    {
        double sign = 1;
        if (rnd.get_random_double() < 0.5)
            sign = -1;
        m(0) = 2*radius*rnd.get_random_double()-radius;
        m(1) = sign*sqrt(radius*radius - m(0)*m(0));

        // translate this point away from the origin
        m(0) += 25;
        m(1) += 25;

        datafile << m(0) << " " << m(1) << " 3\n";
    }
    datafile.close();
}

ext: cpp

max_stars_repo_name: ytobah/dlib-mod

max_issues_repo_name: ytobah/dlib-mod

max_forks_repo_name: ytobah/dlib-mod


text:
#pragma once

//#define PRODUCT_DISTRIBUTION_SAMPLING

#include <memory>
#include <type_traits>
//#include <boost/container/static_vector.hpp>

#include "sampler.hxx"
#include "spectral.hxx"
//#include "memory_arena.hxx"

#ifdef PRODUCT_DISTRIBUTION_SAMPLING
#include "distribution_mixture_models.hxx"
#endif

struct TagScatterSample {};
using ScatterSample = Sample<Double3, Spectral3, TagScatterSample>;

class Texture;
struct SurfaceInteraction;
struct PathContext;
struct RaySegment;
class PiecewiseConstantTransmittance;

// Included here because it uses ScatterSample.
#include"phasefunctions.hxx"

namespace materials
{

struct ShaderQuery
{
  std::reference_wrapper<const SurfaceInteraction> surface_hit;
  std::reference_wrapper<const PathContext> context;
  double minimum_roughness = 0.;
};

}

using materials::ShaderQuery;

class Shader
{
public:
  bool require_monochromatic = false;
  bool prefer_path_tracing_over_photonmap = false;
  bool is_pure_specular = false;
  bool is_pure_diffuse = false;
  bool supports_lobes = false;
  Shader() {}
  virtual ~Shader() {}
  // Old interface
  ScatterSample SampleBSDF(const Double3 &reverse_incident_dir, const SurfaceInteraction &surf_hit, Sampler& sampler, const PathContext &context) const;
  Spectral3 EvaluateBSDF(const Double3 &reverse_incident_dir, const SurfaceInteraction &surf_hit, const Double3 &out_direction, const PathContext &context, double *pdf) const;
  double Pdf(const Double3 &reverse_incident_dir, const SurfaceInteraction &surf_hit, const Double3 &out_direction, const PathContext &context) const;
  // New Interface
  virtual ScatterSample SampleBSDF(const Double3 &reverse_incident_dir, ShaderQuery query, Sampler& sampler) const = 0;
  virtual Spectral3 EvaluateBSDF(const Double3 &reverse_incident_dir, ShaderQuery query, const Double3 &out_direction, double *pdf) const = 0;
  virtual double Pdf(const Double3 &reverse_incident_dir, ShaderQuery query, const Double3 &out_direction) const;
  virtual double MyRoughness(ShaderQuery query) const;

  virtual double GuidingProbMixShaderAmount(const SurfaceInteraction &surface_hit) const;
#ifdef PRODUCT_DISTRIBUTION_SAMPLING
  virtual vmf_fitting::VonMisesFischerMixture<2> ComputeLobes(const Double3 &incident_dir, const SurfaceInteraction &surface_hit, const PathContext &context) const;
  virtual void IntializeLobes();
#endif

  //virtual materials::LobeOwner PickTheLobe(const Double3 &incident_dir, const SurfaceInteraction &surface_hit, Sampler &sampler, const PathContext &context) const = 0;
};

std::unique_ptr<Shader> MakeGlossyTransmissiveDielectricShader(
  double _ior_ratio,
  double alpha_,
  double alpha_min_,
  std::shared_ptr<Texture> glossy_exponent_texture_);

std::unique_ptr<Shader> MakeDiffuseShader(
  const SpectralN &reflectance,
  std::shared_ptr<Texture> _diffuse_texture);

std::unique_ptr<Shader> MakeMicrofacetShader(
  const SpectralN &_glossy_reflectance,
  double _glossy_exponent,
  std::shared_ptr<Texture> _glossy_exponent_texture);

std::unique_ptr<Shader> MakeSpecularTransmissiveDielectricShader(
  double _ior_ratio,
  double ior_lambda_coeff_ = 0.);

std::unique_ptr<Shader> MakeSpecularDenseDielectricShader(
  const double _specular_reflectivity,
  const SpectralN &_diffuse_reflectivity,
  std::shared_ptr<Texture> _diffuse_texture);

std::unique_ptr<Shader> MakeSpecularReflectiveShader(const SpectralN &reflectance);

std::unique_ptr<Shader> MakeInvisibleShader();

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Media
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace materials
{

enum MediumFlags : int
{
  IS_SCATTERING = 1,
  IS_EMISSIVE = 2,
  IS_MONOCHROMATIC = 4,
  IS_HOMOGENEOUS = 8
};

inline constexpr MediumFlags operator | (MediumFlags lhs, MediumFlags rhs) noexcept
{
    // Good tip from https://softwareengineering.stackexchange.com/questions/194412/using-scoped-enums-for-bit-flags-in-c
    using T = std::underlying_type_t <MediumFlags>;
    return static_cast<MediumFlags>(static_cast<T>(lhs) | static_cast<T>(rhs));
}

struct MediaCoefficients
{
  Spectral3 sigma_s;
  Spectral3 sigma_t;
  Spectral3 emission{ Eigen::zero };
};

struct VolumePdfCoefficients
{
  double pdf_scatter_fwd{ 1. }; // Moving forward. Pdf for scatter event to occur at the end of the given segment.
  double pdf_scatter_bwd{ 1. }; // Backward. For scatter event at the segment start, moving from back to start.
  double transmittance{ 1. }; // Corresponding transmittances.
};

inline std::tuple<double, double> FwdCoeffs(const VolumePdfCoefficients &c)
{
  return std::make_tuple(c.pdf_scatter_fwd, c.transmittance);
}

inline std::tuple<double, double> BwdCoeffs(const VolumePdfCoefficients &c)
{
  return std::make_tuple(c.pdf_scatter_bwd, c.transmittance);
}

inline void Accumulate(VolumePdfCoefficients &accumulated, const VolumePdfCoefficients &segment_coeff, bool is_first, bool is_last)
{
  accumulated.pdf_scatter_fwd *= is_last ? segment_coeff.pdf_scatter_fwd : segment_coeff.transmittance;
  accumulated.pdf_scatter_bwd *= is_first ? segment_coeff.pdf_scatter_bwd : segment_coeff.transmittance;
  accumulated.transmittance *= segment_coeff.transmittance;
}

#if 0
using PhaseFunctionPtr = util::MemoryArena::unique_ptr<PhaseFunctions::PhaseFunction>;

class OnTheLine
{
  public:

    virtual void AdvancePointer(double dt) = 0;
    virtual MediaCoefficients GetCoefficients() const = 0;
    // Needed here because the phase function in the atmospheric model depends on the local composition!
    virtual PhaseFunctionPtr AllocatePhaseFunction(util::MemoryArena &arena) = 0;
};

using OnTheLinePtr = util::MemoryArena::unique_ptr<OnTheLine>;
using MemoryArena = util::MemoryArena;
#endif

/* Good reference for path tracing with emissive volumes:
    Raab et. al (2008) "Unbiased global illumination with participating media" */
class Medium
{
public:
  // Represents both, scattering and emission/absorption events.
  struct InteractionSample
  {
    double t;
    // Following PBRT pg 893, the returned weight is either
    // weight_surf = T(t_intersect)/p_surf if t > t_intersect, or
    // weight_med =  T(t) / p(t)
    // where t_intersect refers to the end of the supplied segment.
    Spectral3 weight;
    Spectral3 sigma_s;
  };
  using PhaseSample = ScatterSample;
  using MaterialCoefficients = materials::MediaCoefficients;

  struct VolumeSample
  {
    Double3 pos;
  };

  const bool is_emissive;
  const bool is_scattering;
  const bool is_monochromatic;
  const bool is_homogeneous;
  const int priority;
  Medium(int _priority, MediumFlags flags) :
    is_emissive(flags & IS_EMISSIVE),
    is_scattering(flags & IS_SCATTERING),
    is_monochromatic(flags & IS_MONOCHROMATIC),
    is_homogeneous(flags & IS_HOMOGENEOUS), priority(_priority) {}
  virtual ~Medium() {}

  //virtual OnTheLinePtr GetOnTheLine(const RaySegment &segment, const PathContext &context, MemoryArena &arena) const;

  virtual InteractionSample SampleInteractionPoint(const RaySegment &segment, const Spectral3 &initial_weights, Sampler &sampler, const PathContext &context) const = 0;
  virtual Spectral3 EvaluateTransmission(const RaySegment &segment, Sampler &sampler, const PathContext &context) const = 0;
  virtual void ConstructShortBeamTransmittance(const RaySegment &segment, Sampler &sampler, const PathContext &context, PiecewiseConstantTransmittance &pct) const = 0;
  virtual VolumePdfCoefficients ComputeVolumePdfCoefficients(const RaySegment &segment, const PathContext &context) const = 0; // Can be approximate. Deterministic.

  virtual PhaseSample SamplePhaseFunction(const Double3 &incident_dir, const Double3 &pos, Sampler &sampler, const PathContext &context) const = 0;
  virtual Spectral3 EvaluatePhaseFunction(const Double3 &indcident_dir, const Double3 &pos, const Double3 &out_direction, const PathContext &context, double *pdf) const = 0;

  virtual Spectral3 ComputeMajorante(const RaySegment &segment, const PathContext &context) const = 0;
  virtual MaterialCoefficients EvaluateCoeffs(const Double3 &pos, const PathContext &context) const = 0;
};

class VacuumMedium : public Medium
{
public:
  VacuumMedium(int priority = -1) : Medium(priority, IS_MONOCHROMATIC|IS_HOMOGENEOUS) {}
  virtual InteractionSample SampleInteractionPoint(const RaySegment &segment, const Spectral3 &initial_weights, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluateTransmission(const RaySegment &segment, Sampler &sampler, const PathContext &context) const override;
  virtual void ConstructShortBeamTransmittance(const RaySegment &segment, Sampler &sampler, const PathContext &context, PiecewiseConstantTransmittance &pct) const override;
  virtual VolumePdfCoefficients ComputeVolumePdfCoefficients(const RaySegment &segment, const PathContext &context) const override;

  virtual PhaseSample SamplePhaseFunction(const Double3 &incident_dir, const Double3 &pos, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluatePhaseFunction(const Double3 &indcident_dir, const Double3 &pos, const Double3 &out_direction, const PathContext &context, double *pdf) const override;

  virtual Spectral3 ComputeMajorante(const RaySegment &segment, const PathContext &context) const override;
  virtual MaterialCoefficients EvaluateCoeffs(const Double3 &pos, const PathContext &context) const override;
};

class HomogeneousMedium : public Medium
{
  SpectralN sigma_s, sigma_a, sigma_ext;
  Spectral3 EvaluateTransmissionHomogeneous(double x, const Spectral3 &sigma_ext) const;
public:
  std::unique_ptr<PhaseFunctions::PhaseFunction> phasefunction; // filled by parser
public:
  HomogeneousMedium(const SpectralN &_sigma_s, const SpectralN &_sigma_a, int _priority);
  virtual InteractionSample SampleInteractionPoint(const RaySegment &segment, const Spectral3 &initial_weights, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluateTransmission(const RaySegment &segment, Sampler &sampler, const PathContext &context) const override;
  virtual void ConstructShortBeamTransmittance(const RaySegment &segment, Sampler &sampler, const PathContext &context, PiecewiseConstantTransmittance &pct) const override;
  virtual VolumePdfCoefficients ComputeVolumePdfCoefficients(const RaySegment &segment, const PathContext &context) const override;

  virtual PhaseSample SamplePhaseFunction(const Double3 &incident_dir, const Double3 &pos, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluatePhaseFunction(const Double3 &indcident_dir, const Double3 &pos, const Double3 &out_direction, const PathContext &context, double *pdf) const override;

  virtual Spectral3 ComputeMajorante(const RaySegment &segment, const PathContext &context) const override;
  virtual MaterialCoefficients EvaluateCoeffs(const Double3 &pos, const PathContext &context) const override;
};

class ModulatedDensityMedium : public Medium
{
  Eigen::Affine3d trafo;
  SpectralN sigma_s, sigma_a, sigma_ext;
  double low_density_fraction;
public:
  std::unique_ptr<PhaseFunctions::PhaseFunction> phasefunction; // filled by parser

  ModulatedDensityMedium(const SpectralN &_sigma_s, const SpectralN &_sigma_a, double low_density_fraction, const Eigen::Affine3d &trafo, int _priority);
  virtual InteractionSample SampleInteractionPoint(const RaySegment &segment, const Spectral3 &initial_weights, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluateTransmission(const RaySegment &segment, Sampler &sampler, const PathContext &context) const override;
  virtual void ConstructShortBeamTransmittance(const RaySegment &segment, Sampler &sampler, const PathContext &context, PiecewiseConstantTransmittance &pct) const override;
  virtual VolumePdfCoefficients ComputeVolumePdfCoefficients(const RaySegment &segment, const PathContext &context) const override;

  virtual PhaseSample SamplePhaseFunction(const Double3 &incident_dir, const Double3 &pos, Sampler &sampler, const PathContext &context) const override;
  virtual Spectral3 EvaluatePhaseFunction(const Double3 &indcident_dir, const Double3 &pos, const Double3 &out_direction, const PathContext &context, double *pdf) const override;

  virtual Spectral3 ComputeMajorante(const RaySegment &segment, const PathContext &context) const override;
  virtual MaterialCoefficients EvaluateCoeffs(const Double3 &pos, const PathContext &context) const override;
};

}  // materials

using materials::Medium;
using materials::VolumePdfCoefficients;
using materials::FwdCoeffs;
using materials::BwdCoeffs;
using materials::Accumulate;

ext: hxx

max_stars_repo_name: DaWelter/NaiveTrace

max_issues_repo_name: DaWelter/NaiveTrace

max_forks_repo_name: DaWelter/NaiveTrace


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

#include <SFML/Graphics.hpp>

#include "../../src/shared/state.h"
#include "../../src/client/render.h"

using namespace state;
using namespace render;

BOOST_AUTO_TEST_CASE(TestRender)
{
	state::State s {};
	StateLayer sl {};

	s.registerObserver(&sl);

	sl.initLayers(s,35);
	sl.getTilesets();

}

max_stars_repo_name: StevenEnsea/plt

max_issues_repo_name: StevenEnsea/plt

max_forks_repo_name: StevenEnsea/plt


text:
/*
Copyright Barrett Adair 2016-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http ://boost.org/LICENSE_1_0.txt)
*/

#include <type_traits>
#include <functional>
#include <utility>
#include <boost/callable_traits/has_member_qualifiers.hpp>
#include "test.hpp"

struct foo {};

template<typename T>
void assert_qualified() {
    CT_ASSERT( has_member_qualifiers<T>::value);
}

template<typename T>
void assert_unqualified() {
    CT_ASSERT(! has_member_qualifiers<T>::value);
}

int main() {

    {
        using f   = void(foo::*)();
        using c   = void(foo::*)() const;
        using v   = void(foo::*)() volatile;
        using cv  = void(foo::*)() const volatile;

        assert_unqualified<f>();
        assert_qualified<c>();
        assert_qualified<v>();
        assert_qualified<cv>();
    }

    {
        struct f   { int operator()() { return 0; } };
        struct c   { int operator()() const { return 0; } };
        struct v   { int operator()() volatile { return 0; } };
        struct cv  { int operator()() const volatile { return 0; } };

        assert_unqualified<f>();
        assert_qualified<c>();
        assert_qualified<v>();
        assert_qualified<cv>();
    }

    using f_ptr = void(*)();
    assert_unqualified<f_ptr>();
    assert_unqualified<f_ptr foo::*>();
    assert_unqualified<int foo::*>();
    assert_unqualified<void(&)()>();
}


text:
//
// Created by Rakesh on 25/12/2021.
//

#include "client/client.h"
#include "../api/api.h"
#include "../common/util/clara.h"
#include "../log/NanoLog.h"

#include <algorithm>
#include <iostream>
#include <thread>
#include <vector>

#include <boost/asio/signal_set.hpp>

int main( int argc, char const * const * argv )
{
  using namespace std::string_literals;
  using clara::Opt;
  std::string server{ "localhost" };
#ifdef __APPLE__
  std::string port{ "2022" };
  std::string logLevel{ "debug" };
#else
  std::string port{ "2020" };
  std::string logLevel{"info"};
#endif
  std::string dir{"/tmp/"};
  std::string action{};
  std::string key{};
  std::string value{};
  std::string file{};
  bool ssl = false;
  bool help = false;

  auto options = clara::Help(help) |
      Opt(server, "localhost")["-s"]["--server"]("Server to connect to (default localhost).") |
      Opt(port, "2020")["-p"]["--port"]("TCP port for the server (default 2020)") |
      Opt(ssl)["-t"]["--with-ssl"]("Use SSL to connect to service (default false)") |
      Opt(file, "file.txt")["-f"]["--file"]("File to bulk import data from") |
      Opt(action, "set")["-a"]["--action"]("Action to perform against the database.") |
      Opt(key, "/key")["-k"]["--key"]("Key or path to apply action to") |
      Opt(value, "value")["-v"]["--value"]("Value to set.  Only applies to 'set' action") |
      Opt(logLevel, "info")["-l"]["--log-level"]("Log level to use [debug|info|warn|critical] (default info).") |
      Opt(dir, "/tmp/")["-o"]["--log-dir"]("Log directory (default /tmp/)");

  auto result = options.parse(clara::Args(argc, argv));
  if ( !result )
  {
    std::cerr << "Error in command line: " << result.errorMessage() << std::endl;
    exit( 1 );
  }

  if ( help )
  {
    options.writeToStream( std::cout );
    exit( 0 );
  }

  if ( logLevel == "debug" ) nanolog::set_log_level( nanolog::LogLevel::DEBUG );
  else if ( logLevel == "info" ) nanolog::set_log_level( nanolog::LogLevel::INFO );
  else if ( logLevel == "warn" ) nanolog::set_log_level( nanolog::LogLevel::WARN );
  else if ( logLevel == "critical" ) nanolog::set_log_level( nanolog::LogLevel::CRIT );
  nanolog::initialize( nanolog::GuaranteedLogger(), dir, "configdb-cli", false );

  boost::asio::signal_set signals( spt::configdb::ContextHolder::instance().ioc, SIGINT, SIGTERM );
  signals.async_wait( [&](auto const&, int ) { spt::configdb::ContextHolder::instance().ioc.stop(); } );

  std::vector<std::thread> v;
  v.reserve( 1 );
  v.emplace_back( []{ spt::configdb::ContextHolder::instance().ioc.run(); } );
  int response = EXIT_SUCCESS;

  try
  {
    spt::configdb::api::init( server, port, ssl );
    if ( file.empty() )
    {
      if ( action.empty() )
      {
        std::cout << "Action not specified" << '\n';
        options.writeToStream( std::cout );
        exit( 1 );
      }

      const std::vector<std::string> actions{ "delete"s ,"get"s, "list"s, "move"s, "set"s };
      if ( std::find( std::begin( actions ), std::end( actions ), action ) == std::end( actions ) )
      {
        std::cout << "Unsupported action" << '\n';
        std::cout << "Valid values get|set|move|list|delete" << '\n';
        exit( 1 );
      }

      if ( key.empty() )
      {
        std::cout << "Key not specified" << '\n';
        options.writeToStream( std::cout );
        exit( 1 );
      }

      if ( action == "set"s && value.empty() )
      {
        std::cout << "Value not specified" << '\n';
        options.writeToStream( std::cout );
        exit( 1 );
      }

      if ( action == "move"s && value.empty() )
      {
        std::cout << "Destination key not specified" << '\n';
        options.writeToStream( std::cout );
        exit( 1 );
      }

      if ( action == "get"s ) response = spt::configdb::client::get( server, port, key, ssl );
      else if ( action == "list"s ) response = spt::configdb::client::list( server, port, key, ssl );
      else if ( action == "set"s ) response = spt::configdb::client::set( server, port, key, value, ssl );
      else if ( action == "move"s ) response = spt::configdb::client::move( server, port, key, value, ssl );
      else if ( action == "delete"s ) response = spt::configdb::client::remove( server, port, key, ssl );
    }
    else
    {
      response = spt::configdb::client::import( server, port, file, ssl );
    }
  }
  catch ( const std::exception& ex )
  {
    std::cerr << "Error communicating with server. " << ex.what() << '\n';
  }

  spt::configdb::ContextHolder::instance().ioc.stop();

  for ( auto&& t : v )
  {
    if ( t.joinable() ) t.join();
  }

  return response;
}

max_stars_repo_name: sptrakesh/config-db

max_issues_repo_name: sptrakesh/config-db

max_forks_repo_name: sptrakesh/config-db


text:
#ifndef processor_hpp
#define processor_hpp

#include <boost/lockfree/queue.hpp>
#include <atomic>
#include <thread>
#include <assert.h>

#include "common.hpp"
#include "exception.hpp"

class Processor
{
public:
    /* functions */
    Processor(boost::lockfree::queue<buffer*, boost::lockfree::fixed_sized<false>> *inputQ,
              boost::lockfree::queue<int8_t*, boost::lockfree::fixed_sized<false>> *outputQ);
    ~Processor(void);

    void coreLoop();

    uint32_t getCount();
    uint32_t getCountBytes();
    void setCount(uint32_t);
    void clearCount();

    bool getWindowStatus();

    void flushPersistence();

    void processorStop();
    void processorStart();
    void processorPause();
    void processorUnpause();

    std::chrono::high_resolution_clock::time_point getTimeFilled();
    std::chrono::high_resolution_clock::time_point getTimeWritten();

    void setCh(int8_t newCh);

    void getMax(int8_t chNum, int8_t* value, uint64_t* pos);
    void getMin(int8_t chNum, int8_t* value, uint64_t* pos);

    void reProcess();

    /* variables */
    uint32_t windowCol;
    uint32_t windowRow;
    uint32_t bufferCol;

private:
    /* functions */
    void copyProcess(int8_t * src, int8_t * dst, uint32_t count);

    void updateWinSize(uint32_t newWinSize);
    void updatePerSize(uint32_t newPerSize);
    void updateWinPerSize(uint32_t newWinSize, uint32_t newPerSize);

    bool findNextTrigger(buffer *currentBuffer, uint32_t* p_column);

    /* variables */
    boost::lockfree::queue<buffer*, boost::lockfree::fixed_sized<false>> *inputQueue;
    boost::lockfree::queue<int8_t*, boost::lockfree::fixed_sized<false>> *outputQueue;

    std::thread processorThread;

    std::chrono::high_resolution_clock::time_point windowFilled;
    std::chrono::high_resolution_clock::time_point windowWritten;

    uint32_t count;
    uint32_t countProcessed;

    int8_t* windowProcessed;

    std::mutex lockThread;

    std::atomic<bool> stopTransfer;
    std::atomic<bool> pauseTransfer;
    std::atomic<bool> windowStored;

    int8_t numCh = 1;
};

#endif

ext: hpp


text:
#include "libs/sources_handling/row_data_input.h"
#include "libs/sources_handling/source_data.h"
#include "libs/sources_handling/schema_read.hpp"
#include "libs/ml_models/utilities.h"
#include "libs/system/exceptions.h"
#include "utils/missing_values.hpp"
#include "logging.h"
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <iostream>
#include <random>

namespace
{

    template<typename T, typename S>
    struct cast_it
    {
        static constexpr T apply(S from)
        {
            return static_cast<T>(from);
        }
    };

    template<typename T>
    struct cast_it<T, T>
    {
        static constexpr T apply(T from)
        {
            return from;
        }
    };

    template<typename T, typename S>
    T cast_value(S from)
    {
        using cast_op = cast_it<T, S>;
        return cast_op::apply(from);
    }

    template<typename T, bool F>
    struct validation
    {
        template<typename S>
        static T convert(S from, const std::string&) {
            return cast_value<S>(from);
        }
    };

    template<typename T>
    struct validation<T, true>
    {
        template<typename S>
        static T convert(S from, const std::string& cid) {
            if (invalid_value(from) || missing_value(from)) {
                throw malformat_input{cid};
            }
            return cast_value<S>(from);
        }
    };

    template<typename TV, typename SV, typename S> inline
    TV from_token(S&& from, const std::string& cid) {
        using validator = validation<SV, std::is_floating_point<SV>::value>;

        return validator::convert(boost::lexical_cast<SV>(from), cid);
    }

    unsigned int process_line(const std::string& line, classifier::read_result& ret)
    {
        using tokenizer = boost::tokenizer<boost::char_separator<char>>;
        using target_value = classifier::read_result::value_type::data_type::value_type;
        using source_value = source_data::algo_data;
        static const boost::char_separator<char> sep(",");

        tokenizer tokens(line, sep);
        unsigned int index = 0;
        for (auto& token: tokens) {
            if (index < ret.size()) {
                const auto& id = ret[index].ID;
                ret[index++].data.push_back(
                        from_token<target_value, source_value>(token, id)
                        //cast_value<target_value>(boost::lexical_cast<source_value>(token))
                    );
            }
        }
        return index;
    }

    bool read_entries(std::istream& from, classifier::read_result& ret)
    {
        // note read each line convert to the entry
        auto index = 0;
        while (from) {
            std::string line;
            if (std::getline(from, line)) {
                auto r = process_line(line, ret);
                if (r !=  ret.size()) {
                    if (r == 0u && !ret[0].data.empty()) {
                        return true;    // we are at the end but we did read input
                    }
                    LOG_ERROR<<"failed to process line number "<<index<<" expected value "<<ret.size()<<" got "<<r;
                    return false;
                }
                ++index;
            }
        }
        LOG_INFO<<"successfully read "<<ret.size()<<" columns and "<<ret[0].data.size()<<" rows";
        return !ret[0].data.empty();
    }

}   // end of local namespace

column_data::column_data(const id_type& id) :
    ID(id)
{
}

std::ostream& operator << (std::ostream& os,
        const column_data& cd)
{
    return os<<"ID: "<<cd.ID<<", data size "<<cd.data.size();
}

schema_type read_schema(std::istream& from)
{
    const auto process_trim_token = [] (auto token) {
        if (token.size() < 3) {
            throw std::runtime_error{"invalid token read - too short"};
        }
        return std::string{&token[1], token.size()-2};   // trim start/end
    };

    return sr::read_schema(from, ",", process_trim_token);
}

namespace classifier
{

namespace details
{
void shuffle(std::size_t rn, read_result::iterator be_data,
        read_result::iterator end_data);
void shuffle_rows(int from_inx, int to_inx,
        read_result::iterator be_data,
        read_result::iterator end_data);
std::tuple<read_result::value_type::data_type::const_iterator,
           read_result::value_type::data_type::const_iterator>
    prepare4labels_copy(const read_result& data,
                const column_data::id_type& id,
                unsigned int rows, unsigned int off);
void shuffle_row(int from_inx, int to_inx,
        read_result::value_type::data_type::iterator begin);

void shuffle(std::size_t rn, read_result::iterator be_data,
        read_result::iterator end_data)
{
    std::random_device rd;
    std::mt19937 eng(rd());
    std::uniform_int_distribution<> distr(0, (int)rn);
    for (auto i = 0u; i < rn; ++i) {
        shuffle_rows(distr(eng), distr(eng),
                     be_data, end_data);
    }
}

void shuffle_row(int from_inx, int to_inx,
        read_result::value_type::data_type::iterator begin)
{
    auto fi = begin + from_inx;
    auto ft = begin + to_inx;
    //std::cout<<"swaping "<<*ft<<" and "<<*fi<<", ";
    std::swap(*fi, *ft);

}

void shuffle_rows(int from_inx, int to_inx,
        read_result::iterator be_data,
        read_result::iterator end_data)
{
    //std::cout<<"trying to swap at location "<<from_inx<<" and "<<to_inx<<std::endl;
    if (from_inx != to_inx) {
        std::for_each(be_data, end_data, [from_inx, to_inx](auto& col) {
                    shuffle_row(from_inx, to_inx, col.data.begin());
                }
        );
    }
}

std::tuple<read_result::value_type::data_type::const_iterator,
           read_result::value_type::data_type::const_iterator>
    prepare4labels_copy(const read_result& data,
                const column_data::id_type& id,
                unsigned int rows, unsigned int off)
{
    using iterator = read_result::value_type::data_type::const_iterator;
    if (empty(data)) {
        return std::make_tuple(iterator{}, iterator{});
    }
    auto i = std::find_if(std::begin(data), std::end(data),
                                [&id] (auto& col) {
                                    return col.ID == id;
                                }
    );
    if (i == std::end(data)) {
        return std::make_tuple(iterator{}, iterator{});
    } else {
        if ((off + rows) > i->data.size()) {    // make sure not to overflow!!
            rows -= (off + rows) - i->data.size();
        }
        rows = std::min(rows, (unsigned int)i->data.size());
        mlmodels::class_data ret(rows, 0.f);
        auto begin = std::begin(i->data) + off;
        auto end = begin + rows;
        return std::make_tuple(begin, end);
    }

}

}

read_result read(std::istream& from, const schema_type& schema)
{
    if (from && !schema.empty()) {
        LOG_INFO<<"reading data based on schema with "<<schema.size()<<" columns";
        read_result ret;
        std::for_each(std::begin(schema), std::end(schema), [&ret](auto& cn) {
                ret.emplace_back(cn);
            }
        );
        if (read_entries(from, ret)) {
            return ret;
        } // just fall to the default - which would signal an error
    } else {
        LOG_ERROR<<"failed to read - "<<(from ? "schema empty" : "source file is invalid");
    }
    return read_result{};
}

mlmodels::training_data data_matrix(const read_result& row_data,
        const column_data::id_type& label_col,
        unsigned int rows_count, unsigned int offset)
{
    static const std::string index_column = "index";
    // we need to build a matrix that would be transpose of the
    // data we have and without the data from the column that
    // is marked as label column, we also need to stop after
    // the given number of rows
    if (empty(row_data)) {
        return mlmodels::training_data{}; // invalid input
    }

    rows_count = std::min(rows_count, (unsigned int)rows(row_data));
    // build list of columns that we would save data from
    std::vector<read_result::const_iterator> indices;
    for (auto it = row_data.begin(); it !=  row_data.end(); ++it) {
        if (it->ID != label_col && it->ID != index_column) {
            indices.push_back(it);
        }
    }
    if ((rows_count + offset) > rows(row_data)) { // make sure not to overflow!!
        rows_count -= (rows_count + offset) - rows(row_data);
    }
    mlmodels::training_data result(boost::extents[rows_count][indices.size()]);
    // copy the number of rows that the user wants
    for (auto i = 0u; i < rows_count; ++i, ++offset) {
        auto j = 0u;
        for (const auto& cit : indices) {
            result[i][j++] = cit->data[offset];
        }
    }
    return result;
}

mlmodels::class_data labels_data(const read_result& row_data,
        const column_data::id_type& label_col,
        unsigned int rows, unsigned int off)
{
    auto r = details::prepare4labels_copy(row_data, label_col, rows, off);
    auto begin = std::get<0>(r);
    auto end = std::get<1>(r);
    if (begin == end) {
        return mlmodels::class_data{};    // invalid call
    }
    mlmodels::class_data ret(std::distance(begin, end), 0.f);
    std::copy(begin, end, std::begin(ret));
    return ret;
}

mlmodels::classes_data transform2labels(const read_result& from,
                    const column_data::id_type& label_col,
                    unsigned int rows, unsigned int off)
{
    auto r = details::prepare4labels_copy(from, label_col, rows, off);
    auto begin = std::get<0>(r);
    auto end = std::get<1>(r);
    if (begin != end) {
        return mlmodels::classes_transform(begin, end);
    } else {
        return mlmodels::classes_data{};
    }
}

bool empty(const read_result& rr)
{
    return rr.empty() || rr[0].data.empty();
}

std::size_t rows(const read_result& rr)
{
    return empty(rr) ? 0u : rr[0].data.size();
}

std::size_t columns(const read_result& rr)
{
   return rr.size();
}

const read_result::value_type::data_type&
    data_entry(const read_result& from, const column_data::id_type& id)
{
    auto i = std::find_if(std::begin(from), std::end(from), [&id](auto& c) {
                            return c.ID == id;
                        }
                );
    if (i == std::end(from)) {
        throw std::out_of_range{"column " + id + " do not exists"};
    }
    return i->data;
}

read_result&& randomalized(read_result from)
{
    if (empty(from)) {
        return std::move(from);
    }
    auto rn = rows(from) - 1u;

    details::shuffle(rn, from.begin(), from.end());
    return std::move(from);
}

}   // end of namespace classifer


text:
#include <cppassist/string/regex.h>

#ifdef USE_STD_REGEX
    #include <regex>

    namespace regex_namespace = std;
#else
    #include <boost/regex.hpp>

    namespace regex_namespace = boost;
#endif

namespace cppassist
{
namespace string
{

bool matchesRegex(const std::string & string, const std::string & regex)
{
    return regex_namespace::regex_match(string, regex_namespace::regex(regex));
}

std::vector<std::string> extract(const std::string & string, const std::string & regex)
{
    std::vector<std::string> values;

    regex_namespace::smatch matchResults;
    const regex_namespace::regex r(regex);

    std::string s = string;
    while (regex_namespace::regex_search(s, matchResults, r))
    {
        values.push_back(matchResults[0]);
        s = matchResults.suffix().str();
    }

    return values;
}

std::string::const_iterator extractNext(std::string::const_iterator begin, std::string::const_iterator end, const std::string & regex, std::string & match)
{
    match.clear();

    regex_namespace::smatch matchResults;
    const regex_namespace::regex r(regex);

    if (!regex_namespace::regex_search(begin, end, matchResults, r))
    {
        return begin;
    }

    match = matchResults[0];

    return begin + match.size();
}

const char * extractNext(const char * begin, const char * end, const std::string & regex, std::string & match)
{
    match.clear();

    regex_namespace::cmatch matchResults;
    const regex_namespace::regex r(regex);

    if (!regex_namespace::regex_search(begin, end, matchResults, r))
    {
        return begin;
    }

    match = matchResults[0];

    return begin + match.size();
}

} // namespace string
} // namespace cppassist


text:
#ifndef VAR_STORE_HPP
#define VAR_STORE_HPP

#include <cstddef>
#include <tuple>
#include <type_traits>
#include <boost/fusion/include/as_list.hpp>
#include <boost/fusion/include/deref.hpp>
#include <boost/fusion/include/empty.hpp>
#include <boost/fusion/include/end.hpp>
#include <boost/fusion/include/find_if.hpp>
#include <boost/fusion/include/join.hpp>
#include <boost/fusion/include/make_list.hpp>
#include <boost/mpl/bool.hpp>

#include "terminal.hpp"

namespace sme { namespace detail {

    namespace varstore {

        namespace fusion = boost::fusion;
        namespace mpl = boost::mpl;

        // used by fusion::find_if to find a var
        template<typename Tuple, typename VarId>
        struct find_var {
            using Tuple_ = std::remove_cv_t<std::remove_reference_t<Tuple>>;

            using type =
                typename std::conditional<
                    std::is_same<
                        typename std::tuple_element<0, Tuple_>::type,
                        VarId
                    >::value,
                    mpl::true_,
                    mpl::false_
                >::type;
        };

        // check if a var exists or not
        template<typename VarStore, typename VarId>
        struct check_var_existence {
            static_assert(
                terminal::is_var<VarId>::value,
                "\n\n\n\n*****     invalid var type     *****\n\n\n"
            );

            static std::size_t const value =
                !fusion::result_of::empty<VarStore const>::type::value &&
                !std::is_same<
                    typename fusion::result_of::find_if<
                        VarStore const,
                        find_var<mpl::_, VarId>
                    >::type,
                    typename fusion::result_of::end<VarStore const>::type
                >::value;
        };

        // get a var from varstore
        template<typename VarId, typename VarStore>
        decltype(auto) get_var(VarStore const& store) {
            static_assert(
                check_var_existence<VarStore const, VarId>::value,
                "\n\n\n\n*****     cannot find var     *****\n\n\n"
            );

            return fusion::deref(fusion::find_if<find_var<mpl::_, VarId>>(store));
        }

        // create varstore view from a list of varstores
        template<typename VS1, typename VS2>
        decltype(auto) create_view(VS1 const& s1, VS2 const& s2) {
            return fusion::join(s1, s2);
        }

        template<typename VSFirst, typename... VSRest>
        decltype(auto) create_view(VSFirst const& sfirst, VSRest const&... srest) {
            return create_view(sfirst, create_view(srest...));
        }

        // turn varstore view to real varstore
        template<typename VarStoreView>
        decltype(auto) varstore_from_view(VarStoreView const& view) {
            return fusion::as_list(view);
        }

        // create varstore from a list of vars
        template<typename... Var>
        decltype(auto) varstore_from_var(Var const&... var) {
            return fusion::make_list(var...);
        }

        // create an empty varstore
        auto empty() {
            return fusion::nil{};
        }

    } // namespace varstore

}} // namespace sme::detail

#endif // VAR_STORE_HPP


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        :
// Author      : Avi
// Revision    : $Revision: #11 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8

#include <stdexcept>
#include "Pid.hpp"
#include <unistd.h>    // for getpid
#include <boost/lexical_cast.hpp>

std::string Pid::getpid()
{
   std::string pid;
   try { pid = boost::lexical_cast<std::string>(::getpid());  }
   catch (boost::bad_lexical_cast& e) {
      throw std::runtime_error("Pid::getpid(): Could not convert PID to a string\n");
   }
   return pid;
}

std::string Pid::unique_name(const std:: string& prefix)
{
   std::string ret = prefix;
   ret += "_";
   ret += Pid::getpid();
   return ret;
}

max_stars_repo_name: ecmwf/ecflow

max_issues_repo_name: CoollRock/ecflow

max_forks_repo_name: CoollRock/ecflow


text:
#define CATCH_CONFIG_MAIN

#include "CALPHADFreeEnergyFunctionsBinary3Ph2Sl.h"
#include "InterpolationType.h"

#include "catch.hpp"

#include <boost/optional/optional.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <fstream>
#include <iostream>
#include <string>

namespace pt = boost::property_tree;

TEST_CASE("CALPHAD binary three phase, two sublattice KKS",
    "[binary three phase, two sublattice kks]")
{
    Thermo4PFM::EnergyInterpolationType energy_interp_func_type
        = Thermo4PFM::EnergyInterpolationType::PBG;
    Thermo4PFM::ConcInterpolationType conc_interp_func_type
        = Thermo4PFM::ConcInterpolationType::PBG;

    double temperature = 820.;

    std::cout << " Read CALPHAD database..." << std::endl;
    pt::ptree calphad_db;
    try
    {
        pt::read_json(
            "../thermodynamic_data/calphadAlCuLFccTheta.json", calphad_db);
    }
    catch (std::exception& e)
    {
        std::cerr << "exception caught: " << e.what() << std::endl;
    }

    pt::ptree newton_db;
    newton_db.put("alpha", 0.5);
    newton_db.put("max_its", 100);

    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(
        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);

    // initial guesses
    double c_init0 = 0.8;
    double c_init1 = 0.6;
    double c_init2 = 0.67;

    double sol[3] = { c_init0, c_init1, c_init2 };

    // compute concentrations satisfying KKS equations
    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range
    double conc = 0.7;

    // This phi doesn't quite give Sum(h(phi)) = 1, but it is close
    double phi[3] = { 0.3, 0.45, 0.5 };

    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);

    std::cout << "-------------------------------" << std::endl;
    std::cout << "Temperature = " << temperature << std::endl;
    std::cout << "Result for c = " << conc << " and phi = " << phi[0] << " "
              << phi[1] << " " << phi[2] << std::endl;
    std::cout << "   cL = " << sol[0] << std::endl;
    std::cout << "   cA = " << sol[1] << std::endl;
    std::cout << "   cB = " << sol[2] << std::endl;

    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;
    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;
    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;

    std::cout << "Verification:" << std::endl;

    double derivL;
    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);
    std::cout << "   dfL/dcL = " << derivL << std::endl;

    double derivS1;
    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);
    std::cout << "   dfS1/dcS1 = " << derivS1 << std::endl;

    REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));

    double derivS2;
    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);
    std::cout << "   dfS2/dcS2 = " << derivS2 << std::endl;

    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));
}

TEST_CASE("CALPHAD binary three phase, two sublattice KKS #2",
    "[binary three phase, two sublattice kks #2]")
{
    Thermo4PFM::EnergyInterpolationType energy_interp_func_type
        = Thermo4PFM::EnergyInterpolationType::PBG;
    Thermo4PFM::ConcInterpolationType conc_interp_func_type
        = Thermo4PFM::ConcInterpolationType::PBG;

    double temperature = 820.;

    std::cout << " Read CALPHAD database..." << std::endl;
    pt::ptree calphad_db;
    try
    {
        pt::read_json(
            "../thermodynamic_data/calphadAlCuLFccTheta.json", calphad_db);
    }
    catch (std::exception& e)
    {
        std::cerr << "exception caught: " << e.what() << std::endl;
    }

    pt::ptree newton_db;
    newton_db.put("alpha", 1.0);
    newton_db.put("max_its", 20000);

    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(
        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);

    // initial guesses
    double c_init0 = 0.79267;
    double c_init1 = 0.79267;
    double c_init2 = 0.79267;

    double sol[3] = { c_init0, c_init1, c_init2 };

    // compute concentrations satisfying KKS equations
    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range
    double conc = 0.79267;

    // This phi doesn't quite give Sum(h(phi)) = 1, but it is close
    double phi[3] = { 0.938956, 5.88418e-15, 0.0610444 };

    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);

    std::cout << "-------------------------------" << std::endl;
    std::cout << "Temperature = " << temperature << std::endl;
    std::cout << "Result for c = " << conc << " and phi = " << phi[0] << " "
              << phi[1] << " " << phi[2] << std::endl;
    std::cout << "   cL = " << sol[0] << std::endl;
    std::cout << "   cA = " << sol[1] << std::endl;
    std::cout << "   cB = " << sol[2] << std::endl;

    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;
    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;
    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;

    std::cout << "Verification:" << std::endl;

    double derivL;
    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);
    std::cout << "   dfL/dcL = " << derivL << std::endl;

    double derivS1;
    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);
    std::cout << "   dfS1/dcS1 = " << derivS1 << std::endl;

    // REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));

    double derivS2;
    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);
    std::cout << "   dfS2/dcS2 = " << derivS2 << std::endl;

    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));
}

TEST_CASE("CALPHAD binary three phase, two sublattice KKS #3",
    "[binary three phase, two sublattice kks #3]")
{
    // This case may require a restart of the solver with new initial conditions
    // to pass.

    Thermo4PFM::EnergyInterpolationType energy_interp_func_type
        = Thermo4PFM::EnergyInterpolationType::PBG;
    Thermo4PFM::ConcInterpolationType conc_interp_func_type
        = Thermo4PFM::ConcInterpolationType::PBG;

    double temperature = 820.;

    std::cout << " Read CALPHAD database..." << std::endl;
    pt::ptree calphad_db;
    try
    {
        pt::read_json(
            "../thermodynamic_data/calphadAlCuLFccTheta.json", calphad_db);
    }
    catch (std::exception& e)
    {
        std::cerr << "exception caught: " << e.what() << std::endl;
    }

    pt::ptree newton_db;
    newton_db.put("alpha", 1.0);
    newton_db.put("max_its", 30);

    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(
        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);

    // initial guesses
    double c_init0 = 0.800000011921;
    double c_init1 = 0.800000011921;
    double c_init2 = 0.800000011921;

    double sol[3] = { c_init0, c_init1, c_init2 };

    // compute concentrations satisfying KKS equations
    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range
    double conc = 0.800000011921;

    // Want phi that corresponds to hphi = [0.982551, 0.0174491, 4.79499e-25]
    // Want phi that corresponds to hphi = [1.0, 6.18271e-09, 3.69779e-32]
    // double phi[3] = { 0.998, 8.5e-4, 1.5e-11 };
    double phi[3] = { 0.998, 8.5e-4, 1.5e-11 };

    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);

    std::cout << "-------------------------------" << std::endl;
    std::cout << "Temperature = " << temperature << std::endl;
    std::cout << "Result for c = " << conc << " and phi = " << phi[0] << " "
              << phi[1] << " " << phi[2] << std::endl;
    std::cout << "   cL = " << sol[0] << std::endl;
    std::cout << "   cA = " << sol[1] << std::endl;
    std::cout << "   cB = " << sol[2] << std::endl;

    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;
    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;
    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;

    std::cout << "Verification:" << std::endl;

    double derivL;
    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);
    std::cout << "   dfL/dcL = " << derivL << std::endl;

    double derivS1;
    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);
    std::cout << "   dfS1/dcS1 = " << derivS1 << std::endl;

    REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));

    double derivS2;
    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);
    std::cout << "   dfS2/dcS2 = " << derivS2 << std::endl;

    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));
}


text: #include <boost/units/systems/si/area.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//==============================================================================
//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_UTILITY_CONFIG_HPP_INCLUDED
#define NT2_CORE_UTILITY_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>

#ifdef NT2_CORE_RANDOM_DYN_LINK
#  ifdef NT2_CORE_RANDOM_SOURCE
#    define NT2_CORE_RANDOM_DECL BOOST_SYMBOL_EXPORT
#  else
#    define NT2_CORE_RANDOM_DECL BOOST_SYMBOL_IMPORT
#  endif
#else
#  define NT2_CORE_RANDOM_DECL
#endif

#endif


text:
//======================================================================
/*! \file IbeoSutpSendInterface.hpp
 *
 * \copydoc Copyright
 * \author Jan Christian Dittmer (jcd)
 * \date May 3, 2017
 *///-------------------------------------------------------------------

#ifndef SRC_IBEOSDK_DEVICES_SUTP_IBEOSUTPSENDINTERFACE_HPP_SEEN
#define SRC_IBEOSDK_DEVICES_SUTP_IBEOSUTPSENDINTERFACE_HPP_SEEN

//======================================================================

#include <ibeosdk/misc/WinCompatibility.hpp>

#include <ibeosdk/datablocks/snippets/IbeoDataHeader.hpp>

#include <boost/function.hpp>
#include <boost/asio.hpp>

//======================================================================

namespace ibeosdk {

//======================================================================

class IbeoSutpSendInterface {
public:
	typedef boost::function<bool(boost::asio::streambuf& outBuff)> SendingFunction;

public:
	IbeoSutpSendInterface(SendingFunction sender);
	virtual ~IbeoSutpSendInterface();

public:
	void send(const IbeoDataHeader& dh, const char* const buffer);
//	void send(const IbeoDataHeader& dh, std::istream& is);

protected:
	void serializeSutpHeader(std::ostream& os,
	                         const uint16_t fragmentId, const uint16_t nbOfFragments,
	                         const DataTypeId dtId);

protected:
	static const uint64_t timeOutDurationMs;
	static const int64_t fragmentSize;

protected:
	SendingFunction m_sending;

	//! sequenceNumber counter for sending SUTP packages
	uint16_t m_segNo;

	//! id of the device that owns this connection
	uint8_t m_deviceId;

	uint32_t m_nbOfSendPackages;

}; // IbeoSutpSendInterface

//======================================================================

}// namespace ibeosdk

//======================================================================

#endif // SRC_IBEOSDK_DEVICES_SUTP_IBEOSUTPSENDINTERFACE_HPP_SEEN

//======================================================================


text:
/**
 * @file dataset_info.hpp
 * @author Ryan Curtin
 *
 * Defines the DatasetInfo class, which holds information about a dataset.  This
 * is useful when the dataset contains categorical non-numeric features that
 * needs to be mapped to categorical numeric features.
 */
#ifndef MLPACK_CORE_DATA_DATASET_INFO_HPP
#define MLPACK_CORE_DATA_DATASET_INFO_HPP

#include <mlpack/core.hpp>
#include <unordered_map>
#include <boost/bimap.hpp>

namespace mlpack {
namespace data {

/**
 * The Datatype enum specifies the types of data mlpack algorithms can use.  The
 * vast majority of mlpack algorithms can only use numeric data (i.e.
 * float/double/etc.), but some algorithms can use categorical data, specified
 * via this Datatype enum and the DatasetInfo class.
 */
enum Datatype : bool /* bool is all the precision we need for two types */
{
  numeric = 0,
  categorical = 1
};

/**
 * Auxiliary information for a dataset, including mappings to/from strings and
 * the datatype of each dimension.  DatasetInfo objects are optionally produced
 * by data::Load(), and store the type of each dimension (Datatype::numeric or
 * Datatype::categorical) as well as mappings from strings to unsigned integers
 * and vice versa.
 */
class DatasetInfo
{
 public:
  /**
   * Create the DatasetInfo object with the given dimensionality.  Note that the
   * dimensionality cannot be changed later; you will have to create a new
   * DatasetInfo object.
   */
  DatasetInfo(const size_t dimensionality = 0);

  /**
   * Given the string and the dimension to which it belongs, return its numeric
   * mapping.  If no mapping yet exists, the string is added to the list of
   * mappings for the given dimension.  The dimension parameter refers to the
   * index of the dimension of the string (i.e. the row in the dataset).
   *
   * @param string String to find/create mapping for.
   * @param dimension Index of the dimension of the string.
   */
  size_t MapString(const std::string& string, const size_t dimension);

  /**
   * Return the string that corresponds to a given value in a given dimension.
   * If the string is not a valid mapping in the given dimension, a
   * std::invalid_argument is thrown.
   *
   * @param value Mapped value for string.
   * @param dimension Dimension to unmap string from.
   */
  const std::string& UnmapString(const size_t value, const size_t dimension);

  //! Return the type of a given dimension (numeric or categorical).
  Datatype Type(const size_t dimension) const;
  //! Modify the type of a given dimension (be careful!).
  Datatype& Type(const size_t dimension);

  /**
   * Get the number of mappings for a particular dimension.  If the dimension
   * is numeric, then this will return 0.
   */
  size_t NumMappings(const size_t dimension) const;

  /**
   * Get the dimensionality of the DatasetInfo object (that is, how many
   * dimensions it has information for).  If this object was created by a call
   * to mlpack::data::Load(), then the dimensionality will be the same as the
   * number of rows (dimensions) in the dataset.
   */
  size_t Dimensionality() const;

  /**
   * Serialize the dataset information.
   */
  template<typename Archive>
  void Serialize(Archive& ar, const unsigned int /* version */)
  {
    ar & data::CreateNVP(types, "types");
    ar & data::CreateNVP(maps, "maps");
  }

 private:
  //! Types of each dimension.
  std::vector<Datatype> types;

  //! Mappings from strings to integers.  Map entries will only exist for
  //! dimensions that are categorical.
  std::unordered_map<size_t, std::pair<boost::bimap<std::string, size_t>,
      size_t>> maps;

};

} // namespace data
} // namespace mlpack

#include "dataset_info_impl.hpp"

#endif


text:
/*
 *  Copyright 2011-2015 Maxim Milakov
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "network_schema.h"

#include "layer_factory.h"
#include "neural_network_exception.h"
#include "proto/nnforge.pb.h"

#include <boost/uuid/uuid_io.hpp>
#include <boost/format.hpp>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>

namespace nnforge
{
	// {51D12B28-F064-4F14-9AF1-F7FEA14AA141}
	const boost::uuids::uuid network_schema::schema_guid =
	{ 0x51, 0xd1, 0x2b, 0x28
	, 0xf0, 0x64
	, 0x4f, 0x14
	, 0x9a, 0xf1
	, 0xf7, 0xfe, 0xa1, 0x4a, 0xa1, 0x41 };

	network_schema::network_schema()
	{
	}

	const const_layer_list& network_schema::get_layers() const
	{
		return layers;
	}

	network_schema::operator const const_layer_list&() const
	{
		return get_layers();
	}

	void network_schema::add_layer(const_layer_smart_ptr new_layer)
	{
		layer_configuration new_config = new_layer->get_layer_configuration(output_config);

		layers.push_back(new_layer);

		output_config = new_config;
	}

	const boost::uuids::uuid& network_schema::get_uuid() const
	{
		return schema_guid;
	}

	void network_schema::write(std::ostream& binary_stream_to_write_to) const
	{
		binary_stream_to_write_to.exceptions(std::ostream::eofbit | std::ostream::failbit | std::ostream::badbit);

		const boost::uuids::uuid& network_guid = get_uuid();
		binary_stream_to_write_to.write(reinterpret_cast<const char*>(network_guid.data), sizeof(network_guid.data));

		const const_layer_list& layers_to_write = get_layers();
		unsigned int layer_count = static_cast<unsigned int>(layers_to_write.size());
		binary_stream_to_write_to.write(reinterpret_cast<const char*>(&layer_count), sizeof(layer_count));

		for(const_layer_list::const_iterator it = layers_to_write.begin(); it != layers_to_write.end(); ++it)
		{
			const boost::uuids::uuid& layer_guid = (*it)->get_uuid();
			binary_stream_to_write_to.write(reinterpret_cast<const char*>(layer_guid.data), sizeof(layer_guid.data));

			(*it)->write(binary_stream_to_write_to);
		}

		binary_stream_to_write_to.flush();
	}

	std::vector<layer_data_configuration_list> network_schema::get_layer_data_configuration_list_list() const
	{
		std::vector<layer_data_configuration_list> res;

		for(const_layer_list::const_iterator it = layers.begin(); it != layers.end(); ++it)
			res.push_back((*it)->get_layer_data_configuration_list());

		return res;
	}

	void network_schema::read(std::istream& binary_stream_to_read_from)
	{
		clear();

		binary_stream_to_read_from.exceptions(std::ostream::eofbit | std::ostream::failbit | std::ostream::badbit);

		boost::uuids::uuid network_guid_read;
		binary_stream_to_read_from.read(reinterpret_cast<char*>(network_guid_read.data), sizeof(network_guid_read.data));
		if (network_guid_read != get_uuid())
			throw neural_network_exception((boost::format("Unknown schema GUID encountered in input stream: %1%") % network_guid_read).str());

		unsigned int layer_count_read;
		binary_stream_to_read_from.read(reinterpret_cast<char*>(&layer_count_read), sizeof(layer_count_read));

		for(unsigned int i = 0; i < layer_count_read; ++i)
		{
			boost::uuids::uuid layer_read_guid;
			binary_stream_to_read_from.read(reinterpret_cast<char*>(layer_read_guid.data), sizeof(layer_read_guid.data));

			layer_smart_ptr new_layer = single_layer_factory::get_const_instance().create_layer(layer_read_guid);
			new_layer->read(binary_stream_to_read_from, layer_read_guid);
			add_layer(new_layer);
		}
	}

	void network_schema::write_proto(std::ostream& stream_to_write_to) const
	{
		protobuf::NetworkSchema schema;
		if (!name.empty())
			schema.set_name(name);

		for(int i = 0; i < layers.size(); ++i)
		{
			protobuf::Layer * layer_proto = schema.add_layer();
			const_layer_smart_ptr current_layer = layers[i];
			layer_proto->set_type(current_layer->get_type_name());
			if (!current_layer->instance_name.empty())
				layer_proto->set_name(current_layer->instance_name);

			current_layer->write_proto(layer_proto);
		}

		google::protobuf::io::OstreamOutputStream output_stream(&stream_to_write_to);
		google::protobuf::TextFormat::Print(schema, &output_stream);
	}

	void network_schema::read_proto(std::istream& stream_to_read_from)
	{
		clear();

		protobuf::NetworkSchema schema;
		google::protobuf::io::IstreamInputStream input_stream(&stream_to_read_from);
		google::protobuf::TextFormat::Parse(&input_stream, &schema);

		name = schema.name();

		for(int i = 0; i < schema.layer_size(); ++i)
		{
			layer_smart_ptr new_layer = single_layer_factory::get_const_instance().create_layer(schema.layer(i).type());
			new_layer->instance_name = schema.layer(i).name();
			new_layer->read_proto(&schema.layer(i));
			add_layer(new_layer);
		}
	}

	void network_schema::clear()
	{
		layers.clear();
		output_config = layer_configuration();
	}

	layer_configuration_specific_list network_schema::get_layer_configuration_specific_list(
		const layer_configuration_specific& input_layer_configuration_specific) const
	{
		layer_configuration_specific_list res;

		res.push_back(input_layer_configuration_specific);

		for(unsigned int i = 0; i < layers.size(); ++i)
			res.push_back(layers[i]->get_output_layer_configuration_specific(res[i]));

		return res;
	}

	layer_configuration_specific_list network_schema::get_layer_configuration_specific_list_reverse(const layer_configuration_specific& output_layer_configuration_specific) const
	{
		layer_configuration_specific_list res;

		res.resize(layers.size() + 1);
		res[layers.size()] = output_layer_configuration_specific;

		for(unsigned int i = static_cast<unsigned int>(layers.size()); i > 0; --i)
			res[i - 1] = (layers[i - 1]->get_input_layer_configuration_specific(res[i]));

		return res;
	}

	std::vector<std::pair<unsigned int, unsigned int> > network_schema::get_input_rectangle_borders(
		const std::vector<std::pair<unsigned int, unsigned int> >& output_rectangle_borders,
		unsigned int output_layer_id) const
	{
		std::vector<std::pair<unsigned int, unsigned int> > input_rectangle_borders = output_rectangle_borders;

		for(int i = static_cast<int>(output_layer_id); i >= 0; --i)
			input_rectangle_borders = layers[i]->get_input_rectangle_borders(input_rectangle_borders);

		return input_rectangle_borders;
	}

	std::vector<unsigned int> network_schema::get_cumulative_tiling_factor_list(tiling_factor input_tiling_factor) const
	{
		std::vector<unsigned int> res;
		res.push_back(input_tiling_factor);

		tiling_factor current_tiling_factor = input_tiling_factor;
		for(unsigned int i = 0; i < layers.size(); ++i)
		{
			tiling_factor new_tf = layers[i]->get_tiling_factor();
			current_tiling_factor = current_tiling_factor * new_tf;
			res.push_back(current_tiling_factor);
		}

		return res;
	}

	std::vector<unsigned int> network_schema::get_output_strides() const
	{
		std::vector<tiling_factor> min_factors;
		std::vector<tiling_factor> current_factors;
		for(int i = static_cast<int>(layers.size() - 1); i >= 0; --i)
		{
			std::vector<tiling_factor> tf_list = layers[i]->get_tiling_factor_list();

			for(int j = 0; j < tf_list.size(); ++j)
			{
				if (j < current_factors.size())
					current_factors[j] *= tf_list[j];
				else
					current_factors.push_back(tf_list[j]) ;
			}

			for(int j = 0; j < current_factors.size(); ++j)
			{
				if (j < min_factors.size())
					min_factors[j] = std::min(min_factors[j], current_factors[j]);
				else
					min_factors.push_back(current_factors[j]);
			}
		}

		std::vector<unsigned int> res;
		for(int i = 0; i < min_factors.size(); ++i)
		{
			if (min_factors[i] > tiling_factor(1))
				throw neural_network_exception((boost::format("network_schema::get_output_strides - invalid minimum stride %1% encountered at dimension %2%") % min_factors[i].str() % i).str());

			res.push_back(min_factors[i].get_inverse());
		}

		return res;
	}
}

max_stars_repo_name: anshumang/nnForgeINST

max_issues_repo_name: anshumang/nnForgeINST

max_forks_repo_name: anshumang/nnForgeINST


text:
#include "mp/co_moving_detection.hpp"

#include <iostream>
#include <dlib/svm.h>

#include "mp/feature_computation.hpp"
#include "mp/ground_truth.hpp"

namespace mp {

// Increment if any details in the layout of
// co_moving_classifier::impl change.
static const i32 VERSION = 3;

using sample_type        = dlib::matrix<double, 0, 1>; // 0 -> row size determined at runtime
using vector_normalizer  = dlib::vector_normalizer<sample_type>;
using kernel_type        = dlib::linear_kernel<sample_type>;
using trainer_type       = dlib::svm_c_linear_trainer<kernel_type>; // TODO: Decide on a final trainer type.
using decision_func_type = dlib::decision_function<kernel_type>;
using function_type      = dlib::normalized_function<decision_func_type>;

// Extracts a vector of samples (== feature vectors) and labels (== co-moving/not co-moving)
// from the input data.
static void get_learning_data(const similarity_data &data, const ground_truth &gt,
                              vector<sample_type> &samples, vector<double> &labels)
{
    samples.clear();
    labels.clear();

    samples.reserve(data.pairs.size() * data.duration);
    labels.reserve(data.pairs.size() * data.duration);

    sample_type sample;
    sample.set_size(data.feature_dimension, 1);
    // For each pair ...
    for (auto &pair : data.pairs) {
        const string &left_name = data.devices[pair.left];
        const string &right_name = data.devices[pair.right];

        // ... and each timestamp ...
        for (i64 ts = data.begin_timestamp; ts <= data.end_timestamp; ++ts) {
            // ... get the feature vector and its corresponding ground truth
            auto feature = data.feature_at(pair, ts);
            for (i32 i = 0; i < data.feature_dimension; ++i) {
                sample(i) = feature[i];
            }
            samples.push_back(sample);

            bool co_moving = gt.co_moving_at(ts, left_name, right_name);
            labels.push_back(co_moving ? 1.0 : -1.0);
        }
    }
}

// Trains the given normalizer using the provided samples
// and then normalizes the samples.
static void normalize(vector_normalizer &norm, vector<sample_type> &samples)
{
    norm.train(samples);
    for (auto &sample : samples) {
        sample = norm(sample);
    }
}

struct co_moving_classifier::impl
{
    function_type func;
    size_t        training_dimension;
    sample_type   sample;
};

void co_moving_classifier::print_cross_validation(const similarity_data &data, const ground_truth &gt, std::ostream &o)
{
    vector<sample_type> samples;
    vector<double> labels;
    get_learning_data(data, gt, samples, labels);
    dlib::randomize_samples(samples, labels);

    vector_normalizer norm;
    normalize(norm, samples);

    trainer_type trainer;
    o << "Cross validation results: " << std::endl;
    for (double C = 1; C < 100000; C *= 5) {
        trainer.set_c(C);

        // Two values:
        // - fraction of correctly identified +1 cases
        // - ________________________________ -1 cases
        o << "C = " << C
          << ", accuracy = " << dlib::cross_validate_trainer(trainer, samples, labels, 3);
        o << std::flush;
    }
}

bool co_moving_classifier::co_moving(array_view<const double> a)
{
    if (!m_impl) {
        return false;
    }

    // May only be used with an input dimension
    // that equals the training dimension.
    assert(a.size() == m_impl->training_dimension);

    // Sample is an instance of sample_type that is
    // cached by this instance of co_moving_classifier.
    // This saves us an allocation per classification.
    sample_type &sample = m_impl->sample;
    for (size_t i = 0; i < m_impl->training_dimension; ++i) {
        sample(i) = a[i];
    }
    return m_impl->func(sample) >= 0;
}

void co_moving_classifier::learn(const similarity_data &data, const ground_truth &gt)
{
    trainer_type trainer;
    trainer.set_c(1);

    vector<sample_type> samples;
    vector<double> labels;
    get_learning_data(data, gt, samples, labels);
    dlib::randomize_samples(samples, labels);

    vector_normalizer norm;
    normalize(norm, samples);

    std::unique_ptr<impl> ptr(new impl());
    ptr->training_dimension = data.feature_dimension;
    ptr->func.normalizer = norm; // other samples will be normalized, too.
    ptr->func.function = trainer.train(samples, labels);
    ptr->sample.set_size(ptr->training_dimension, 1);
    m_impl = std::move(ptr);
}

void co_moving_classifier::load(std::istream &i)
{
    i32 version;
    dlib::deserialize(version, i);
    if (version != VERSION) {
        throw std::runtime_error("Serialized classifier has incorrect version " + std::to_string(version)
                                 + ", version must be " + std::to_string(VERSION));
    }

    bool valid;
    dlib::deserialize(valid, i);
    if (valid) {
        std::unique_ptr<impl> ptr(new impl());
        dlib::deserialize(ptr->func, i);
        dlib::deserialize(ptr->training_dimension, i);
        ptr->sample.set_size(ptr->training_dimension, 1);
        m_impl = std::move(ptr);
    } else {
        m_impl.reset();
    }
}

void co_moving_classifier::save(std::ostream &o) const
{
    dlib::serialize(VERSION, o);
    bool valid = static_cast<bool>(m_impl);
    dlib::serialize(valid, o);

    if (valid) {
        dlib::serialize(m_impl->func, o);
        dlib::serialize(m_impl->training_dimension, o);
        // sample does not need to be stored,
        // because its value does not matter and its
        // size equals training_dimension.
    }
}

co_moving_classifier::co_moving_classifier()
    : m_impl()
{}

co_moving_classifier::~co_moving_classifier()
{}

co_moving_classifier::co_moving_classifier(co_moving_classifier &&other)
    : m_impl(std::move(other.m_impl))
{}

co_moving_classifier& co_moving_classifier::operator =(co_moving_classifier &&other)
{
    m_impl = std::move(other.m_impl);
    return *this;
}

} // namespace mp

max_stars_repo_name: mbeckem/mp

max_issues_repo_name: mbeckem/mp

max_forks_repo_name: mbeckem/mp


text:
#include "k8deployer/Kubeconfig.h"
#include "k8deployer/Component.h"

#include <boost/fusion/adapted.hpp>

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::ClusterData,
    (std::string, certificate_authority)
    (std::string, certificate_authority_data)
    (std::string, server)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::Cluster,
    (k8deployer::Kubeconfig::ClusterData, cluster)
    (std::string, name)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::UserData,
    (std::string, client_certificate)
    (std::string, client_certificate_data)
    (std::string, client_key)
    (std::string, client_key_data)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::User,
    (std::string, name)
    (k8deployer::Kubeconfig::UserData, user)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::ContextData,
    (std::string, cluster)
    (std::string, user)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig::Context,
    (std::string, name)
    (k8deployer::Kubeconfig::ContextData, context)
);

BOOST_FUSION_ADAPT_STRUCT(k8deployer::Kubeconfig,
    (std::string, kind)
    (std::string, apiVersion)
    (std::string, current_context)
    (std::vector<k8deployer::Kubeconfig::Cluster>, clusters)
    (std::vector<k8deployer::Kubeconfig::User>, users)
    (std::vector<k8deployer::Kubeconfig::Context>, contexts)

);

namespace k8deployer {

using namespace std;
using namespace std::string_literals;

namespace {

// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
static std::string base64_decode(const std::string &in) {

    string out;

    vector<int> T(256,-1);
    for (int i=0; i<64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;

    int val=0, valb=-8;
    for (uint8_t c : in) {
        if (T[c] == -1) break;
        val = (val << 6) + T[c];
        valb += 6;
        if (valb >= 0) {
            out.push_back(char((val>>valb)&0xFF));
            valb -= 8;
        }
    }
    return out;
}

} // ns

string Kubeconfig::getCaCert() const
{
    if (!clusters.at(activeCluster).cluster.certificate_authority_data.empty()) {
        return base64_decode(clusters.at(activeCluster).cluster.certificate_authority_data);
    }

    return slurp(clusters.at(activeCluster).cluster.certificate_authority);
}

string Kubeconfig::getClientCert() const
{
    if (!users.at(activeUser).user.client_certificate_data.empty()) {
        return base64_decode(users.at(activeUser).user.client_certificate_data);
    }

    return slurp(users.at(activeUser).user.client_certificate);
}

string Kubeconfig::getClientKey() const
{
    if (!users.at(activeUser).user.client_key_data.empty()) {
        return base64_decode(users.at(activeUser).user.client_key_data);
    }

    return slurp(users.at(activeUser).user.client_key);
}

string Kubeconfig::getServer() const
{
    return clusters.at(activeCluster).cluster.server;
}

string Kubeconfig::getClusterName() const
{
    return clusters.at(activeCluster).name;
}

unique_ptr<Kubeconfig> Kubeconfig::load(const string &kubefile)
{
    static const restc_cpp::JsonFieldMapping mappings = {
        {"certificate_authority_data", "certificate-authority-data"},
        {"client_certificate_data", "client-certificate-data"},
        {"client_key_data", "client-key-data"},
        {"current_context", "current-context"},
        {"certificate_authority", "certificate-authority"},
        {"client_certificate", "client-certificate"},
        {"client_key", "client-key"}
    };

    const auto path = getKubeconfig(kubefile);

    // Convert yaml file to json
    auto json = fileToJson(path.string(), true);

    // Deserialize json to Kubeconfig instance
    auto kc = make_unique<Kubeconfig>();
    std::istringstream ifs{json};
    restc_cpp::serialize_properties_t properties;
    properties.ignore_unknown_properties = true;
    properties.name_mapping = &mappings;
    restc_cpp::SerializeFromJson(*kc, ifs, properties);

    if (kc->clusters.empty()) {
        throw runtime_error{"No clusters in kubeconfig: "s + path.string()};
    }

    // Deal with contexts
    bool gotCurrentContext = kc->current_context.empty();
    if (!gotCurrentContext) {
        for(const auto& c : kc->contexts) {
            if (kc->current_context == c.name) {
                // Resolve cluster
                for(const auto& cluster: kc->clusters) {
                    if (cluster.name == c.context.cluster) {
                        // Resolve user
                        for (const auto& user: kc ->users) {
                            if (user.name == c.context.user) {
                                gotCurrentContext = true;
                                break;
                            }
                            ++kc->activeUser;
                        }
                        break;
                    }
                    ++kc->activeCluster;
                }
                break;
            }
        }
    }

    if (!gotCurrentContext) {
        throw runtime_error("Failed to resolve current context: "s + kc->current_context);
    }

    return kc;
}

filesystem::path Kubeconfig::getKubeconfig(const string &kubefile)
{
    filesystem::path path;

    if (!kubefile.empty()) {
        path = kubefile;
    } else if (auto env = getenv("KUBECONFIG")) {
        // For now, support only one file in this environment variable
        path = env;
    } else {
        path = getenv("HOME");
        path /= ".kube";
        path /= "config";
    }

    if (!filesystem::is_regular_file(path)) {
        throw std::runtime_error("No such path: "s + path.string());
    }

    return path;
}

} // ns


text:
/**********************************************************************
 *  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
 *  All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 **********************************************************************/

#include <analysis/DesignOfExperimentsOptions.hpp>
#include <analysis/DesignOfExperimentsOptions_Impl.hpp>

#include <utilities/core/Json.hpp>

#include <boost/function.hpp>
#include <boost/bind.hpp>

namespace openstudio {
namespace analysis {

namespace detail {

  DesignOfExperimentsOptions_Impl::DesignOfExperimentsOptions_Impl(
      const DesignOfExperimentsType& designType)
    : AlgorithmOptions_Impl(), m_designType(designType)
  {}

  DesignOfExperimentsOptions_Impl::DesignOfExperimentsOptions_Impl(
      const DesignOfExperimentsType& designType,
      const std::vector<Attribute>& options)
    : AlgorithmOptions_Impl(options), m_designType(designType)
  {}

  AlgorithmOptions DesignOfExperimentsOptions_Impl::clone() const {
    boost::shared_ptr<DesignOfExperimentsOptions_Impl> impl(new DesignOfExperimentsOptions_Impl(*this));
    return DesignOfExperimentsOptions(impl);
  }

  DesignOfExperimentsType DesignOfExperimentsOptions_Impl::designType() const {
    return m_designType;
  }

  void DesignOfExperimentsOptions_Impl::setDesignType(const DesignOfExperimentsType& designType) {
    m_designType = designType;
  }

  QVariant DesignOfExperimentsOptions_Impl::toVariant() const {
    QVariantMap map = AlgorithmOptions_Impl::toVariant().toMap();

    map["design_type"] = toQString(designType().valueName());

    return QVariant(map);
  }

  DesignOfExperimentsOptions DesignOfExperimentsOptions_Impl::fromVariant(const QVariant& variant,
                                                                          const VersionString& version)
  {
    QVariantMap map = variant.toMap();
    AttributeVector attributes = deserializeUnorderedVector(
          map["attributes"].toList(),
          boost::function<Attribute (const QVariant&)>(boost::bind(openstudio::detail::toAttribute,_1,version)));
    return DesignOfExperimentsOptions(DesignOfExperimentsType(map["design_type"].toString().toStdString()),
                                      attributes);
  }

} // detail

DesignOfExperimentsOptions::DesignOfExperimentsOptions(const DesignOfExperimentsType& designType)
  : AlgorithmOptions(boost::shared_ptr<detail::DesignOfExperimentsOptions_Impl>(
        new detail::DesignOfExperimentsOptions_Impl(designType)))
{}

DesignOfExperimentsOptions::DesignOfExperimentsOptions(const DesignOfExperimentsType& designType,
                                                       const std::vector<Attribute>& options)
  : AlgorithmOptions(boost::shared_ptr<detail::DesignOfExperimentsOptions_Impl>(
        new detail::DesignOfExperimentsOptions_Impl(designType,options)))
{}

DesignOfExperimentsType DesignOfExperimentsOptions::designType() const {
  return getImpl<detail::DesignOfExperimentsOptions_Impl>()->designType();
}

void DesignOfExperimentsOptions::setDesignType(const DesignOfExperimentsType& designType) {
  getImpl<detail::DesignOfExperimentsOptions_Impl>()->setDesignType(designType);
}

/// @cond
DesignOfExperimentsOptions::DesignOfExperimentsOptions(boost::shared_ptr<detail::DesignOfExperimentsOptions_Impl> impl)
  : AlgorithmOptions(impl)
{}
/// @endcond

} // analysis
} // openstudio

max_stars_repo_name: ORNL-BTRIC/OpenStudio

max_issues_repo_name: ORNL-BTRIC/OpenStudio

max_forks_repo_name: ORNL-BTRIC/OpenStudio


text:
///////////////////////////////////////////////////////////////////////////////
// frequency.hpp                                                             //
//                                                                           //
//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //
//  Software License, Version 1.0. (See accompanying file                    //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_ACCUMULATOR_STATISTICS_FREQUENCY_HPP_ER_2010
#define BOOST_STATISTICS_DETAIL_ACCUMULATOR_STATISTICS_FREQUENCY_HPP_ER_2010
/*

#include <iostream> // tmp

#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/if.hpp>

#include <boost/parameter/binding.hpp>

#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/parameters/accumulator.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/count.hpp>

#include <boost/statistics/detail/non_parametric/empirical_distribution/count.hpp>

namespace boost {
namespace statistics{
namespace detail{
namespace empirical_distribution{

    // Usage:
    //     namespace ns = empirical_distribution;
    //     accumulator_set<T,stats<ns::tag::count<is_cum> > > acc;
    //     acc = boost:for_each(samples,acc);
    //     ns::extract::count<is_cum>(acc,x);
    // The result of the last statement is the % of observation matching (less
    // than) x in the samples if is_cum = false (true).

namespace impl{

    // Frequency as percentage of the sample size
    //
    // Warning : See empirical_distribution::impl::count.
	template<typename T,bool is_cum,typename T1>
	class frequency : public boost::accumulators::accumulator_base{

		typedef std::size_t size_;
        typedef boost::accumulators::dont_care dont_care_;

        public:

        frequency(dont_care_){}

        typedef size_ size_type;
        typedef T sample_type;  // See accumulator_set
        typedef T1 result_type;

        void operator()(dont_care_)const{}

        template<typename Args>
        result_type result(const Args& args) const
        {
        }
    };

}

namespace tag
{
    template<bool is_cum,typename T1 = double>
    struct frequency
      : boost::accumulators::depends_on<
      	statistics::detail::empirical_distribution::tag::count<is_cum>,
        boost::accumulators::tag::count
    >
    {
        struct impl{
            template<typename T,typename W>
            struct apply{
        		typedef statistics::detail::empirical_distribution
                	::impl::frequency<T,is_cum,T1> type;
            };
        };
    };
}

namespace result_of{

    template<bool is_cum,typename T1,typename AccSet>
    struct frequency{

        typedef boost::statistics::detail
        	::empirical_distribution::tag::frequency<is_cum,T1> tag_;
        typedef typename boost::accumulators
        	::detail::template extractor_result<AccSet,tag_>::type type;

    };
}

namespace extract
{

    // Usage : frequency<is_cum,T1>(acc,x)
    template<bool is_cum,typename T1,typename AccSet,typename T>
    typename boost::statistics::detail::empirical_distribution
    	::result_of::template frequency<is_cum,T1,AccSet>::type
    frequency(AccSet const& acc,const T& x)
    {
		    typedef std::size_t size_;
        	typedef boost::accumulators::tag::count tag_n_;

            namespace ns = boost::statistics::detail::empirical_distribution;

            size_ i =  ns::extract::count<is_cum>( acc, x );
            size_ n = boost::accumulators::extract_result<tag_n_>( acc );
            return static_cast<T1>(i)/static_cast<T1>(n);
    }

}

using extract::frequency;

}// empirical_distribution
}// detail
}// statistics
}// boost

*/

#endif


text:
#include "ArrayAccessExpression.h"
#include "NumberVariable.h"
#include "ArrayVariable.h"
#include "StringVariable.h"
#include "exceptions/IllegalArrayAccessOperationException.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <typeinfo>

using namespace thewizardplusplus::wizard_basic_2::compiler::translator;
using namespace thewizardplusplus::wizard_basic_2::compiler::translator::
	exceptions;
using namespace boost;

ArrayAccessExpression::ArrayAccessExpression(const Variable::Pointer& variable,
	const Expression::Pointer& index_expression)
:
	Expression(ValueType::NUMBER),
	variable(variable),
	index_expression(index_expression)
{
	ValueType::Types variable_type = ValueType::UNKNOWN_TYPE;
	if (typeid(*variable) == typeid(NumberVariable)) {
		variable_type = ValueType::NUMBER;
	} else if (typeid(*variable) == typeid(ArrayVariable) || typeid(*variable)
		== typeid(StringVariable))
	{
		variable_type = ValueType::ARRAY;
	}

	if (variable_type != ValueType::ARRAY || index_expression->getType() !=
		ValueType::NUMBER)
	{
		throw IllegalArrayAccessOperationException(variable_type,
			index_expression->getType());
	}
}

std::string ArrayAccessExpression::getCppCode(void) const {
	return (format("%1%[%2%]") % variable->getName() % index_expression->
		getCppCode()).str();
}