text:
#include "solver/eigenvalue/krylov_schur_eigenvalue_solver.hpp"

#include <deal.II/base/mpi.h>
#include <deal.II/lac/slepc_solver.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/lac/petsc_vector.h>

namespace bart::solver::eigenvalue {

auto KrylovSchurEigenvalueSolver::SpectralRadius(const SpectralRadiusI::MatrixBase& base)
-> std::pair<double, std::vector<double>> {
  dealii::SolverControl solver_control(1000, 1e-6);
  dealii::SLEPcWrappers::SolverKrylovSchur solver(solver_control);

  const auto m{ base.m() };

  std::vector<double> eigenvalues(m);
  std::vector<dealii::PETScWrappers::MPI::Vector> eigenvectors(m);
  for (auto& eigenvector : eigenvectors)
    eigenvector.reinit(MPI_COMM_WORLD, m, m);

  solver.solve(base, eigenvalues, eigenvectors, m);

  auto max_element_index = std::distance(eigenvalues.begin(), std::max_element(eigenvalues.begin(), eigenvalues.end()));

  std::vector<double> return_eigenvector(m);

  for (int i = 0; i < return_eigenvector.size(); ++i)
    return_eigenvector.at(i) = eigenvectors.at(max_element_index)[i];

  return {eigenvalues.at(max_element_index), return_eigenvector};
}

} // namespace bart::solver::eigenvalue

ext: cpp

max_stars_repo_name: SlaybaughLab/Transport

max_issues_repo_name: SlaybaughLab/Transport

max_forks_repo_name: SlaybaughLab/Transport


text:
/*
 * outputCSV.cpp
 *
 *  Created on: Aug 25, 2019
 *      Author: wzeng
 */

#include "grDB.h"
#include "graph.h" // for undirected Graph from boost
#include <iterator>
#include <fstream>
#include <cassert>
#include <set>
#include <boost/graph/connected_components.hpp>

vector<Vpin> RoutingDB::getVpins(const Layout &layout, int splitLayer,
		bool twoCutNetsOnly, bool includeFloatingVpins, bool excludeNI) const { // splitLayer: 0-based
	vector<Vpin> vpins;
	using namespace boost;
	int totalVpin = 0;
	cout << "Splitting... " << endl;
	for (size_t gnetID = 0; gnetID < _gnets.size(); ++gnetID) {
		auto &gnet = _gnets[gnetID];
		Graph routingTree;
		for (auto &gWire : gnet._gWires) {
			Vertex v = add_vertex(routingTree);
			routingTree[v].x = gWire._x;
			routingTree[v].y = gWire._y;
			routingTree[v].z = gWire._z;
			routingTree[v].realPinId = gWire._realPinId;
			routingTree[v].isPin = (!excludeNI || gWire._z == 0) && (gWire._realPinId >= 0);
			routingTree[v].isRoot = (gWire._pWireId == -1
					&& gWire._realPinId >= 0);
		}
		for (size_t i = 0; i < gnet._gWires.size(); i++) {
			auto &gWire = gnet._gWires[i];
			if (gWire._pWireId >= 0
					&& !(gWire._z > splitLayer
							&& gnet._gWires[gWire._pWireId]._z > splitLayer)) {
				add_edge(vertex(gWire._pWireId, routingTree),
						vertex(i, routingTree), routingTree); // only connect if lower than or on splitLayer
			}
		}
		int vpCount = 0;
		EdgeIter e, eend;
		for (tie(e, eend) = edges(routingTree); e != eend; ++e) { // for each vpin
			if (routingTree[e->m_source].z > splitLayer
					|| routingTree[e->m_target].z > splitLayer) {
				routingTree[*e].isVpin = true;
				++vpCount;
				++totalVpin;
			}
		}
		if (twoCutNetsOnly && vpCount != 2)
			continue;
		int vpCountBase = totalVpin - vpCount;

		vpCount = 0;
		for (tie(e, eend) = edges(routingTree); e != eend; ++e) { // for each vpin
			if (routingTree[*e].isVpin) {
				Vpin vp;
				vp.vPinID = vpCountBase + vpCount;
				vp.gnetID = gnetID;
				vp.xCoord = routingTree[e->m_source].x;
				vp.yCoord = routingTree[e->m_source].y;
				vp.zCoord = splitLayer;
				std::vector<int> c(num_vertices(routingTree));
				connected_components(routingTree, &c[0]);
				VertexIter v, vend;
				EdgeIter e2, e2end;
				for (tie(e2, e2end) = edges(routingTree); e2 != e2end; ++e2) {
					if (c[e2->m_source] == c[e->m_source]) {
						int x1 = routingTree[e2->m_source].x;
						int y1 = routingTree[e2->m_source].y;
						int z1 = routingTree[e2->m_source].z;
						int x2 = routingTree[e2->m_target].x;
						int y2 = routingTree[e2->m_target].y;
						int z2 = routingTree[e2->m_target].z;
						if (x1 != x2) {
							assert(y1 == y2);
							assert(z1 == z2);
							for (int x = min(x1, x2); x <= max(x1, x2); ++x) {
								vp.gnetGrids.insert(Gcell(x, y1, z1));
							}
                            vp.routes.push_back(make_tuple(x1, y1, z1, x2, y2, z2));
						} else if (y1 != y2) {
							assert(x1 == x2);
							assert(z1 == z2);
							for (int y = min(y1, y2); y <= max(y1, y2); ++y) {
								vp.gnetGrids.insert(Gcell(x1, y, z1));
							}
                            vp.routes.push_back(make_tuple(x1, y1, z1, x2, y2, z2));
						} else if (z1 != z2) {
							assert(x1 == x2);
							assert(y1 == y2);
							for (int z = min(z1, z2); z <= max(z1, z2); ++z) {
								vp.gnetGrids.insert(Gcell(x1, y1, z));
							}
                            vp.routes.push_back(make_tuple(x1, y1, z1, x2, y2, z2));
						}
					}
				}
				for (tie(v, vend) = vertices(routingTree); v != vend; ++v) {
					if (c[*v] == c[e->m_source]) {
						vp.gnetVertices.insert(
								Gcell(routingTree[*v].x, routingTree[*v].y,
										routingTree[*v].z));
						vp.gnetGrids.insert(
								Gcell(routingTree[*v].x, routingTree[*v].y,
										routingTree[*v].z));
						if (routingTree[*v].isRoot)
							vp.hasOriginalRoot = true;
					}

					if (c[*v] == c[e->m_source]
							&& routingTree[*v].isPin) {
						Gcell gcell = Gcell(routingTree[*v].x,
								routingTree[*v].y, routingTree[*v].z);
						// find pin type
						// find pin node
						Net net = gnet._net;
						assert(net._netPins.size() == net._netPinTypes.size());
						assert(
								net._netPins.size() == net._netPinNodeIDs.size());
						for (size_t i = 0; i < net._netPins.size(); ++i) {
							if (layout.getGcell(net._netPins[i]) == gcell) {
								vp.pinNodeIDs.push_back(net._netPinNodeIDs[i]);
								vp.pins.push_back(net._netPins[i]);
								vp.pinTypes.push_back(net._netPinTypes[i]);
								auto &the_node =
										layout._nodes[net._netPinNodeIDs[i]];
								if (the_node._isTerm
										&& the_node._numInputs == 1
										&& the_node._numOutputs == 0) { // PI
									assert(vp.pinTypes.back() == CI);
									vp.pinTypes.back() = PI;
								} /*else if (the_node._isTerm
										&& the_node._numInputs == 0
										&& the_node._numOutputs == 1) { // PO
									assert(vp.pinTypes.back() == CO);
									vp.pinTypes.back() = PO;
								}*/
								vp.cellAreas.push_back(
										layout._nodes[net._netPinNodeIDs[i]]._height
												* layout._nodes[net._netPinNodeIDs[i]]._width);
							}
						}
					}
				}
				EdgeIter ewl, ewlend;
				int wl = 0;
				for (tie(ewl, ewlend) = edges(routingTree); ewl != ewlend;
						++ewl) {
					if (c[ewl->m_source] == c[e->m_source]
							&& c[ewl->m_target] == c[e->m_source]) {
						wl += Gcell(routingTree[ewl->m_source].x,
								routingTree[ewl->m_source].y,
								routingTree[ewl->m_source].z)
								- Gcell(routingTree[ewl->m_target].x,
										routingTree[ewl->m_target].y,
										routingTree[ewl->m_target].z);
					}
				}
				if (includeFloatingVpins || vp.pins.size() > 0) {
					vpCount++;
					vp.wlToL1 = wl;
					vpins.push_back(vp);
				}
			}
		}
		if (twoCutNetsOnly && vpCount != 2) {
			while (vpCount--) {
				vpins.pop_back();
			}
		}
		// Find matching Vpin
		for (int i = 1; i <= vpCount; ++i) {
			for (int j = 1; j <= vpCount; ++j) {
				if (vpins[vpins.size() - i].vPinID
						!= vpins[vpins.size() - j].vPinID) {
					vpins[vpins.size() - i].matchingVpinIdx = vpins.size() - j;
					break;
				}
			}
		}
	}

	cout << "# Vpins: " << vpins.size() << endl;
	return vpins;
}


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/value_types.hpp>
#include <mapnik/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/geometry_correct.hpp>

// boost
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
#include <mapnik/mapped_memory_cache.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
#pragma GCC diagnostic pop
#endif

// ogr
#include "ogr_index_featureset.hpp"
#include "ogr_converter.hpp"
#include "ogr_index.hpp"

#include <gdal_version.h>

using mapnik::query;
using mapnik::box2d;
using mapnik::feature_ptr;
using mapnik::geometry_utils;
using mapnik::transcoder;
using mapnik::feature_factory;

template <typename filterT>
ogr_index_featureset<filterT>::ogr_index_featureset(mapnik::context_ptr const & ctx,
                                                    OGRLayer & layer,
                                                    filterT const& filter,
                                                    std::string const& index_file,
                                                    std::string const& encoding)
    : ctx_(ctx),
      layer_(layer),
      layerdef_(layer.GetLayerDefn()),
      filter_(filter),
      tr_(new transcoder(encoding)),
      fidcolumn_(layer_.GetFIDColumn()),
      feature_envelope_()
{

#if defined(MAPNIK_MEMORY_MAPPED_FILE)
    boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(index_file, true);
    if (memory)
    {
        boost::interprocess::ibufferstream file(static_cast<char*>((*memory)->get_address()),(*memory)->get_size());
        ogr_index<filterT,boost::interprocess::ibufferstream >::query(filter,file,ids_);
    }
#else
  #if defined (WINDOWS)
      std::ifstream file(mapnik::utf8_to_utf16(index_file), std::ios::in | std::ios::binary);
  #else
      std::ifstream file(index_file.c_str(), std::ios::in | std::ios::binary);
  #endif
      ogr_index<filterT,std::ifstream>::query(filter,file,ids_);
#endif

    std::sort(ids_.begin(),ids_.end());

    MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Query size=" << ids_.size();

    itr_ = ids_.begin();

    // reset reading
    layer_.ResetReading();
}

template <typename filterT>
ogr_index_featureset<filterT>::~ogr_index_featureset() {}

template <typename filterT>
feature_ptr ogr_index_featureset<filterT>::next()
{
    while (itr_ != ids_.end())
    {
        int pos = *itr_++;
        layer_.SetNextByIndex (pos);

        OGRFeature *poFeature = layer_.GetNextFeature();
        if (poFeature == nullptr)
        {
            return feature_ptr();
        }

        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom=poFeature->GetGeometryRef();
        if (geom && !geom->IsEmpty())
        {
            geom->getEnvelope(&feature_envelope_);
            if (!filter_.pass(mapnik::box2d<double>(feature_envelope_.MinX,feature_envelope_.MinY,
                                            feature_envelope_.MaxX,feature_envelope_.MaxY))) continue;
            auto geom_corrected = ogr_converter::convert_geometry(geom);
            mapnik::geometry::correct(geom_corrected);
            feature->set_geometry(std::move(geom_corrected));
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        int fld_count = layerdef_->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = layerdef_->GetFieldDefn (i);
            OGRFieldType type_oid = fld->GetType ();
            std::string fld_name = fld->GetNameRef ();

            switch (type_oid)
            {
            case OFTInteger:
            {
                feature->put<mapnik::value_integer>(fld_name,poFeature->GetFieldAsInteger (i));
                break;
            }
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64:
            {
                feature->put<mapnik::value_integer>( fld_name, poFeature->GetFieldAsInteger64(i));
                break;
            }
#endif

            case OFTReal:
            {
                feature->put(fld_name,poFeature->GetFieldAsDouble (i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                feature->put(fld_name,tr_->transcode(poFeature->GetFieldAsString (i)));
                break;
            }

            case OFTIntegerList:
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64List:
#endif
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    return feature_ptr();
}

template class ogr_index_featureset<mapnik::filter_in_box>;
template class ogr_index_featureset<mapnik::filter_at_point>;


text:
// Boost seed_rng.hpp header file  ----------------------------------------------//

// Copyright 2007 Andy Tompkins.
// 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)

// Revision History
//  09 Nov 2007 - Initial Revision
//  25 Feb 2008 - moved to namespace boost::uuids::detail
//  28 Nov 2009 - disabled deprecated warnings for MSVC

// seed_rng models a UniformRandomNumberGenerator (see Boost.Random).
// Random number generators are hard to seed well.  This is intended to provide
// good seed values for random number generators.
// It creates random numbers from a sha1 hash of data from a variary of sources,
// all of which are standard function calls.  It produces random numbers slowly.
// Peter Dimov provided the details of sha1_random_digest_().
// see http://archives.free.net.ph/message/20070507.175609.4c4f503a.en.html

#ifndef BOOST_UUID_SEED_RNG_HPP
#define BOOST_UUID_SEED_RNG_HPP

#include <boost/config.hpp>
#include <cstring> // for memcpy
#include <limits>
#include <ctime> // for time_t, time, clock_t, clock
#include <cstdlib> // for rand
#include <cstdio> // for FILE, fopen, fread, fclose
#include <boost/uuid/sha1.hpp>
//#include <boost/nondet_random.hpp> //forward declare boost::random_device

// can't use boost::generator_iterator since boost::random number seed(Iter&, Iter)
// functions need a last iterator
//#include <boost/generator_iterator.hpp>
# include <boost/iterator/iterator_facade.hpp>

#if defined(_MSC_VER)
#pragma warning(push) // Save warning settings.
#pragma warning(disable : 4996) // Disable deprecated std::fopen
#endif

#ifdef BOOST_NO_STDC_NAMESPACE
namespace std {
    using ::memcpy;
    using ::time_t;
    using ::time;
    using ::clock_t;
    using ::clock;
    using ::rand;
    using ::FILE;
    using ::fopen;
    using ::fread;
    using ::fclose;
} //namespace std
#endif

// forward declare random number generators
namespace boost {
class random_device;
} //namespace boost

namespace boost {
namespace uuids {
namespace detail {

// should this be part of Boost.Random?
class seed_rng
{
public:
    typedef unsigned int result_type;
    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
    //BOOST_STATIC_CONSTANT(unsigned int, min_value = 0);
    //BOOST_STATIC_CONSTANT(unsigned int, max_value = UINT_MAX);

public:
    // note: rd_ intentionally left uninitialized
    seed_rng()
        : rd_index_(5)
        , random_(std::fopen( "/dev/urandom", "rb" ))
    {}

    ~seed_rng()
    {
        if (random_) {
            std::fclose(random_);
        }
    }

    result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const
    {
        return (std::numeric_limits<result_type>::min)();
    }
    result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const
    {
        return (std::numeric_limits<result_type>::max)();
    }

    result_type operator()()
    {
        if (rd_index_ >= 5) {
            //get new digest
            sha1_random_digest_();

            rd_index_ = 0;
        }

        return rd_[rd_index_++];
    }

private:
    static unsigned int * sha1_random_digest_state_()
    {
        // intentionally left uninitialized
        static unsigned int state[ 5 ];
        return state;
    }

    void sha1_random_digest_()
    {
        boost::uuids::detail::sha1 sha;

        unsigned int * ps = sha1_random_digest_state_();

        unsigned int state[ 5 ];
        std::memcpy( state, ps, sizeof( state ) ); // harmless data race

        sha.process_bytes( (unsigned char const*)state, sizeof( state ) );
        sha.process_bytes( (unsigned char const*)&ps, sizeof( ps ) );

        {
            std::time_t tm = std::time( 0 );
            sha.process_bytes( (unsigned char const*)&tm, sizeof( tm ) );
        }

        {
            std::clock_t ck = std::clock();
            sha.process_bytes( (unsigned char const*)&ck, sizeof( ck ) );
        }

        {
            unsigned int rn[] = { std::rand(), std::rand(), std::rand() };
            sha.process_bytes( (unsigned char const*)rn, sizeof( rn ) );
        }

        {
            // intentionally left uninitialized
            unsigned char buffer[ 20 ];

            if(random_)
            {
                std::fread( buffer, 1, 20, random_ );
            }

            // using an uninitialized buffer[] if fopen fails
            // intentional, we rely on its contents being random
            sha.process_bytes( buffer, sizeof( buffer ) );
        }

        {
            // *p is intentionally left uninitialized
            unsigned int * p = new unsigned int;

            sha.process_bytes( (unsigned char const*)p, sizeof( *p ) );
            sha.process_bytes( (unsigned char const*)&p, sizeof( p ) );

            delete p;
        }

        sha.process_bytes( (unsigned char const*)rd_, sizeof( rd_ ) );

        unsigned int digest[ 5 ];
        sha.get_digest( digest );

        for( int i = 0; i < 5; ++i )
        {
            // harmless data race
            ps[ i ] ^= digest[ i ];
            rd_[ i ] ^= digest[ i ];
        }
    }

private:
    unsigned int rd_[5];
    int rd_index_;
    std::FILE * random_;

private: // make seed_rng noncopyable
    seed_rng(seed_rng const&);
    seed_rng& operator=(seed_rng const&);
};

// almost a copy of boost::generator_iterator
// but default constructor sets m_g to NULL
template <class Generator>
class generator_iterator
  : public iterator_facade<
        generator_iterator<Generator>
      , typename Generator::result_type
      , single_pass_traversal_tag
      , typename Generator::result_type const&
    >
{
    typedef iterator_facade<
        generator_iterator<Generator>
      , typename Generator::result_type
      , single_pass_traversal_tag
      , typename Generator::result_type const&
    > super_t;

 public:
    generator_iterator() : m_g(NULL) {}
    generator_iterator(Generator* g) : m_g(g), m_value((*m_g)()) {}

    void increment()
    {
        m_value = (*m_g)();
    }

    const typename Generator::result_type&
    dereference() const
    {
        return m_value;
    }

    bool equal(generator_iterator const& y) const
    {
        return this->m_g == y.m_g && this->m_value == y.m_value;
    }

 private:
    Generator* m_g;
    typename Generator::result_type m_value;
};

// seed() seeds a random number generator with good seed values

template <typename UniformRandomNumberGenerator>
inline void seed(UniformRandomNumberGenerator& rng)
{
    seed_rng seed_gen;
    generator_iterator<seed_rng> begin(&seed_gen);
    generator_iterator<seed_rng> end;
    rng.seed(begin, end);
}

// random_device does not / can not be seeded
template <>
inline void seed<boost::random_device>(boost::random_device&) {}

// random_device does not / can not be seeded
template <>
inline void seed<seed_rng>(seed_rng&) {}

}}} //namespace boost::uuids::detail

#if defined(_MSC_VER)
#pragma warning(pop) // Restore warnings to previous state.
#endif

#endif

ext: hpp

max_stars_repo_name: zigaosolin/Raytracer

max_issues_repo_name: zigaosolin/Raytracer

max_forks_repo_name: zigaosolin/Raytracer


text:
#pragma once

#include "terminalpp/ansi/control_sequence.hpp"
#include "terminalpp/ansi/mouse.hpp"
#include "terminalpp/virtual_key.hpp"
#include <boost/variant.hpp>

namespace terminalpp {

using token = boost::variant<
    terminalpp::virtual_key,
    terminalpp::ansi::mouse::report,
    terminalpp::ansi::control_sequence
>;

}

max_stars_repo_name: ruszkait/terminalpp

max_issues_repo_name: p-ranav/terminalpp

max_forks_repo_name: p-ranav/terminalpp


text:
/* ----------------------------------------------------------------------------
** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved.
**
** ReflectionParser.cpp
** --------------------------------------------------------------------------*/

#include "Precompiled.h"

#include "ReflectionParser.h"
#include "Version.h"

#include "LanguageTypes/Class.h"
#include "LanguageTypes/External.h"
#include "LanguageTypes/Global.h"
#include "LanguageTypes/Function.h"
#include "LanguageTypes/Enum.h"

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

#include <fstream>
#include <vector>

#define RECURSE_NAMESPACES(kind, cursor, method, ns) \
    if (kind == CXCursor_Namespace)                  \
    {                                                \
        auto displayName = cursor.GetDisplayName( ); \
        if (!displayName.empty( ))                   \
        {                                            \
            ns.emplace_back( displayName );          \
            method( cursor, ns );                    \
            ns.pop_back( );                          \
        }                                            \
    }                                                \

#define TRY_ADD_LANGUAGE_TYPE(handle, container)                \
    if (handle->ShouldCompile( ))                               \
    {                                                           \
        auto file = handle->GetSourceFile( );                   \
        m_moduleFiles[ file ].container.emplace_back( handle ); \
    }                                                           \

#define COMPILE_TYPE_TEMPLATES(data, listName, container)   \
    {                                                       \
        TemplateData typeData { TemplateData::Type::List }; \
        for (auto &handle : container)                      \
            typeData << handle->CompileTemplate( this );    \
        data[ listName ] = typeData;                        \
    }                                                       \

namespace
{
    const boost::regex kSpecialCharsRegex( "[^a-zA-Z0-9]+" );
}

ReflectionParser::ReflectionParser(const ReflectionOptions &options)
    : m_options( options )
    , m_index( nullptr )
    , m_translationUnit( nullptr )
    , m_moduleFileHeaderTemplate( "" )
    , m_moduleFileSourceTemplate( "" )
{
    // replace special characters in target name with underscores
    m_options.targetName = boost::regex_replace(
        m_options.targetName,
        kSpecialCharsRegex,
        "_"
    );
}

ReflectionParser::~ReflectionParser(void)
{
    if (m_translationUnit)
        clang_disposeTranslationUnit( m_translationUnit );

    if (m_index)
        clang_disposeIndex( m_index );
}

void ReflectionParser::Parse(void)
{
    m_index = clang_createIndex( true, m_options.displayDiagnostics );

    std::vector<const char *> arguments;

#if defined(SYSTEM_INCLUDE_DIRECTORY)

    arguments.emplace_back( "-I" SYSTEM_INCLUDE_DIRECTORY );

#endif

    for (auto &argument : m_options.arguments)
        arguments.emplace_back( argument.c_str( ) );

    if (m_options.displayDiagnostics)
    {
        for (auto *argument : arguments)
            std::cout << argument << std::endl;
    }

    m_translationUnit = clang_createTranslationUnitFromSourceFile(
        m_index,
        m_options.inputSourceFile.c_str( ),
        static_cast<int>( arguments.size( ) ),
        arguments.data( ),
        0,
        nullptr
    );

    auto cursor = clang_getTranslationUnitCursor( m_translationUnit );

    Namespace tempNamespace;

    buildClasses( cursor, tempNamespace );

    tempNamespace.clear( );

    buildGlobals( cursor, tempNamespace );

    tempNamespace.clear( );

    buildGlobalFunctions( cursor, tempNamespace );

    tempNamespace.clear( );

    buildEnums( cursor, tempNamespace );
}

void ReflectionParser::GenerateFiles(void)
{
    fs::path sourceRootDirectory( m_options.sourceRoot );
    fs::path outputFileDirectory( m_options.outputModuleFileDirectory );

    m_moduleFileHeaderTemplate = LoadTemplate( kTemplateModuleFileHeader );

    if (!m_moduleFileHeaderTemplate.isValid( ))
    {
        std::stringstream error;

        error << "Unable to compile module file header template." << std::endl;
        error << m_moduleFileHeaderTemplate.errorMessage( );

        throw std::runtime_error( error.str( ) );
    }

    m_moduleFileSourceTemplate = LoadTemplate( kTemplateModuleFileSource );

    if (!m_moduleFileSourceTemplate.isValid( ))
    {
        std::stringstream error;

        error << "Unable to compile module file source template." << std::endl;
        error << m_moduleFileSourceTemplate.errorMessage( );

        throw std::runtime_error( error.str( ) );
    }

    TemplateData moduleFilesData { TemplateData::Type::List };

    fs::path metaCacheFileName = m_options.outputModuleFileDirectory;

    metaCacheFileName /= ".meta-cache";

    auto metaCacheFileExists = exists( metaCacheFileName );

    std::string moduleFileCache;

    for (auto &file : m_moduleFiles)
    {
        fs::path filePath( file.first );

        // path relative to the source root
        auto relativeDir = utils::MakeRelativePath( sourceRootDirectory, filePath )
            .replace_extension( "" ).string( );

        if (relativeDir.find_first_of( ".." ) != std::string::npos)
            continue;

        auto outputFile = outputFileDirectory / relativeDir;
        auto outputFileHeader = change_extension( outputFile, "Generated.h" );
        auto outputFileSource = change_extension( outputFile, "Generated.cpp" );

		if (!exists(outputFileHeader) ||
			!exists(outputFileSource))
		{
			continue;
		}

        // module file name
        file.second.name = boost::regex_replace(
            relativeDir,
            kSpecialCharsRegex,
            "_"
        );

        moduleFileCache += file.second.name + "\n";

        TemplateData moduleFileData { TemplateData::Type::Object };

        moduleFileData[ "name" ] = file.second.name;
        moduleFileData[ "header" ] = outputFileHeader.string( );

        moduleFilesData << moduleFileData;

        // if the generated file header/source doesn't exist, we need to regenerate
        if (m_options.forceRebuild ||
            !metaCacheFileExists ||
            !exists( outputFileHeader ) ||
            !exists( outputFileSource )
        )
        {
            generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second );

            continue;
        }

        auto lastSourceWrite = last_write_time( filePath );
        auto lastGeneratedHeaderWrite = last_write_time( outputFileHeader );
        auto lastGeneratedSourceWrite = last_write_time( outputFileSource );

        // if the generated file is older than the source file, we need to regenerate
        if (lastSourceWrite > lastGeneratedHeaderWrite || lastSourceWrite > lastGeneratedSourceWrite)
            generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second );
    }

    if (!m_options.forceRebuild && metaCacheFileExists)
    {
        std::ifstream cacheFile( metaCacheFileName.string( ) );

        std::istreambuf_iterator<char> cacheFileBegin( cacheFile );
        std::istreambuf_iterator<char> cacheFileEnd( nullptr );

        // the cache is the same, so we don't need to write the source files
        if (utils::RangeEqual(
                moduleFileCache.begin( ), moduleFileCache.end( ),
                cacheFileBegin, cacheFileEnd
            ))
        {
            return;
        }
    }

    // update the cache
    utils::WriteText(
        metaCacheFileName.string( ),
        moduleFileCache
    );

    // module source file
    {
        auto sourceTemplate = LoadTemplate( kTemplateModuleSource );

        if (!sourceTemplate.isValid( ))
        {
            std::stringstream error;

            error << "Unable to compile module source template." << std::endl;
            error << sourceTemplate.errorMessage( );

            throw std::runtime_error( error.str( ).c_str( ) );
        }

        TemplateData sourceData { TemplateData::Type::Object };

        addGlobalTemplateData( sourceData );

        sourceData[ "moduleFile" ] = moduleFilesData;

        COMPILE_TYPE_TEMPLATES( sourceData, "external", m_externals );

        fs::path sourcePath( m_options.outputModuleSource );

        fs::create_directory( sourcePath.parent_path( ) );

        utils::WriteText(
            sourcePath.string( ),
            sourceTemplate.render( sourceData )
        );
    }
}

MustacheTemplate ReflectionParser::LoadTemplate(const std::string &name) const
{
    auto path = fs::path( m_options.templateDirectory );

    path.append( name );

    try
    {
        std::string text;

        utils::LoadText( path.string( ), text );

        return text;
    }
    catch (std::exception &e)
    {
        std::stringstream error;

        error << "Unable to load template ";
        error << name << "." << std::endl;
        error << "-- " << e.what( );

        utils::FatalError( error.str( ) );
    }

    // this will never happen
    return { "" };
}

TemplateData::PartialType ReflectionParser::LoadTemplatePartial(
    const std::string &name
) const
{
    auto path =
        fs::path( m_options.templateDirectory ).append( name ).string( );

    try
    {
        auto partialLoader = [=]()
        {
            auto cache = m_templatePartialCache.find( path );

            if (cache == m_templatePartialCache.end( ))
            {
                std::string text;

                utils::LoadText( path, text );

                m_templatePartialCache[ path ] = text;

                return text;
            }

            return cache->second;
        };

        return partialLoader;
    }
    catch(std::exception &e)
    {
        std::stringstream error;

        error << "Unable to load template partial ";
        error << name << "." << std::endl;
        error << "-- " << e.what( );

        utils::FatalError( error.str( ) );
    }

    // this will never happen
    return nullptr;
}

void ReflectionParser::buildClasses(
    const Cursor &cursor,
    Namespace &currentNamespace
)
{
    for (auto &child : cursor.GetChildren( ))
    {
        auto kind = child.GetKind( );

#if defined TEIGHA_API_SETTINGS
		auto fileName = child.GetSourceFileName();
		if (!fileName.empty() && std::find(m_options.ignoreList.begin(), m_options.ignoreList.end(), fileName) != m_options.ignoreList.end())
		{
			continue;
		}
#endif

        // actual definition and a class or struct
        if (child.IsDefinition( ) &&
            (kind == CXCursor_ClassDecl || kind == CXCursor_StructDecl)
        )
        {
#if defined TEIGHA_API_SETTINGS
            //skip structs that represent teigha enums
			if (kind == CXCursor_StructDecl)
			{
				std::string prefix = "IsEnum";
				bool isEnum = strncmp(child.GetDisplayName().c_str(), prefix.c_str(), prefix.size()) == 0;
				if (isEnum)
					continue;
			}
#endif

            auto klass = std::make_shared<Class>( child, currentNamespace );

            TRY_ADD_LANGUAGE_TYPE( klass, classes );
        }
        else if (kind == CXCursor_TypedefDecl)
        {
            auto displayName = child.GetDisplayName( );

            // external declaration; they're always compiled, but only registered
            if (boost::starts_with( displayName, kMetaExternalTypeDefName ))
            {
                m_externals.emplace_back(
                    std::make_shared<External>( child.GetTypedefType( ).GetDeclaration( ) )
                );
            }
        }

        RECURSE_NAMESPACES( kind, child, buildClasses, currentNamespace );
    }
}

void ReflectionParser::buildGlobals(
    const Cursor &cursor,
    Namespace &currentNamespace
)
{
    auto children = cursor.GetChildren( );

    for (auto &child : children)
    {
        // skip static globals (hidden)
        if (child.GetStorageClass( ) == CX_SC_Static)
            continue;

        auto kind = child.GetKind( );

        // variable declaration, which is global
        if (kind == CXCursor_VarDecl)
        {
            auto global = std::make_shared<Global>( child, currentNamespace );

            TRY_ADD_LANGUAGE_TYPE( global, globals );
        }

        RECURSE_NAMESPACES( kind, child, buildGlobals, currentNamespace );
    }
}

void ReflectionParser::buildGlobalFunctions(
    const Cursor &cursor,
    Namespace &currentNamespace
)
{
    for (auto &child : cursor.GetChildren( ))
    {
        // skip static globals (hidden)
        if (child.GetStorageClass( ) == CX_SC_Static)
            continue;

        auto kind = child.GetKind( );

        // function declaration, which is global
        if (kind == CXCursor_FunctionDecl)
        {
            auto function = std::make_shared<Function>( child, currentNamespace );

            TRY_ADD_LANGUAGE_TYPE( function, globalFunctions );
        }

        RECURSE_NAMESPACES(
            kind,
            child,
            buildGlobalFunctions,
            currentNamespace
        );
    }
}

void ReflectionParser::buildEnums(
    const Cursor &cursor,
    Namespace &currentNamespace
)
{
    for (auto &child : cursor.GetChildren( ))
    {
        auto kind = child.GetKind( );

        // actual definition and an enum
        if (child.IsDefinition( ) && kind == CXCursor_EnumDecl)
        {
            // anonymous enum if the underlying type display name contains this
            if (child.GetType( ).GetDisplayName( ).find( "anonymous enum at" )
                != std::string::npos)
            {
                // anonymous enums are just loaded as
                // globals with each of their values
                for (auto &enumChild : child.GetChildren( ))
                {
                    if (enumChild.GetKind( ) == CXCursor_EnumConstantDecl)
                    {
                        auto global = std::make_shared<Global>( enumChild, currentNamespace, nullptr );

                        TRY_ADD_LANGUAGE_TYPE( global, globals );
                    }
                }
            }
            else
            {
                auto enewm = std::make_shared<Enum>( child, currentNamespace );

                TRY_ADD_LANGUAGE_TYPE( enewm, enums );
            }
        }

        RECURSE_NAMESPACES( kind, child, buildEnums, currentNamespace );
    }
}

void ReflectionParser::addGlobalTemplateData(TemplateData &data)
{
    data[ "version" ] = kMetaGeneratorVersion;
    data[ "targetName" ] = m_options.targetName;
    data[ "inputSourceFile" ] = m_options.inputSourceFile;
    data[ "moduleHeaderFile" ] = m_options.moduleHeaderFile;
    data[ "outputModuleSourceFile" ] = m_options.outputModuleSource;

    data[ "usingPrecompiledHeader" ] =
        utils::TemplateBool( !m_options.precompiledHeader.empty( ) );

    data[ "precompiledHeader" ] = m_options.precompiledHeader;
}

void ReflectionParser::generateModuleFile(
    const fs::path &fileHeader,
    const fs::path &fileSource,
    const std::string &sourceHeader,
    const ModuleFile &file
)
{
    // header file
    {
        TemplateData headerData { TemplateData::Type::Object };

        addGlobalTemplateData( headerData );

        headerData[ "moduleFileName" ] = file.name;

        fs::create_directory( fileHeader.parent_path( ) );

        utils::WriteText(
            fileHeader.string( ),
            m_moduleFileHeaderTemplate.render( headerData )
        );
    }

    // source file
    {
        TemplateData sourceData { TemplateData::Type::Object };

        addGlobalTemplateData( sourceData );

        sourceData[ "moduleFileName" ] = file.name;
        sourceData[ "moduleFileSourceHeader" ] = sourceHeader;
        sourceData[ "moduleFileHeader" ] = fileHeader.string( );

        COMPILE_TYPE_TEMPLATES( sourceData, "class", file.classes );
        COMPILE_TYPE_TEMPLATES( sourceData, "global", file.globals );
        COMPILE_TYPE_TEMPLATES( sourceData, "globalFunction", file.globalFunctions );
        COMPILE_TYPE_TEMPLATES( sourceData, "enum", file.enums );

        fs::create_directory( fileSource.parent_path( ) );

        utils::WriteText(
            fileSource.string( ),
            m_moduleFileSourceTemplate.render( sourceData )
        );
    }
}

max_stars_repo_name: JoinCAD/CPP-Reflection

max_issues_repo_name: JoinCAD/CPP-Reflection

max_forks_repo_name: JoinCAD/CPP-Reflection


text:
#ifndef SERVICE_ENGINE_HPP
#define SERVICE_ENGINE_HPP

#include <libcommon/libcommon_config.h>
#include <boost/aligned_storage.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <vector>

namespace FBi
{

class ServiceContext
{
public:
	boost::asio::io_service::work* work;
	boost::thread* work_thread;
	boost::asio::io_service* io_service;
};

class LIBCOMMON_DECL ServiceEngine
{
public:
	explicit ServiceEngine(int num = 1);
	~ServiceEngine();

	boost::asio::io_service& GetIOService();
	void StartService();
	void StopService();
	bool IsRunning();

private:
	int RR_index_;
	boost::mutex mutex_;
	std::vector<ServiceContext> context_vec_;
	bool ready_;
};

// Class to manage the memory to be used for handler-based custom allocation.
// It contains a single block of memory which may be returned for allocation
// requests.
//Single Block Allocator
typedef boost::aligned_storage<1024> sb_allocator;

// Wrapper class template for handler objects to allow handler memory
// allocation to be customised. Calls to operator() are forwarded to the
// encapsulated handler.
template <typename Handler>
class custom_alloc_handler
{
public:
	custom_alloc_handler(sb_allocator& a, BOOST_ASIO_MOVE_ARG(Handler) h)
		: allocator_(a),
		handler_(BOOST_ASIO_MOVE_CAST(Handler)(h))
	{
	}
#if defined(BOOST_ASIO_HAS_MOVE)
	custom_alloc_handler(const custom_alloc_handler& other)
		: allocator_(other.allocator_),
		  handler_(other.handler_)
	{
	}

	custom_alloc_handler(custom_alloc_handler&& other)
		: allocator_(other.allocator_),
		  handler_(BOOST_ASIO_MOVE_CAST(Handler)(other.handler_))
	{
	}
#endif

	template <typename Arg1>
	void operator()(const Arg1& arg1)
	{
		handler_(arg1);
	}

	template <typename Arg1, typename Arg2>
	void operator()(const Arg1& arg1, const Arg2& arg2)
	{
		handler_(arg1, arg2);
	}

	friend void* asio_handler_allocate(std::size_t size,
			custom_alloc_handler<Handler>* this_handler)
	{
		assert(size < 1024);
		return this_handler->allocator_.address();
	}

	friend void asio_handler_deallocate(void* /*pointer*/, std::size_t /*size*/,
			custom_alloc_handler<Handler>* /*this_handler*/)
	{
		//this_handler->allocator_.deallocate(pointer);
	}

private:
	sb_allocator& allocator_;
	Handler handler_;
};

// Helper function to wrap a handler object to add custom allocation.
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
	sb_allocator& a, BOOST_ASIO_MOVE_ARG(Handler) h)
{
	return custom_alloc_handler<Handler>(a, BOOST_ASIO_MOVE_CAST(Handler)(h));
}

}

#endif //SERVICE_ENGINE_HPP


text:
/*

Copyright (c) 2005-2020, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TESTPDETESTCLASSES_HPP_
#define TESTPDETESTCLASSES_HPP_

#include <cxxtest/TestSuite.h>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include "ArchiveOpener.hpp"
#include "ArchiveLocationInfo.hpp"
#include "OutputFileHandler.hpp"

#include "Node.hpp"

#include "HeatEquation.hpp"
#include "HeatEquationWithElementDependentSourceTerm.hpp"
#include "NonlinearEquationPde.hpp"
#include "SimplePoissonEquation.hpp"
#include "VaryingDiffusionAndSourceTermPde.hpp"
#include "SimpleUniformSourceParabolicPde.hpp"

#include "PetscSetupAndFinalize.hpp"

class TestPdeTestClasses : public CxxTest::TestSuite
{
public:
    void TestSimplePoissonEquation()
    {
        ChastePoint<1> zero1(0);
        ChastePoint<2> zero2(0,0);
        ChastePoint<3> zero3(0,0,0);

        SimplePoissonEquation<1,1> heat_equation1;
        SimplePoissonEquation<2,2> heat_equation2;
        SimplePoissonEquation<3,3> heat_equation3;

        // Diffusion matrices should be equal to identity
        c_matrix<double,1,1> diff1 = heat_equation1.ComputeDiffusionTerm(zero1);
        c_matrix<double,2,2> diff2 = heat_equation2.ComputeDiffusionTerm(zero2);
        c_matrix<double,3,3> diff3 = heat_equation3.ComputeDiffusionTerm(zero3);

        TS_ASSERT_DELTA(diff1(0,0),1,1e-12);

        TS_ASSERT_DELTA(diff2(0,0),1,1e-12);
        TS_ASSERT_DELTA(diff2(1,1),1,1e-12);
        TS_ASSERT_DELTA(diff2(0,1),0,1e-12);

        TS_ASSERT_DELTA(diff3(0,0),1,1e-12);
        TS_ASSERT_DELTA(diff3(1,1),1,1e-12);
        TS_ASSERT_DELTA(diff3(2,2),1,1e-12);
        TS_ASSERT_DELTA(diff3(0,1),0,1e-12);
        TS_ASSERT_DELTA(diff3(0,2),0,1e-12);
        TS_ASSERT_DELTA(diff3(1,2),0,1e-12);

        Node<2> zero(0);
        SimplePoissonEquation<2,2> heat_equation;
        TS_ASSERT_DELTA(heat_equation.ComputeConstantInUSourceTermAtNode(zero), 1.0, 1e-12);
    }

    void TestNonlinearEquationPde()
    {
        ChastePoint<1> zero1(0);
        ChastePoint<2> zero2(0,0);
        ChastePoint<3> zero3(0,0,0);
        double u = 2.0;

        NonlinearEquationPde<1> heat_equation1;
        NonlinearEquationPde<2> heat_equation2;
        NonlinearEquationPde<3> heat_equation3;

        TS_ASSERT_DELTA(heat_equation1.ComputeNonlinearSourceTerm(zero1,u),0.0,1e-12);
        TS_ASSERT_DELTA(heat_equation2.ComputeNonlinearSourceTerm(zero2,u),0.0,1e-12);
        TS_ASSERT_DELTA(heat_equation3.ComputeNonlinearSourceTerm(zero3,u),0.0,1e-12);

        // Diffusion matrices should be equal to identity * u;
        c_matrix<double, 1, 1> diff1 = heat_equation1.ComputeDiffusionTerm(zero1,u);
        c_matrix<double, 2, 2> diff2 = heat_equation2.ComputeDiffusionTerm(zero2,u);
        c_matrix<double, 3, 3> diff3 = heat_equation3.ComputeDiffusionTerm(zero3,u);

        TS_ASSERT_DELTA(diff1(0,0),u,1e-12);

        TS_ASSERT_DELTA(diff2(0,0),u,1e-12);
        TS_ASSERT_DELTA(diff2(1,1),u,1e-12);
        TS_ASSERT_DELTA(diff2(0,1),0,1e-12);

        TS_ASSERT_DELTA(diff3(0,0),u,1e-12);
        TS_ASSERT_DELTA(diff3(1,1),u,1e-12);
        TS_ASSERT_DELTA(diff3(2,2),u,1e-12);
        TS_ASSERT_DELTA(diff3(0,1),0,1e-12);
        TS_ASSERT_DELTA(diff3(0,2),0,1e-12);
        TS_ASSERT_DELTA(diff3(1,2),0,1e-12);
    }

    void TestHeatEquation()
    {
        ChastePoint<1> zero1(0);
        ChastePoint<2> zero2(0,0);
        ChastePoint<3> zero3(0,0,0);
        double u = 2.0;

        HeatEquation<1> pde1;
        HeatEquation<2> pde2;
        HeatEquation<3> pde3;

        TS_ASSERT_DELTA(pde1.ComputeSourceTerm(zero1,u), 0.0, 1e-12);
        TS_ASSERT_DELTA(pde2.ComputeSourceTerm(zero2,u), 0.0, 1e-12);
        TS_ASSERT_DELTA(pde3.ComputeSourceTerm(zero3,u), 0.0, 1e-12);

        TS_ASSERT_DELTA(pde1.ComputeDuDtCoefficientFunction(zero1), 1.0, 1e-12);
        TS_ASSERT_DELTA(pde2.ComputeDuDtCoefficientFunction(zero2), 1.0, 1e-12);
        TS_ASSERT_DELTA(pde3.ComputeDuDtCoefficientFunction(zero3), 1.0, 1e-12);

        // Diffusion matrices should be equal to identity
        c_matrix<double, 1, 1> diff1 = pde1.ComputeDiffusionTerm(zero1);
        c_matrix<double, 2, 2> diff2 = pde2.ComputeDiffusionTerm(zero2);
        c_matrix<double, 3, 3> diff3 = pde3.ComputeDiffusionTerm(zero3);

        TS_ASSERT_DELTA(diff1(0,0), 1, 1e-12);

        TS_ASSERT_DELTA(diff2(0,0), 1, 1e-12);
        TS_ASSERT_DELTA(diff2(1,1), 1, 1e-12);
        TS_ASSERT_DELTA(diff2(0,1), 0, 1e-12);

        TS_ASSERT_DELTA(diff3(0,0), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(1,1), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(2,2), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(0,1), 0, 1e-12);
        TS_ASSERT_DELTA(diff3(0,2), 0, 1e-12);
        TS_ASSERT_DELTA(diff3(1,2), 0, 1e-12);

        Node<1> node(0, zero1);
        TS_ASSERT_DELTA(pde1.ComputeSourceTermAtNode(node,u), 0.0, 1e-12);
    }

    void TestHeatEquationWithElementDependentSourceTerm()
    {
        // The PDE is set to give elements with index = 0 a source of zero
        // and a source of 1 otherwise.

        std::vector<Node<1>*> one_d_nodes;
        one_d_nodes.push_back(new Node<1>(0, false, 2.0));
        one_d_nodes.push_back(new Node<1>(1, false, 2.5));
        Element<1,1> one_d_element(0u, one_d_nodes);
        ChastePoint<1> zero1(0);

        std::vector<Node<2>*> two_d_nodes;
        two_d_nodes.push_back(new Node<2>(0, false, 0.0, 0.0));
        two_d_nodes.push_back(new Node<2>(1, false, 1.0, 0.0));
        two_d_nodes.push_back(new Node<2>(2, false, 0.0, 1.0));
        Element<2,2> two_d_element(0u, two_d_nodes);
        ChastePoint<2> zero2(0,0);

        std::vector<Node<3>*> three_d_nodes;
        three_d_nodes.push_back(new Node<3>(0, false, 0.0, 0.0, 0.0));
        three_d_nodes.push_back(new Node<3>(1, false, 1.0, 0.0, 0.0));
        three_d_nodes.push_back(new Node<3>(2, false, 0.0, 1.0, 0.0));
        three_d_nodes.push_back(new Node<3>(3, false, 0.0, 0.0, 1.0));
        Element<3,3> three_d_element(0u, three_d_nodes);
        ChastePoint<3> zero3(0,0,0);
        double u = 2.0;

        HeatEquationWithElementDependentSourceTerm<1> pde1;
        HeatEquationWithElementDependentSourceTerm<2> pde2;
        HeatEquationWithElementDependentSourceTerm<3> pde3;

        TS_ASSERT_DELTA(pde1.ComputeSourceTerm(zero1, u, &one_d_element), 0.0, 1e-12);
        one_d_element.ResetIndex(1u);
        TS_ASSERT_DELTA(pde1.ComputeSourceTerm(zero1, u, &one_d_element), 1.0, 1e-12);

        TS_ASSERT_DELTA(pde2.ComputeSourceTerm(zero2, u, &two_d_element), 0.0, 1e-12);
        two_d_element.ResetIndex(1u);
        TS_ASSERT_DELTA(pde2.ComputeSourceTerm(zero2, u, &two_d_element), 1.0, 1e-12);

        TS_ASSERT_DELTA(pde3.ComputeSourceTerm(zero3, u, &three_d_element), 0.0, 1e-12);
        three_d_element.ResetIndex(1u);
        TS_ASSERT_DELTA(pde3.ComputeSourceTerm(zero3, u, &three_d_element), 1.0, 1e-12);

        TS_ASSERT_DELTA(pde1.ComputeDuDtCoefficientFunction(zero1), 1.0, 1e-12);
        TS_ASSERT_DELTA(pde2.ComputeDuDtCoefficientFunction(zero2), 1.0, 1e-12);
        TS_ASSERT_DELTA(pde3.ComputeDuDtCoefficientFunction(zero3), 1.0, 1e-12);

        // Diffusion matrices should be equal to identity
        c_matrix<double, 1, 1> diff1 = pde1.ComputeDiffusionTerm(zero1);
        c_matrix<double, 2, 2> diff2 = pde2.ComputeDiffusionTerm(zero2);
        c_matrix<double, 3, 3> diff3 = pde3.ComputeDiffusionTerm(zero3);

        TS_ASSERT_DELTA(diff1(0,0), 1, 1e-12);

        TS_ASSERT_DELTA(diff2(0,0), 1, 1e-12);
        TS_ASSERT_DELTA(diff2(1,1), 1, 1e-12);
        TS_ASSERT_DELTA(diff2(0,1), 0, 1e-12);

        TS_ASSERT_DELTA(diff3(0,0), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(1,1), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(2,2), 1, 1e-12);
        TS_ASSERT_DELTA(diff3(0,1), 0, 1e-12);
        TS_ASSERT_DELTA(diff3(0,2), 0, 1e-12);
        TS_ASSERT_DELTA(diff3(1,2), 0, 1e-12);

        delete one_d_nodes[0];
        delete one_d_nodes[1];

        delete two_d_nodes[0];
        delete two_d_nodes[1];
        delete two_d_nodes[2];

        delete three_d_nodes[0];
        delete three_d_nodes[1];
        delete three_d_nodes[2];
        delete three_d_nodes[3];
    }

    void TestVaryingPde1D()
    {
        VaryingDiffusionAndSourceTermPde<1> pde;
        ChastePoint<1> evaluation_point(2);
        TS_ASSERT_EQUALS(pde.ComputeConstantInUSourceTerm(evaluation_point, NULL),8.0);
        c_matrix<double, 1, 1> diffusion_term = pde.ComputeDiffusionTerm(evaluation_point);
        TS_ASSERT_EQUALS(diffusion_term(0,0), 4);
    }

    void TestVaryingPde2D()
    {
        VaryingDiffusionAndSourceTermPde<2> pde;
        ChastePoint<2> evaluation_point(3,4);
        TS_ASSERT_EQUALS(pde.ComputeConstantInUSourceTerm(evaluation_point, NULL),125.0);
        c_matrix<double, 2, 2> diffusion_term = pde.ComputeDiffusionTerm(evaluation_point);
        TS_ASSERT_EQUALS(diffusion_term(0,0), 25.0);
        TS_ASSERT_EQUALS(diffusion_term(0,1), 0.0);
        TS_ASSERT_EQUALS(diffusion_term(1,0), 0.0);
        TS_ASSERT_EQUALS(diffusion_term(1,1), 25.0);
    }

    void TestSimpleUniformSourceParabolicPdeMethods()
    {
        // Create a PDE object
        SimpleUniformSourceParabolicPde<2> pde(0.1);

        // Test that the member variables have been initialised correctly
        TS_ASSERT_EQUALS(pde.GetCoefficient(),0.1);

        // Test methods
        ChastePoint<2> point;
        TS_ASSERT_DELTA(pde.ComputeSourceTerm(point,DBL_MAX), 0.1, 1e-6);
        TS_ASSERT_DELTA(pde.ComputeDuDtCoefficientFunction(point), 1.0, 1e-6);
        c_matrix<double,2,2> diffusion_matrix = pde.ComputeDiffusionTerm(point);
        for (unsigned i=0; i<2; i++)
        {
            for (unsigned j=0; j<2; j++)
            {
                double value = 0.0;
                if (i == j)
                {
                    value = 1.0;
                }
                TS_ASSERT_DELTA(diffusion_matrix(i,j), value, 1e-6);
            }
        }
    }

    void TestSimpleUniformSourceParabolicPdeArchiving()
    {

        FileFinder archive_dir("archive", RelativeTo::ChasteTestOutput);
        std::string archive_file = "SimpleUniformSourceParabolicPde.arch";
        ArchiveLocationInfo::SetMeshFilename("SimpleUniformSourceParabolicPde");

        {
            // Create a PDE object
            AbstractLinearParabolicPde<2,2>* const p_pde = new SimpleUniformSourceParabolicPde<2>(0.1);

            // Create output archive and archive PDE object
            ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();
            (*p_arch) << p_pde;

            delete p_pde;
        }

        {
            AbstractLinearParabolicPde<2,2>* p_pde;

            // Create an input archive and restore PDE object from archive
            ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
            (*p_arch) >> p_pde;

            // Test that the PDE and its member variables were archived correctly
            TS_ASSERT(dynamic_cast<SimpleUniformSourceParabolicPde<2>*>(p_pde) != NULL);

            SimpleUniformSourceParabolicPde<2>* p_static_cast_pde = static_cast<SimpleUniformSourceParabolicPde<2>*>(p_pde);
            TS_ASSERT_EQUALS(p_static_cast_pde->GetCoefficient(),0.1);

            // Avoid memory leaks
            delete p_pde;
        }
    }
};

#endif // TESTPDETESTCLASSES_HPP_

max_stars_repo_name: SoftMatterMechanics/ApicalStressFibers

max_issues_repo_name: SoftMatterMechanics/ApicalStressFibers

max_forks_repo_name: SoftMatterMechanics/ApicalStressFibers


text:
// Copyright 2017 Peter Dimov.
//
// 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

#include <boost/mp11/detail/config.hpp>

#if BOOST_MP11_MSVC
# pragma warning( disable: 4503 ) // decorated name length exceeded
#endif

#include <boost/mp11/function.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <boost/core/lightweight_test_trait.hpp>
#include <type_traits>

int main()
{
    using boost::mp11::mp_same;
    using boost::mp11::mp_true;
    using boost::mp11::mp_false;

    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<>, mp_true>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void>, mp_true>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void>, mp_true>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, void>, mp_true>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, void, void>, mp_true>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, void, void, void>, mp_true>));

    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, int>, mp_false>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, int>, mp_false>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, void, int>, mp_false>));
    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_same<void, void, void, void, int>, mp_false>));

    using boost::mp11::mp_repeat_c;
    using boost::mp11::mp_list;
    using boost::mp11::mp_apply;

    int const N = 1089;

    using L = mp_repeat_c<mp_list<void>, N>;
    using R = mp_apply<mp_same, L>;

    BOOST_TEST_TRAIT_TRUE((std::is_same<R, mp_true>));

    return boost::report_errors();
}


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_CSCPI_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_CSCPI_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the cosecant of angle in
    \f$\pi\f$ multiples: \f$1/c\sin(\pi x)\f$.

    @par Header <boost/simd/function/cscpi.hpp>

    @par Note

      As most other trigonometric function cscpi can be called with
      a second optional parameter  which is a tag on speed and accuracy
      (see @ref cos for further details)

    @see cscd, csc,

    @par Example:

      @snippet cscpi.cpp cscpi

    @par Possible output:

      @snippet cscpi.txt cscpi

  **/
  IEEEValue cscpi(IEEEValue const& x);
} }
#endif

#include <boost/simd/function/scalar/cscpi.hpp>
#include <boost/simd/function/simd/cscpi.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//

#define BOOST_TEST_MODULE sap_test

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <vector>

#include <nil/crypto3/zk/snark/reductions/r1cs_to_sap.hpp>
#include <nil/crypto3/zk/snark/relations/constraint_satisfaction_problems/r1cs.hpp>

#include <nil/crypto3/algebra/random_element.hpp>
#include <nil/crypto3/algebra/curves/mnt4.hpp>
#include <nil/crypto3/algebra/fields/mnt4/base_field.hpp>
#include <nil/crypto3/algebra/fields/mnt4/scalar_field.hpp>
#include <nil/crypto3/algebra/fields/arithmetic_params/mnt4.hpp>
#include <nil/crypto3/algebra/curves/params/multiexp/mnt4.hpp>
#include <nil/crypto3/algebra/curves/params/wnaf/mnt4.hpp>
#include <nil/crypto3/algebra/curves/mnt6.hpp>
#include <nil/crypto3/algebra/fields/mnt6/base_field.hpp>
#include <nil/crypto3/algebra/fields/mnt6/scalar_field.hpp>
#include <nil/crypto3/algebra/fields/arithmetic_params/mnt6.hpp>
#include <nil/crypto3/algebra/curves/params/multiexp/mnt6.hpp>
#include <nil/crypto3/algebra/curves/params/wnaf/mnt6.hpp>

#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_examples.hpp>

using namespace nil::crypto3::zk::snark;
using namespace nil::crypto3::algebra;

template<typename FieldType>
void test_sap(const std::size_t sap_degree, const std::size_t num_inputs, const bool binary_input) {
    /*
      We construct an instance where the SAP degree is <= sap_degree.
      The R1CS-to-SAP reduction produces SAPs with degree
        (2 * num_constraints + 2 * num_inputs + 1).
      So we generate an instance of R1CS where the number of constraints is
        (sap_degree - 1) / 2 - num_inputs.
    */
    const std::size_t num_constraints = (sap_degree - 1) / 2 - num_inputs;
    BOOST_CHECK(num_constraints >= 1);

    r1cs_example<FieldType> example;
    if (binary_input) {
        example = generate_r1cs_example_with_binary_input<FieldType>(num_constraints, num_inputs);
    } else {
        example = generate_r1cs_example_with_field_input<FieldType>(num_constraints, num_inputs);
    }
    BOOST_CHECK(example.constraint_system.is_satisfied(example.primary_input, example.auxiliary_input));

    const typename FieldType::value_type t = random_element<FieldType>(),
                                         d1 = random_element<FieldType>(),
                                         d2 = random_element<FieldType>();

    sap_instance<FieldType> sap_inst_1 = reductions::r1cs_to_sap<FieldType>::instance_map(example.constraint_system);

    sap_instance_evaluation<FieldType> sap_inst_2 =
        reductions::r1cs_to_sap<FieldType>::instance_map_with_evaluation(example.constraint_system, t);

    sap_witness<FieldType> sap_wit =
        reductions::r1cs_to_sap<FieldType>::witness_map(example.constraint_system, example.primary_input, example.auxiliary_input, d1, d2);

    BOOST_CHECK(sap_inst_1.is_satisfied(sap_wit));
    BOOST_CHECK(sap_inst_2.is_satisfied(sap_wit));
}

BOOST_AUTO_TEST_SUITE(sap_test_suite)

BOOST_AUTO_TEST_CASE(sap_test) {
    const std::size_t num_inputs = 10;

    /**
     * due to the specifics of our reduction, we can only get SAPs with odd
     * degrees, so we can only test "special" versions of the domains
     */

    using basic_curve_type = curves::mnt6<298>;

    const std::size_t basic_domain_size_special = (1ul << fields::arithmetic_params<basic_curve_type::scalar_field_type>::s) - 1ul;
    const std::size_t step_domain_size_special = (1ul << 10) + (1ul << 8) - 1ul;
    const std::size_t extended_domain_size_special = (1ul << (fields::arithmetic_params<basic_curve_type::scalar_field_type>::s + 1)) - 1ul;

    test_sap<typename basic_curve_type::scalar_field_type>(basic_domain_size_special, num_inputs, true);
    test_sap<typename basic_curve_type::scalar_field_type>(step_domain_size_special, num_inputs, true);
    test_sap<typename basic_curve_type::scalar_field_type>(extended_domain_size_special, num_inputs, true);

    test_sap<typename basic_curve_type::scalar_field_type>(basic_domain_size_special, num_inputs, false);
    test_sap<typename basic_curve_type::scalar_field_type>(step_domain_size_special, num_inputs, false);
    test_sap<typename basic_curve_type::scalar_field_type>(extended_domain_size_special, num_inputs, false);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include "Day14-DockingData.h"

#include "BitmaskProgramExecutor.h"

#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>

__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <boost/algorithm/string.hpp>
__END_LIBRARIES_DISABLE_WARNINGS

namespace AdventOfCode
{
namespace Year2020
{
namespace Day14
{

Instruction parseInstruction(const std::string& instruction)
{
    std::vector<std::string> tokens;
    if (instruction.substr(0, 3) == "mem")
    {
        boost::split(tokens, instruction, boost::is_any_of("[]= "), boost::token_compress_on);
        return Instruction{InstructionType::MEM, tokens.at(2), std::stoull(tokens.at(1))};
    }
    else
    {
        boost::split(tokens, instruction, boost::is_any_of("= "), boost::token_compress_on);
        return Instruction{InstructionType::MASK, tokens.at(1)};
    }
}

std::vector<Instruction> parseInstructions(const std::vector<std::string>& instructionLines)
{
    std::vector<Instruction> instructions;

    for (const auto& line : instructionLines)
    {
        Instruction instruction = parseInstruction(line);
        instructions.push_back(std::move(instruction));
    }

    return instructions;
}

uint64_t sumOfValuesInMemoryAfterCompletion(const std::vector<std::string>& instructionLines)
{
    std::vector<Instruction> instructions = parseInstructions(instructionLines);
    BitmaskProgramExecutor bitmaskProgramExecutor{std::move(instructions)};
    bitmaskProgramExecutor.execute();
    return bitmaskProgramExecutor.getSumOfValuesInMemory();
}

uint64_t sumOfValuesInMemoryAfterDecoderCompletion(const std::vector<std::string>& instructionLines)
{
    std::vector<Instruction> instructions = parseInstructions(instructionLines);
    BitmaskDecoderProgramExecutor bitmaskDecoderProgramExecutor{std::move(instructions)};
    bitmaskDecoderProgramExecutor.execute();
    return bitmaskDecoderProgramExecutor.getSumOfValuesInMemory();
}

}
}
}

max_stars_repo_name: dbartok/advent-of-code-cpp

max_issues_repo_name: dbartok/advent-of-code-cpp

max_forks_repo_name: dbartok/advent-of-code-cpp


text:
/*

 Copyright (c) 2014 University of Edinburgh, Imperial College, University of Manchester.
 Developed in the PAMELA project, EPSRC Programme Grant EP/K008730/1

 This code is licensed under the MIT License.

 Copyright 2016 Emanuele Vespa, Imperial College London

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.

 3. Neither the name of the copyright holder nor the names of its contributors
 may be used to endorse or promote products derived from this software without
 specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __PREPROCESSING_HPP
#define __PREPROCESSING_HPP

#include <cstdint>

#include <Eigen/Dense>

#include "se/timings.h"
#include "se/commons.h"
#include "se/utils/math_utils.h"
#include "se/image/image.hpp"
#include "se/sensor_implementation.hpp"

void bilateralFilterKernel(se::Image<float>&         out,
                           const se::Image<float>&   in,
                           const std::vector<float>& gaussian,
                           const float               e_d,
                           const int                 radius);

void depthToPointCloudKernel(se::Image<Eigen::Vector3f>& point_cloud_C,
                             const se::Image<float>&     depth_image,
                             const SensorImpl&           sensor);

void pointCloudToDepthKernel(se::Image<float>&                 depth_image,
                             const se::Image<Eigen::Vector3f>& point_cloud_X,
                             const Eigen::Matrix4f&            T_CX);

/**
 * NegY should only be true when reading an ICL-NUIM dataset which has a
 * left-handed coordinate system (the y focal length will be negative).
 */
template <bool NegY>
void pointCloudToNormalKernel(se::Image<Eigen::Vector3f>&       out,
                         const se::Image<Eigen::Vector3f>& in);

/**
 * Downsample the input depth to match the resolution of the output depth.
 * The ration between the resolutions must be a power of 2. Median downsampling
 * is used to prevent creating new depth which create artifacts behind object
 * edges. Depth values of 0 are considered invalid and are ignored when
 * computing the median.
 */
void downsampleDepthKernel(const float*           input_depth,
                           const Eigen::Vector2i& input_res,
                           se::Image<float>&      output_depth);

void halfSampleRobustImageKernel(se::Image<float>&       out,
                                 const se::Image<float>& in,
                                 const float             e_d,
                                 const int               r);

/**
 * Downsample an RGBA image and copy into an se::Image class.
 *
 * \param[in] input_RGBA Pointer to the RGBA image data, 4 channels, 8 bits
 * per channel.
 * \param[in] input_res Size of the RGBA image in pixels (width and height).
 * \param[out] output_RGB Object to store the output image to. The output image
 * dimensions must be an integer multiple of the input image dimensions. The
 * data for each pixel is stored in ARGB order, with the alpha channel in the
 * MSB of the uint32_t and the red channel in the LSB of the uint32_t.
 */
void downsampleImageKernel(const uint32_t*        input_RGBA,
                           const Eigen::Vector2i& input_res,
                           se::Image<uint32_t>&   output_RGBA);

#endif

max_stars_repo_name: hexagon-geo-surv/supereight-public

max_issues_repo_name: hexagon-geo-surv/supereight-public

max_forks_repo_name: hexagon-geo-surv/supereight-public


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

#ifndef MCL_PROBLEM_H
#define MCL_PROBLEM_H

#if MCL_DEBUG == 1
#include <iostream>
#endif

#include <Eigen/Dense>

namespace mcl {
namespace optlib {

template<typename Scalar, int DIM>
class Problem {
private:
    typedef Eigen::Matrix<Scalar,DIM,1> VecX;
    typedef Eigen::Matrix<Scalar,DIM,DIM> MatX;

public:
	// Returns true if the solver has converged
	// x0 is the result of the previous iteration
	// x1 is the result at the current iteration
	// grad is the gradient at the last iteration
	virtual bool converged(const VecX &x0, const VecX &x1, const VecX &grad) = 0;

	// Compute just the value
	virtual Scalar value(const VecX &x) = 0;

    virtual Scalar valueLBFGS(const VecX &x) = 0;

	// Compute the objective value and the gradient
    virtual Scalar gradient(const VecX &x, VecX &grad){
        std::cout << "finite gradient!" << std::endl;
        finiteGradient(x, grad);
        return value(x);
    }

    // Compute the objective value and the gradient
    //virtual void U_gradient(const MatX &F, const MatX &S, MatX &grad) = 0;
//    virtual void U_gradient(const VecX &x, VecX &grad){
//        std::cout << "finite gradient!" << std::endl;
//        finiteGradient(x, grad);
//    }

	// Compute hessian
	virtual void hessian(const VecX &x, MatX &hessian){
		finiteHessian(x, hessian);
	}

	// Solve dx = H^-1 g (used by Newton's)
	virtual void solve_hessian(const VecX &x, const VecX &grad, VecX &dx){
		MatX hess;
		if( DIM  == Eigen::Dynamic ){
			int dim = x.rows();
			hess = MatX::Zero(dim,dim);
		}
		hessian(x,hess); // hessian at x_n

		// Going with with high-accurate, low requirements as default factorization for lin-solve
		// Copied from https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html
		//	Method			Requirements	Spd (sm)	Spd (lg)	Accuracy
		//	partialPivLu()		Invertible	++		++		+
		//	fullPivLu()		None		-		- -		+++
		//	householderQr()		None		++		++		+
		//	colPivHouseholderQr()	None		++		-		+++
		//	fullPivHouseholderQr()	None		-		- -		+++
		//	llt()			PD		+++		+++		+
		//	ldlt()			P/N SD 		+++		+		++
		if( DIM == Eigen::Dynamic || DIM > 4 ){
			dx = hess.fullPivLu().solve(-grad);
		}
		else {
			dx = -hess.inverse()*grad;
		}
	}

    void getfiniteGradient(const VecX &x, VecX &grad){
        finiteGradient(x, grad);
    }

	// Gradient with finite differences
	inline void finiteGradient(const VecX &x, VecX &grad){
		const int accuracy = 0; // accuracy can be 0, 1, 2, 3
		const Scalar eps = 2.2204e-6;
		const std::vector< std::vector<Scalar> > coeff =
		{ {1, -1}, {1, -8, 8, -1}, {-1, 9, -45, 45, -9, 1}, {3, -32, 168, -672, 672, -168, 32, -3} };
		const std::vector< std::vector<Scalar> > coeff2 =
		{ {1, -1}, {-2, -1, 1, 2}, {-3, -2, -1, 1, 2, 3}, {-4, -3, -2, -1, 1, 2, 3, 4} };
		const std::vector<Scalar> dd = {2, 12, 60, 840};
		int dim = x.rows();
		VecX finiteDiff = VecX::Zero(dim);
		for(int d = 0; d < dim; ++d){
			for (int s = 0; s < 2*(accuracy+1); ++s){
				VecX xx = x.eval();
				xx[d] += coeff2[accuracy][s]*eps;
				finiteDiff[d] += coeff[accuracy][s]*value(xx);
			}
			finiteDiff[d] /= (dd[accuracy]* eps);
		}
		grad = finiteDiff;
	} // end finite grad

	// Hessian with finite differences
	inline void finiteHessian(const VecX &x, MatX &hess){
		const Scalar eps = std::numeric_limits<Scalar>::epsilon()*10e7;
		int dim = x.rows();
		for(int i = 0; i < dim; ++i){
			for(int j = 0; j < dim; ++j){
				VecX xx = x;
				Scalar f4 = value(xx);
				xx[i] += eps;
				xx[j] += eps;
				Scalar f1 = value(xx);
				xx[j] -= eps;
				Scalar f2 = value(xx);
				xx[j] += eps;
				xx[i] -= eps;
				Scalar f3 = value(xx);
				hess(i, j) = (f1 - f2 - f3 + f4) / (eps * eps);
			}
		}
	} // end finite hess
};

}
}

#endif

max_stars_repo_name: bldeng/AA-ADMM

max_issues_repo_name: wangxihao/AA-ADMM

max_forks_repo_name: wangxihao/AA-ADMM


text:
// std::forward<H>(h) rgstd : std::forward<Args>(args)
// Copyright (c) 2018 Damian Jarek (damian dot jarek93 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/djarek/compose
//

#ifndef COMPOSE_DETAIL_ALLOCATOR_UTILS_HPP
#define COMPOSE_DETAIL_ALLOCATOR_UTILS_HPP

#include <boost/asio/associated_allocator.hpp>

#ifndef COMPOSE_NO_RECYCLING_ALLOCATOR
#include <boost/asio/detail/recycling_allocator.hpp>
#endif // COMPOSE_NO_RECYCLING_ALLOCATOR
#include <memory>

namespace compose
{
namespace detail
{

#ifndef COMPOSE_NO_RECYCLING_ALLOCATOR
using default_allocator = boost::asio::detail::recycling_allocator<void>;
#else
using default_allocator = std::allocator<void>;
#endif

template<typename T>
struct uniform_init_wrapper
{
    template<typename... Args>
    explicit uniform_init_wrapper(Args&&... args)
      : t_{std::forward<Args>(args)...}
    {
    }

    T t_;
};

template<typename Allocator>
struct deleter
{
    using value_type = typename Allocator::value_type;
    void operator()(value_type* p) const
    {
        std::allocator_traits<Allocator> traits;
        traits.destroy(alloc_, p);
        traits.deallocate(alloc_, p, 1);
    }

    Allocator& alloc_;
};

template<typename Allocator>
struct deallocator
{
    using value_type = typename Allocator::value_type;
    void operator()(value_type* p) const
    {
        std::allocator_traits<Allocator>::deallocate(alloc_, p, 1);
    }

    Allocator& alloc_;
};

template<class Handler, class T>
using rebound_associated_alloc_t = typename std::allocator_traits<
  boost::asio::associated_allocator_t<Handler, default_allocator>>::
  template rebind_alloc<T>;

} // namespace detail
} // namespace compose

#endif // COMPOSE_DETAIL_ALLOCATOR_UTILS_HPP

max_stars_repo_name: djarek/Compose

max_issues_repo_name: djarek/Compose

max_forks_repo_name: djarek/Compose


text:
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ToolsCommon.h"

#include <boost/filesystem.hpp>
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <boost/iostreams/filtering_stream.hpp> // uses deprecated auto_ptr
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include <json/json.h>

#include "CommentFilter.h"
#include "DexLoader.h"
#include "DexOutput.h"
#include "DexUtil.h"
#include "IRMetaIO.h"
#include "InstructionLowering.h"
#include "JarLoader.h"
#include "Timer.h"
#include "Walkers.h"

namespace {
/**
 * Entry file contains the list of dex files, config file and original command
 * line arguments.
 */
const std::string ENTRY_FILE = "/entry.json";
void load_entry_file(const std::string& input_ir_dir, Json::Value* entry_data) {
  std::ifstream istrm(input_ir_dir + ENTRY_FILE);
  istrm >> *entry_data;
}

void write_entry_file(const std::string& output_ir_dir,
                      const Json::Value& entry_data) {
  std::ofstream ostrm(output_ir_dir + ENTRY_FILE);
  ostrm << entry_data;
}

/**
 * Init the IR meta to default values.
 */
void init_ir_meta(DexStoresVector& stores) {
  Timer t("Init default meta");
  Scope classes = build_class_scope(stores);
  walk::parallel::classes(classes, [](DexClass* cls) {
    cls->set_deobfuscated_name(show(cls));
    for (DexField* field : cls->get_sfields()) {
      field->set_deobfuscated_name(show(field));
    }
    for (DexField* field : cls->get_ifields()) {
      field->set_deobfuscated_name(show(field));
    }
    for (DexMethod* method : cls->get_dmethods()) {
      method->set_deobfuscated_name(show(method));
    }
    for (DexMethod* method : cls->get_vmethods()) {
      method->set_deobfuscated_name(show(method));
    }
  });
}

/**
 * Write meta data to file.
 * Development usage only
 */
void write_ir_meta(const std::string& output_ir_dir, DexStoresVector& stores) {
  Timer t("Dumping IR meta");
  Scope classes = build_class_scope(stores);
  ir_meta_io::dump(classes, output_ir_dir);
}

/**
 * Write intermediate dex to files.
 * Development usage only
 */
void write_intermediate_dex(const RedexOptions& redex_options,
                            ConfigFiles& conf,
                            const std::string& output_ir_dir,
                            DexStoresVector& stores,
                            Json::Value& dex_files) {
  Timer write_int_dex_timer("Write intermediate dex");
  {
    Timer t("Instruction lowering");
    instruction_lowering::run(stores);
  }
  std::unique_ptr<PositionMapper> pos_mapper(PositionMapper::make(""));
  for (size_t store_number = 0; store_number < stores.size(); ++store_number) {
    auto& store = stores[store_number];
    Timer t("Writing intermediate dexes");

    dex_files.append(Json::nullValue);
    Json::Value& store_files = dex_files[dex_files.size() - 1];
    store_files["name"] = store.get_name();
    store_files["list"] = Json::arrayValue;

    for (size_t i = 0; i < store.get_dexen().size(); i++) {
      if (store.get_dexen()[i].empty()) {
        continue;
      }
      std::string filename =
          redex::get_dex_output_name(output_ir_dir, store, i);
      write_classes_to_dex(redex_options,
                           filename,
                           &store.get_dexen()[i],
                           nullptr /* locator_index */,
                           store_number,
                           i,
                           conf,
                           pos_mapper.get(),
                           nullptr,
                           nullptr,
                           nullptr /* IODIMetadata* */,
                           stores[0].get_dex_magic());
      auto basename = boost::filesystem::path(filename).filename().string();
      store_files["list"].append(basename);
    }
  }
}

/**
 * Load intermediate dex
 */
void load_intermediate_dex(const std::string& input_ir_dir,
                           const Json::Value& dex_files,
                           DexStoresVector& stores) {
  Timer t("Load intermediate dex");
  dex_stats_t dex_stats;
  for (const Json::Value& store_files : dex_files) {
    DexStore store(store_files["name"].asString());
    stores.emplace_back(std::move(store));
    for (const Json::Value& file_name : store_files["list"]) {
      auto location = boost::filesystem::path(input_ir_dir);
      location /= file_name.asString();
      DexClasses classes = load_classes_from_dex(location.c_str(), &dex_stats);
      stores.back().add_classes(std::move(classes));
    }
  }
}

/**
 * Load IR meta data
 */
bool load_ir_meta(const std::string& input_ir_dir) {
  Timer t("Loading IR meta");
  return ir_meta_io::load(input_ir_dir);
}

static void assert_dex_magic_consistency(const std::string& source,
                                         const std::string& target) {
  always_assert_log(source.compare(target) == 0,
                    "APK contains dex file of different versions: %s vs %s\n",
                    source.c_str(), target.c_str());
}
} // namespace

namespace redex {

bool dir_is_writable(const std::string& dir) {
  if (!boost::filesystem::is_directory(dir)) {
    return false;
  }
#ifdef _MSC_VER
  return _access(dir.c_str(), 2) == 0;
#else
  return access(dir.c_str(), W_OK) == 0;
#endif
}

Json::Value parse_config(const std::string& config_file) {
  std::ifstream config_stream(config_file);
  if (!config_stream) {
    std::cerr << "error: cannot find config file: " << config_file << std::endl;
    exit(EXIT_FAILURE);
  }

  boost::iostreams::filtering_istream inbuf;
  inbuf.push(CommentFilter());
  inbuf.push(config_stream);
  Json::Value ret;
  inbuf >> ret; // parse JSON
  return ret;
}

/**
 * Dumping dex, IR meta data and entry file
 */
void write_all_intermediate(ConfigFiles& conf,
                            const std::string& output_ir_dir,
                            const RedexOptions& redex_options,
                            DexStoresVector& stores,
                            Json::Value& entry_data) {
  Timer t("Dumping all");
  redex_options.serialize(entry_data);
  entry_data["dex_list"] = Json::arrayValue;
  write_ir_meta(output_ir_dir, stores);
  write_intermediate_dex(redex_options, conf, output_ir_dir, stores,
                         entry_data["dex_list"]);
  write_entry_file(output_ir_dir, entry_data);
}

/**
 * Loading entry file, dex files and IR meta data
 */
void load_all_intermediate(const std::string& input_ir_dir,
                           DexStoresVector& stores,
                           Json::Value* entry_data) {
  Timer t("Loading all");
  load_entry_file(input_ir_dir, entry_data);
  load_intermediate_dex(input_ir_dir, (*entry_data)["dex_list"], stores);

  // load external classes
  Scope external_classes;
  if (!(*entry_data).get("jars", Json::nullValue).empty()) {
    for (const Json::Value& item : (*entry_data)["jars"]) {
      const std::string jar_path = item.asString();
      always_assert(load_jar_file(jar_path.c_str(), &external_classes));
    }
  }

  init_ir_meta(stores);
  if (!load_ir_meta(input_ir_dir)) {
    std::string error =
        "Use default IR meta instead. The process result may be greatly "
        "different from the result of running whole optimization passes with "
        "redex-all\n";
    std::cerr << error;
    TRACE_NO_LINE(MAIN, 1, "%s", error.c_str());
  }
}

/**
 * Helper to load classes from a list of input dex files into a DexStoresVector.
 * Processes dex (.dex) files as well as DexMetadata files (.json)
 */
void load_classes_from_dexes_and_metadata(
    const std::vector<std::string>& dex_files,
    DexStoresVector& stores,
    dex_stats_t& input_totals,
    std::vector<dex_stats_t>& input_dexes_stats) {
  always_assert_log(!stores.empty(),
                    "Cannot load classes into empty DexStoresVector");
  for (const auto& filename : dex_files) {
    if (filename.size() >= 5 &&
        filename.compare(filename.size() - 4, 4, ".dex") == 0) {
      assert_dex_magic_consistency(stores[0].get_dex_magic(),
                                   load_dex_magic_from_dex(filename.c_str()));
      dex_stats_t dex_stats;
      DexClasses classes = load_classes_from_dex(filename.c_str(), &dex_stats);
      input_totals += dex_stats;
      input_dexes_stats.push_back(dex_stats);
      stores[0].add_classes(std::move(classes));
    } else {
      DexMetadata store_metadata;
      store_metadata.parse(filename);
      DexStore store(store_metadata);
      for (const auto& file_path : store_metadata.get_files()) {
        assert_dex_magic_consistency(
            stores[0].get_dex_magic(),
            load_dex_magic_from_dex(file_path.c_str()));
        dex_stats_t dex_stats;
        DexClasses classes =
            load_classes_from_dex(file_path.c_str(), &dex_stats);

        input_totals += dex_stats;
        input_dexes_stats.push_back(dex_stats);
        store.add_classes(std::move(classes));
      }
      stores.emplace_back(std::move(store));
    }
  }
}

/**
 * Helper to get the output name of a specific dex file when a series of dex
 * files are being output by redex programs.
 * Index corresponds to the position in the order dex files are passed into
 * the redex programs: classes.dex -> 0, classes2.dex -> 1, classes3.dex -> 2...
 */
std::string get_dex_output_name(const std::string& output_dir,
                                const DexStore& store,
                                int index) {
  std::ostringstream ss;
  ss << output_dir << "/" << store.get_name();
  if (store.get_name().compare("classes") == 0) {
    // primary/secondary dex store, primary has no numeral and secondaries
    // start at 2
    if (index > 0) {
      ss << (index + 1);
    }
  } else {
    // other dex stores do not have a primary,
    // so it makes sense to start at 2
    ss << (index + 2);
  }
  ss << ".dex";
  return ss.str();
}
} // namespace redex

max_stars_repo_name: srivastavaayu/redex

max_issues_repo_name: srivastavaayu/redex

max_forks_repo_name: srivastavaayu/redex


text:
#include "test_registrator.h"

#include <queue_logger.h>
#include <time_tracker.h>

#include <boost/algorithm/string.hpp>

using namespace system_utilities::common;

namespace system_utilities
{
	namespace tests_
	{
		namespace common
		{
			namespace details
			{
				typedef queue_logger< true, false, false > q_logger;

				void logger_writer( q_logger* logger, const size_t size )
				{
					for ( size_t i = 0 ; i < size ; ++i )
						logger->note() << "qwerasdfzxcvkjhgiyt7654";
				}
				void queue_logger_write_test_helper( const size_t amount_of_messages_per_thread, const size_t time )
				{
					static const size_t processors_thread_size = 4;
					static const size_t thread_per_log = 4;

					std::stringstream log_first, log_second;

					details::q_logger::tasker task_processor( processors_thread_size );

					typedef boost::shared_ptr< details::q_logger > logger_ptr;
					std::vector< logger_ptr > loggers;
					boost::thread_group tg;

					{
						details::q_logger* logger = new details::q_logger( log_first, task_processor );
						loggers.push_back( logger_ptr( logger ) );
					}
					{
						details::q_logger* logger = new details::q_logger( log_second, task_processor );
						loggers.push_back( logger_ptr( logger ) );
					}

					time_tracker< std::chrono::milliseconds > tt;
					for ( size_t i = 0 ; i < thread_per_log ; ++i )
					{
						tg.create_thread( boost::bind( &details::logger_writer, loggers[0].get(), amount_of_messages_per_thread ) );
						tg.create_thread( boost::bind( &details::logger_writer, loggers[1].get(), amount_of_messages_per_thread ) );
					}
					tg.join_all();
					task_processor.wait();

					BOOST_CHECK_EQUAL( tt.elapsed() < time , true );
					//BOOST_CHECK_EQUAL( tt.elapsed( ), 250 );
					const std::string first_result = log_first.str();
					const std::string second_result = log_second.str();

					typedef std::vector< std::string > strings;
					{
						strings lines;
						boost::algorithm::split( lines, first_result, boost::algorithm::is_any_of( "\n" ) );
						BOOST_CHECK_EQUAL( lines.size(), amount_of_messages_per_thread * thread_per_log + 1 );
						for (size_t i = 0 ; i < amount_of_messages_per_thread * thread_per_log ; ++i )
							BOOST_CHECK_EQUAL( lines[ i ].c_str(), "qwerasdfzxcvkjhgiyt7654" );
					}
					{
						strings lines;
						boost::algorithm::split( lines, second_result, boost::algorithm::is_any_of( "\n" ) );
						BOOST_CHECK_EQUAL( lines.size(), amount_of_messages_per_thread * thread_per_log + 1 );
						for (size_t i = 0 ; i < amount_of_messages_per_thread * thread_per_log ; ++i )
							BOOST_CHECK_EQUAL( lines[ i ].c_str(), "qwerasdfzxcvkjhgiyt7654" );
					}

				}
			}
			void queue_logger_constructor_tests()
			{
				std::stringstream str;
				queue_logger<>::tasker task_processor( 4 );
				BOOST_CHECK_NO_THROW( queue_logger<> first_logger( str, task_processor ) );
				BOOST_CHECK_NO_THROW( queue_logger<> second_logger( str, task_processor ) );
			}
			void queue_logger_write_tests()
			{
				details::queue_logger_write_test_helper( 2500, 50 );
			}
			void queue_logger_performance_write_tests()
			{
				details::queue_logger_write_test_helper( 25000, 350 );
			}
		}
	}
}


text:
#include <boost/tokenizer.hpp>
#include <iostream>
#include <string>

using namespace std;

int main() {
  typedef boost::tokenizer<boost::offset_separator> tokenizer;
  string s = "Boost_C++_Libraries";
  int offsets[] = {5, 5, 9};
  boost::offset_separator sep{offsets, offsets + 3};
  tokenizer tok{s, sep};
  for (const auto &t: tok)
    cout << t << endl;
}


text:
#pragma once

#include <bunsan/config/traits.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>

#include <string>
#include <vector>

namespace bunsan::pm {

/// Represents \ref package_page "package" reference in repository.
class entry {
 public:
  static constexpr char def_delim = '/';

 public:
  // construction
  entry() = default;
  entry(const entry &) = default;
  entry(entry &&) = default;
  entry &operator=(const entry &e);
  entry &operator=(entry &&e) noexcept;
  void swap(entry &e) noexcept;

  // conversions
  entry(const std::string &name_, char delim = def_delim);
  entry(const char *name_, char delim = def_delim);
  entry &operator=(const std::string &name_);

  // comparisons
  bool operator==(const entry &e) const;
  bool operator<(const entry &e) const;

  // operations
  bool empty() const;
  entry operator/(const entry &e) const;
  entry absolute(const entry &root = entry{}) const;
  void make_absolute(const entry &root = entry{});

  // entry conversion getters
  boost::filesystem::path location() const;
  std::string name(char delim = def_delim) const;
  std::string name(const std::string &delim) const;
  const std::vector<std::string> &decomposition() const;
  boost::property_tree::ptree::path_type ptree_path() const;

  /// \returns repository / name('/') / name_
  std::string remote_resource(
      const std::string &repository,
      const boost::filesystem::path &name_ = boost::filesystem::path()) const;

  /// \returns dir / name('/') / name_
  boost::filesystem::path local_resource(
      const boost::filesystem::path &dir,
      const boost::filesystem::path &name_ = boost::filesystem::path()) const;

 public:
  static bool is_allowed_subpath(const std::string &subpath);
  static bool is_allowed_symbol(char c);

 private:
  void build(const std::string &name_, char delim = def_delim);

 private:
  std::vector<std::string> m_location;
};
inline void swap(entry &e1, entry &e2) noexcept { e1.swap(e2); }

template <typename Char, typename Traits>
inline std::basic_istream<Char, Traits> &operator>>(
    std::basic_istream<Char, Traits> &in, entry &e) {
  std::string name;
  in >> name;
  e = name;
  return in;
}

template <typename Char, typename Traits>
inline std::basic_ostream<Char, Traits> &operator<<(
    std::basic_ostream<Char, Traits> &out, const entry &e) {
  return out << e.name();
}

}  // namespace bunsan::pm

namespace bunsan::config::traits {
template <>
struct serializer<bunsan::pm::entry> {
  template <typename Archive>
  static void load(bunsan::pm::entry &obj, Archive &ar, const unsigned int) {
    std::string name_;
    ar >> name_;
    obj = name_;
  }

  template <typename Archive>
  static void save(const bunsan::pm::entry &obj, Archive &ar,
                   const unsigned int) {
    ar << obj.name();
  }
};
}  // namespace bunsan::config::traits

max_stars_repo_name: bacsorg/bacs

max_issues_repo_name: bacsorg/bacs

max_forks_repo_name: bacsorg/bacs