text:
/*    Copyright (c) 2010-2015, Delft University of Technology
 *    All rights reserved.
 *
 *    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 Delft University of Technology 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.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      140110    S. Hirsh          File created.
 *      140220    T. Roegiers       Small changes during codecheck.
 *
 *    References
 *    Hameduddin, I. Rotate vector(s) about axis, rodrigues_rot.m, available at
 *        http://www.mathworks.com/matlabcentral/fileexchange/34426-rotate-vectors-about-axis,
 *        2012, last accessed: 11th January, 2014.
 *    Murray, G. Rotation Matrices and Formulas java script, RotationMatrix.java available at
 *        https://sites.google.com/site/glennmurray/Home/rotation-matrices-and-formulas, 2011.
 *        last accessed: 20th January, 2014.
 *
 *    Notes
 *
 */

#define BOOST_TEST_MAIN

#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>

#include <Eigen/Core>

#include "Tudat/Basics/testMacros.h"
#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"

#include "Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.h"

namespace tudat
{
namespace unit_tests
{

//! Test suite for rotations about about arbitrary axes.
BOOST_AUTO_TEST_SUITE( test_RotationAboutArbitraryAxis )

BOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithCommonOrigin )
{

    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).

    //Set expected rotated vector.
    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 0.0, 1.414213562373095, 1.0 );

    //Set origin of rotation.
    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );

    //Set angle of rotation [rad].
    const double angleOfRotation = mathematical_constants::PI / 4.0;

    //Set axis of rotation.
    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 0.0, 0.0, 1.0 );

    //Set initial position of point.
    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( 1.0, 1.0, 1.0 );

    //Compute rotated position.
    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::
        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,
                                                  axisOfRotation, initialPositionOfPoint );

    // Compare computed and expected vectors.
    BOOST_CHECK_SMALL( computedRotatedPosition.x( ), std::numeric_limits< double >::epsilon( ) );

    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition.segment( 1, 2 ),
                                       expectedRotatedPosition.segment( 1, 2),
                                       std::numeric_limits< double >::epsilon( ) );

}

BOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins )
{

    //Benchmark data is obtained using java script (Murray, 2013).

    //Set expected rotated vector.
    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 3.156561876696307,
                                                                     -5.97145870839039,
                                                                     -4.418680390057799 );
    //Set origin of rotation.
    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 4.0, 1.0, -1.0 );

    //Set angle of rotation [rad]
    const double angleOfRotation = 7.0;

    //Set axis of rotation.
    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 2.0, -2.0, 3.0 );

    //Set initial position of point.
    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -1.0, -5.0, -1.0 );

    //Compute rotated position.
    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::
        computeRotationOfPointAboutArbitraryAxis( originOfRotation,  angleOfRotation,
                                                  axisOfRotation, initialPositionOfPoint );

    // Compare computed and expected radiation pressure acceleration vectors.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition,
                                       expectedRotatedPosition,
                                       std::numeric_limits<double>::epsilon( ) );

}

BOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins2 )
{

    //Benchmark data is obtained using java script (Murray, 2013).

    //Set expected rotated vector.
    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 15.71267522236938,
                                                                     -0.9723168350942417,
                                                                      9.449538267504582 );
    //Set origin of rotation.
    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );

    //Set angle of rotation [rad]
    const double angleOfRotation = 3.0;

    //Set axis of rotation.
    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );

    //Set initial position of point.
    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -4.3, -5.2, 1.2 );

    //Compute rotated position.
    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::
        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,
                                                  axisOfRotation, initialPositionOfPoint );

    // Compare computed and expected radiation pressure acceleration vectors.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition, expectedRotatedPosition, 1.0e-14 );

}

BOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithCommonOrigin )
{

    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).

    //Set expected rotated vector.
    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -5.480598288892924,
                                                                    0.532794739754852,
                                                                    6.138336269794405 );
    //Set origin of rotation.
    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );

    //Set angle of rotation [rad].
    const double angleOfRotation = 12.0;

    //Set axis of rotation.
    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -1.0, -2.0, -3.0 );

    //Set initial position of vector tail.
    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( 1.0, 3.0, 5.0 );

    //Set initial vector.
    const Eigen::Vector3d initialVector = Eigen::Vector3d( -6.0, 4.0, 4.0 );

    //Compute rotated position.
    const Eigen::Vector3d computedRotatedVector = basic_mathematics::
        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,
                                                   axisOfRotation, initialPositionOfVectorTail,
                                                   initialVector );

    // Compare computed and expected radiation pressure acceleration vectors
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );

}

BOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithDifferentOrigins )
{

    //Benchmark data is obtained using java script (Murray, 2013).

    //Set expected rotated vector.
    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -7.15233485964669,
                                                                   -2.4444137866784175,
                                                                    8.308967883857736 );
    //Set origin of rotation.
    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );

    //Set angle of rotation [rad].
    const double angleOfRotation = 3.0;

    //Set axis of rotation.
    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );

    //Set initial position of vector tail.
    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( -4.3, -5.2, 1.2 );

    //Set initial vector.
    const Eigen::Vector3d initialVector = Eigen::Vector3d( 0.3, 11.2, 0.8 );

    //Compute rotated position.
    const Eigen::Vector3d computedRotatedVector = basic_mathematics::
        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,
                                                   axisOfRotation, initialPositionOfVectorTail,
                                                   initialVector );

  // Compare computed and expected rotated vectors.
  TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );

}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat

max_stars_repo_name: JPelamatti/ThesisTUDAT

max_issues_repo_name: JPelamatti/ThesisTUDAT

max_forks_repo_name: JPelamatti/ThesisTUDAT


text:
//---------------------------------------------------------------------------//
//!
//! \file   tstInverseSquareCentimeterUnit.cpp
//! \author Alex Robinson
//! \brief  The inverse square centimeter unit unit tests
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <iostream>

// Boost Includes
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/cgs/area.hpp>
#include <boost/units/systems/si/area.hpp>

// FRENSIE Includes
#include "Utility_InverseSquareCentimeterUnit.hpp"
#include "Utility_InverseCentimeterUnit.hpp"

using namespace Utility::Units;
namespace si = boost::units::si;
namespace cgs = boost::units::cgs;

//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
// Check that the inverse square centimeter unit can be initialized
BOOST_AUTO_TEST_CASE( initialize )
{
  boost::units::quantity<Utility::Units::InverseSquareCentimeter>
    inverse_sqr_centimeter( 1.0*inverse_square_centimeter );

  BOOST_CHECK_EQUAL( inverse_sqr_centimeter.value(), 1.0 );

  inverse_sqr_centimeter = 2.0*inverse_square_centimeter;

  BOOST_CHECK_EQUAL( inverse_sqr_centimeter.value(), 2.0 );
}

//---------------------------------------------------------------------------//
// Check that the inv. sqr. cm unit can be initialized from the inv. cm unit
BOOST_AUTO_TEST_CASE( initialize_from_inv_cm )
{
  boost::units::quantity<Utility::Units::InverseSquareCentimeter>
    inverse_sqr_centimeter( 1.0*inverse_centimeter*inverse_centimeter );

  BOOST_CHECK_EQUAL( inverse_sqr_centimeter.value(), 1.0 );

  inverse_sqr_centimeter = 2.0*inverse_centimeter*inverse_centimeter;

  BOOST_CHECK_EQUAL( inverse_sqr_centimeter.value(), 2.0 );
}

//---------------------------------------------------------------------------//
// Check that the inv. sqr. cm unit can be initialized from cgs, si units
BOOST_AUTO_TEST_CASE( initialize_from_cgs_si )
{
  boost::units::quantity<Utility::Units::InverseSquareCentimeter>
    inverse_sqr_centimeter_cgs( 1.0/cgs::square_centimeter );

  boost::units::quantity<Utility::Units::InverseSquareCentimeter>
    inverse_sqr_centimeter_si( 1.0/si::square_meter );

  BOOST_CHECK_EQUAL( inverse_sqr_centimeter_cgs.value(), 1.0 );
  BOOST_CHECK_EQUAL( inverse_sqr_centimeter_si.value(), 1e-4 );
}

//---------------------------------------------------------------------------//
// end tstInverseSquareCentimeterUnit.cpp
//---------------------------------------------------------------------------//

ext: cpp


text:
// Copyright 2009 by BBN Technologies Corp.
// All Rights Reserved.

#include "common/leak_detection.h"

#include <cstring>
#include "common/UTF8Token.h"
#include "common/Symbol.h"
#include "common/UnexpectedInputException.h"
#include "parse/VocabularyTable.h"
#include "common/NgramScoreTable.h"
#include "parse/ParserTrainer/VocabPruner.h"
#include "parse/ParserTrainer/PrunerPOS.h"
#include "parse/ParserTrainer/FeatureVectorTable.h"
#include "Generic/common/FeatureModule.h"
#include <boost/scoped_ptr.hpp>

// DIVERSITY CHANGES: diversity tags (such as NPP-NNP and PERSON-NNPS)
// are listed in the open class tags list

int main(int argc, char* argv[]) {
	UTF8Token token;

	if (argc != 19 && argc != 18) {
        cerr << "wrong number of arguments to pruner\n";
		cerr << "Usage:\n";
		cerr << "   7 pairs of input/output files --\n";
		cerr << "     vocab head pre post left right part-of-speech\n";
		cerr << "   unknown word pruning threshold\n";
		cerr << "   feature vector output file \n";
		cerr << "   language\n\n";
		cerr << "   [smooth]\n\n";
		cerr << "(language parameter is new: it should be English, Arabic, etc)\n\n";
		cerr << "if the 'smooth' option is specified, then the program will prune\n";
		cerr << " in such a way as to produce events for use in smoothing\n";

        return -1;
    }

	try {

	// Load the specified language feature module.
	FeatureModule::load(argv[17]);

	// if a 18th parameter exists, we are producing smoothing corpus events
	//   by pruning with the main corpus vocabulary
	bool smooth = (argc == 19);
	if ((argc == 19) && (strcmp(argv[18], "smooth") != 0)) {
		cerr << "If 18th parameter is specified, it must be the string 'smooth'\n";
		return -1;
	}

	VocabPruner* pruner = new VocabPruner(argv[1],
								atoi(argv[15]), smooth);
	pruner->print_vocab(argv[2]);
	boost::scoped_ptr<UTF8InputStream> in_scoped_ptr(UTF8InputStream::build());
	UTF8InputStream& in(*in_scoped_ptr);

	in.open(argv[3]);
	pruner->headCounts = new NgramScoreTable (HEAD_NGRAM_SIZE + 1, in);
	in.close();
	pruner->prune_heads(argv[4]);

	in.open(argv[5]);
	pruner->modifierCounts = new NgramScoreTable (MODIFIER_NGRAM_SIZE + 1, in);
	in.close();
	pruner->prune_modifiers(argv[6]);

	in.open(argv[7]);
	pruner->modifierCounts = new NgramScoreTable (MODIFIER_NGRAM_SIZE + 1, in);
	in.close();
	pruner->prune_modifiers(argv[8]);

	in.open(argv[9]);
	pruner->lexicalCounts = new NgramScoreTable (LEXICAL_NGRAM_SIZE + 1, in);
	in.close();
	pruner->prune_lexical(argv[10]);

	in.open(argv[11]);
	pruner->lexicalCounts = new NgramScoreTable (LEXICAL_NGRAM_SIZE + 1, in);
	in.close();
	pruner->prune_lexical(argv[12]);

	in.open(argv[13]);
	PrunerPOS* POS = new PrunerPOS(in, pruner);
	in.close();
	POS->print(argv[14]);

	//use the POS file for feature prune as well
	in.open(argv[13]);
	FeatureVectorTable* feat = new FeatureVectorTable(in,pruner);
	in.close();
	feat->Print(argv[16]);

	// "WordFeature" table is new file from WordCollector

	char headBuf[501];
	char wordFeatInFN[501];
	size_t headsiz = strlen(argv[13]) - 4;
	if (headsiz > 490) headsiz = 490;
	_snprintf(headBuf, headsiz, "%s", argv[13]);
	headBuf[headsiz] = '\0';
	_snprintf(wordFeatInFN, 501, "%s.wordfeat",headBuf);
	//std::cerr<<"Reading word features from "<<wordFeatInFN<<"\n";
	char wordProbOutFN[501];
	_snprintf(wordProbOutFN, 501, "%s.wprob",headBuf);
	//std::cerr<<"Printing word features to "<<wordProbOutFN<<"\n";

	pruner->print_wordprob(wordFeatInFN,wordProbOutFN);

	} catch (UnexpectedInputException uc) {
		uc.putMessage(std::cerr);
		return -1;

	} catch (std::exception e) {
		std::cerr << "Exception: " << e.what() << std::endl;\
		return -1;
	}

	return 0;
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
// Copyright 2009-2010 Jeroen Habraken.
// Copyright 2009-2013 Dean Michael Berris, Glyn Matthews.
// Copyright 2012 Google, Inc.
// 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/config/warning_disable.hpp>
#include <boost/spirit/home/qi.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include "detail/uri_parse.hpp"

BOOST_FUSION_ADAPT_TPL_STRUCT(
    (FwdIter), (network::detail::hierarchical_part)(FwdIter),
    (boost::optional<boost::iterator_range<FwdIter> >, user_info)(
        boost::optional<boost::iterator_range<FwdIter> >, host)(
        boost::optional<boost::iterator_range<FwdIter> >, port)(
        boost::optional<boost::iterator_range<FwdIter> >, path));

BOOST_FUSION_ADAPT_TPL_STRUCT(
    (FwdIter), (network::detail::uri_parts)(FwdIter),
    (boost::optional<boost::iterator_range<FwdIter> >, scheme)(
        network::detail::hierarchical_part<FwdIter>, hier_part)(
        boost::optional<boost::iterator_range<FwdIter> >, query)(
        boost::optional<boost::iterator_range<FwdIter> >, fragment));

namespace network {
  namespace detail {
    namespace qi = boost::spirit::qi;

    template <class String>
    struct uri_grammar
        : qi::grammar<typename String::iterator,
                      detail::uri_parts<typename String::iterator>()> {

      typedef String string_type;
      typedef typename String::iterator iterator;

      uri_grammar() : uri_grammar::base_type(start, "uri") {
        // gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
        gen_delims %= qi::char_(":/?#[]@");
        // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," /
        // ";" / "="
        sub_delims %= qi::char_("!$&'()*+,;=");
        // reserved = gen-delims / sub-delims
        reserved %= gen_delims | sub_delims;
        // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
        unreserved %= qi::alnum | qi::char_("-._~");
        // pct-encoded = "%" HEXDIG HEXDIG
        pct_encoded %= qi::char_("%") >> qi::repeat(2)[qi::xdigit];

        // pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
        pchar %=
            qi::raw[unreserved | pct_encoded | sub_delims | qi::char_(":@")];

        // segment = *pchar
        segment %= qi::raw[*pchar];
        // segment-nz = 1*pchar
        segment_nz %= qi::raw[+pchar];
        // segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
        segment_nz_nc %=
            qi::raw[+(unreserved | pct_encoded | sub_delims | qi::char_("@"))];
        // path-abempty  = *( "/" segment )
        path_abempty %= qi::raw[*(qi::char_("/") >> segment)];
        // path-absolute = "/" [ segment-nz *( "/" segment ) ]
        path_absolute %= qi::raw
            [qi::char_("/") >> -(segment_nz >> *(qi::char_("/") >> segment))];
        // path-rootless = segment-nz *( "/" segment )
        path_rootless %= qi::raw[segment_nz >> *(qi::char_("/") >> segment)];
        // path-empty = 0<pchar>
        path_empty %= qi::raw[qi::eps];

        // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
        scheme %= qi::raw[qi::alpha >> *(qi::alnum | qi::char_("+.-"))];

        // user_info = *( unreserved / pct-encoded / sub-delims / ":" )
        user_info %=
            qi::raw[*(unreserved | pct_encoded | sub_delims | qi::char_(":"))];

        ip_literal %= qi::lit('[') >> (ipv6address | ipvfuture) >> ']';

        ipvfuture %= qi::lit('v') >> +qi::xdigit >> '.' >>
                     +(unreserved | sub_delims | ':');

        ipv6address %= qi::raw
            [qi::repeat(6)[h16 >> ':'] >> ls32 |
             "::" >> qi::repeat(5)[h16 >> ':'] >> ls32 |
             -qi::raw[h16] >> "::" >> qi::repeat(4)[h16 >> ':'] >> ls32 |
             -qi::raw[h16] >> "::" >> qi::repeat(3)[h16 >> ':'] >> ls32 |
             -qi::raw[h16] >> "::" >> qi::repeat(2)[h16 >> ':'] >> ls32 |
             -qi::raw[h16] >> "::" >> h16 >> ':' >> ls32 |
             -qi::raw[h16] >> "::" >> ls32 | -qi::raw[h16] >> "::" >> h16 |
             -qi::raw[h16] >> "::" |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" >>
                 qi::repeat(3)[h16 >> ':'] >> ls32 |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" >>
                 qi::repeat(2)[h16 >> ':'] >> ls32 |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" >> h16 >>
                 ':' >> ls32 |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" >> ls32 |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" >> h16 |
             -qi::raw[qi::repeat(1)[(h16 >> ':')] >> h16] >> "::" |
             -qi::raw[qi::repeat(2)[(h16 >> ':')] >> h16] >> "::" >>
                 qi::repeat(2)[h16 >> ':'] >> ls32 |
             -qi::raw[qi::repeat(2)[(h16 >> ':')] >> h16] >> "::" >> h16 >>
                 ':' >> ls32 |
             -qi::raw[qi::repeat(2)[(h16 >> ':')] >> h16] >> "::" >> ls32 |
             -qi::raw[qi::repeat(2)[(h16 >> ':')] >> h16] >> "::" >> h16 |
             -qi::raw[qi::repeat(2)[(h16 >> ':')] >> h16] >> "::" |
             -qi::raw[qi::repeat(3)[(h16 >> ':')] >> h16] >> "::" >> h16 >>
                 ':' >> ls32 |
             -qi::raw[qi::repeat(3)[(h16 >> ':')] >> h16] >> "::" >> ls32 |
             -qi::raw[qi::repeat(3)[(h16 >> ':')] >> h16] >> "::" >> h16 |
             -qi::raw[qi::repeat(3)[(h16 >> ':')] >> h16] >> "::" |
             -qi::raw[qi::repeat(4)[(h16 >> ':')] >> h16] >> "::" >> ls32 |
             -qi::raw[qi::repeat(4)[(h16 >> ':')] >> h16] >> "::" >> h16 |
             -qi::raw[qi::repeat(4)[(h16 >> ':')] >> h16] >> "::" |
             -qi::raw[qi::repeat(5)[(h16 >> ':')] >> h16] >> "::" >> h16 |
             -qi::raw[qi::repeat(5)[(h16 >> ':')] >> h16] >> "::" |
             -qi::raw[qi::repeat(6)[(h16 >> ':')] >> h16] >> "::"];

        // ls32 = ( h16 ":" h16 ) / IPv4address
        ls32 %= (h16 >> ':' >> h16) | ipv4address;

        // h16 = 1*4HEXDIG
        h16 %= qi::repeat(1, 4)[qi::xdigit];

        // dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT /
        // "25" %x30-35
        dec_octet %= !(qi::lit('0') >> qi::digit) >>
                     qi::raw[qi::uint_parser<boost::uint8_t, 10, 1, 3>()];

        // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
        ipv4address %=
            qi::raw[dec_octet >> qi::repeat(3)[qi::lit('.') >> dec_octet]];

        // reg-name = *( unreserved / pct-encoded / sub-delims )
        reg_name %= qi::raw[*(unreserved | pct_encoded | sub_delims)];

        // host = IP-literal / IPv4address / reg-name
        // This should be priority ordering, but Spirit is greedy
        // and will fail if 'host' starts with 'ipv4address'. We make
        // sure there isn't another '.' after last IPv4 octet.
        host %= qi::raw[ip_literal | (ipv4address >> !(&qi::lit('.'))) | reg_name];

        port %= qi::raw[qi::ushort_ | qi::eps];

        // query = *( pchar / "/" / "?" )
        query %= qi::raw[*(pchar | qi::char_("/?"))];

        // fragment = *( pchar / "/" / "?" )
        fragment %= qi::raw[*(pchar | qi::char_("/?"))];

        // hier-part = "//" authority path-abempty / path-absolute /
        // path-rootless / path-empty
        // authority = [ userinfo "@" ] host [ ":" port ]
        hier_part %=
            ((("//" >> user_info >> '@') | "//") >> host >> -(':' >> port) >>
             path_abempty) |
            (qi::attr(boost::optional<boost::iterator_range<iterator> >()) >>
             qi::attr(boost::optional<boost::iterator_range<iterator> >()) >>
             qi::attr(boost::optional<boost::iterator_range<iterator> >()) >>
             (path_absolute | path_rootless | path_empty));

        start %=
            ((scheme >> ':') >> hier_part >> -('?' >> query) >>
             -('#' >> fragment));
      }

      qi::rule<iterator, typename boost::iterator_range<iterator>::value_type()>
          gen_delims, sub_delims, reserved, unreserved;
      qi::rule<iterator, string_type()> pct_encoded, pchar;

      qi::rule<iterator, string_type()> segment, segment_nz, segment_nz_nc;
      qi::rule<iterator, boost::iterator_range<iterator>()> path_abempty,
          path_absolute, path_rootless, path_empty;

      qi::rule<iterator, string_type()> dec_octet, ipv4address, reg_name,
          ipv6address, ipvfuture, ip_literal;

      qi::rule<iterator, string_type()> h16, ls32;

      qi::rule<iterator, boost::iterator_range<iterator>()> host, port;

      qi::rule<iterator, boost::iterator_range<iterator>()> scheme, user_info,
          query, fragment;

      qi::rule<iterator, detail::hierarchical_part<iterator>()> hier_part;

      // actual uri parser
      qi::rule<iterator, detail::uri_parts<iterator>()> start;
    };

    bool parse(uri::string_type::iterator first,
               uri::string_type::iterator last,
               uri_parts<uri::string_type::iterator> &parts) {
      namespace qi = boost::spirit::qi;
      static uri_grammar<uri::string_type> grammar;
      bool is_valid = qi::parse(first, last, grammar, parts);
      return is_valid && (first == last);
    }
  }  // namespace detail
}  // namespace network

max_stars_repo_name: hunter-packages/uri

max_issues_repo_name: hunter-packages/uri

max_forks_repo_name: hunter-packages/uri


text:
#include "ReflectionOptions.hpp"
#include "ReflectionParser.hpp"

#include "MetaUtils.hpp"
#include "Switches.hpp"

#include <chrono>
#include <iostream>
#include <string>

#include <boost/program_options.hpp>

void parse(std::string const & appName, boost::program_options::variables_map const & cmdLine)
{
  ReflectionOptions options;

  options.generatorPath = appName;
  options.targetName = cmdLine.at(kSwitchTargetName).as<std::string>();
  options.inputPath = cmdLine.at(kSwitchInput).as<std::string>();
  options.outputPath = cmdLine.at(kSwitchOutput).as<std::string>();
  options.buildDirectory = cmdLine.at(kSwitchBuildDirectory).as<std::string>();

  // default arguments
  options.arguments =
  { {
      "-analyzer-display-progress",
      "-x",
      "c++",
      "-D__SC_REFLECTION_PARSER__",
      "-std=c++11"
    } };

  if (cmdLine.count(kSwitchCompilerFlags))
  {
    auto flagsList = cmdLine.at(kSwitchCompilerFlags).as<std::vector<std::string>>();

    for (std::string & flags : flagsList)
    {
      while (1)
      {
        size_t pos = flags.find(";");
        if (pos == std::string::npos)
          break;
        std::string f = flags.substr(0, pos);
        options.arguments.emplace_back(f);

        flags = flags.substr(pos + 1);
      }

    }
    //for (auto & flag : flags)
    //    options.arguments.emplace_back(flag.c_str());
  }

  std::cout << "Generate reflection code for \"" << options.targetName << "\"" << std::endl;

  ReflectionParser parser(options);

  try
  {
    parser.Parse();
  }
  catch (Exception e)
  {
    std::cerr << "Error: " << e.GetDescription() << std::endl;
  }
}

int main(int argc, char *argv[])
{
  auto start = std::chrono::system_clock::now();

  // parse command line
  try
  {
    boost::program_options::options_description program("SC Reflection Parser");

    program.add_options()
        (
          SWITCH_OPTION(Help),
          "Displays help information."
          )
        (
          SWITCH_OPTION(TargetName),
          boost::program_options::value<std::string>()->required(),
          "Input target project name."
          )
        (
          SWITCH_OPTION(Input),
          boost::program_options::value<std::string>()->required(),
          "Source path to parse headers in."
          )
        (
          SWITCH_OPTION(Output),
          boost::program_options::value<std::string>()->required(),
          "Output path for generated headers."
          )
        (
          SWITCH_OPTION(BuildDirectory),
          boost::program_options::value<std::string>()->default_value("./build"),
          "Directory that contains the build intermediate files."
          )
        (
          SWITCH_OPTION(CompilerFlags),
          boost::program_options::value<std::vector<std::string>>()->multitoken()->required(),
          "Optional list of flags to pass to the compiler."
          );

    boost::program_options::variables_map cmdLine;

    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, program), cmdLine);

    if (cmdLine.count("help"))
    {
      std::cout << program << std::endl;

      return EXIT_SUCCESS;
    }

    boost::program_options::notify(cmdLine);

    std::string const appName = argv[0];
    parse(appName, cmdLine);
  }
  catch (std::exception &e)
  {
    utils::FatalError(e.what());
  }
  catch (...)
  {
    utils::FatalError("Unhandled exception occurred!");
  }

  auto duration = std::chrono::system_clock::now() - start;

  std::cout << "Completed in "
            << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()
            << "ms" << std::endl;

  return EXIT_SUCCESS;
}

max_stars_repo_name: RuslanKorshunov/sc-machine

max_issues_repo_name: RuslanKorshunov/sc-machine

max_forks_repo_name: RuslanKorshunov/sc-machine


text:
#ifndef RADIUMENGINE_CORE_ALIGNED_STD_VECTOR_HPP_
#define RADIUMENGINE_CORE_ALIGNED_STD_VECTOR_HPP_
#include <Core/RaCore.hpp>

#include <Eigen/StdVector>
#include <vector>

namespace Ra {
namespace Core {
namespace Container {

/// Shortcut for the ubiquitous aligned std::vector
/// Uses Eigen's aligned allocator, as stated in
/// http://eigen.tuxfamily.org/dox/group__TopicStlContainers.html
template <typename T>
struct AlignedStdVector : public std::vector<T, Eigen::aligned_allocator<T>> {
    using std::vector<T, Eigen::aligned_allocator<T>>::vector;
};
} // namespace Container
} // namespace Core
} // namespace Ra
#endif // RADIUMENGINE_CORE_ALIGNED_STD_VECTOR_HPP_

ext: hpp

max_stars_repo_name: sylvaindeker/Radium-Engine

max_issues_repo_name: sylvaindeker/Radium-Engine

max_forks_repo_name: sylvaindeker/Radium-Engine


text:
#include "df_grid.hpp"
#include "datatypes.hpp"
#include <boost/python.hpp>

namespace gd {
using namespace boost::python;

void py_export_schw_df_grid() {
	class_<DFGrid, boost::noncopyable >("DFGrid", init<int, int, double, double, Galaxy*>())
		.def("output_grid", &DFGrid::output_grid)
		.def("n_dofs", &DFGrid::n_dofs)
		.def("refine_global", &DFGrid::refine_global)
		.def("shape_value", &DFGrid::shape_value)
		.def("print_dof_indices_per_face", &DFGrid::print_dof_indices_per_face)
		.def("print_dof_indices_per_face_on_level", &DFGrid::print_dof_indices_per_face_on_level)
		.def("print_vertices", &DFGrid::print_vertices)
			;
}

};

max_stars_repo_name: maartenbreddels/mab

max_issues_repo_name: maartenbreddels/mab

max_forks_repo_name: maartenbreddels/mab


text:
#include <internal/facts/resolvers/zpool_resolver.hpp>
#include <facter/facts/fact.hpp>
#include <facter/facts/collection.hpp>
#include <facter/facts/scalar_value.hpp>
#include <leatherman/execution/execution.hpp>
#include <leatherman/util/regex.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace facter::facts;
using namespace leatherman::execution;
using namespace leatherman::util;

namespace facter { namespace facts { namespace resolvers {

    zpool_resolver::zpool_resolver() :
        resolver(
            "ZFS storage pool",
            {
                fact::zpool_version,
                fact::zpool_featureflags,
                fact::zpool_versionnumbers,
            })
    {
    }

    void zpool_resolver::resolve(collection& facts)
    {
        auto data = collect_data(facts);

        if (!data.version.empty()) {
            facts.add(fact::zpool_version, make_value<string_value>(move(data.version)));
        }
        if (!data.feature_flags.empty()) {
            facts.add(fact::zpool_featureflags, make_value<string_value>(boost::join(data.feature_flags, ",")));
        }
        if (!data.versions.empty()) {
            facts.add(fact::zpool_versionnumbers, make_value<string_value>(boost::join(data.versions, ",")));
        }
    }

    zpool_resolver::data zpool_resolver::collect_data(collection& facts)
    {
        data result;

        enum { UNKNOWN, FEATURES, VERSIONS } state = UNKNOWN;

        // Get the zpool version and features
        static boost::regex zpool_version("^This system is currently running ZFS pool version (\\d+)\\.$");
        static boost::regex zpool_feature_flags("^This system supports ZFS pool feature flags\\.$");

        static boost::regex zpool_supported_feature_header("^The following features are supported:$");
        static boost::regex zpool_supported_versions_header("^The following versions are supported:$");
        static boost::regex zpool_supported_legacy_versions_header("^The following legacy versions are also supported:$");

        static boost::regex zpool_supported_feature("^([[:alnum:]_]+)(\\s+\\(read-only compatible\\))?$");
        static boost::regex zpool_supported_version("^\\s*(\\d+)[ ]");

        string feature;
        each_line(zpool_command(), {"upgrade", "-v"}, [&] (string& line) {
            switch (state) {
            case UNKNOWN:
                if (re_search(line, zpool_version, &result.version)) {
                } else if (re_search(line, zpool_feature_flags)) {
                    result.version = "5000";
                } else if (re_search(line, zpool_supported_feature_header)) {
                    state = FEATURES;
                } else if (re_search(line, zpool_supported_versions_header)) {
                    state = VERSIONS;
                }
                break;

            case FEATURES:
                if (re_search(line, zpool_supported_feature, &feature)) {
                    result.feature_flags.emplace_back(move(feature));
                } else if (re_search(line, zpool_supported_legacy_versions_header)) {
                    state = VERSIONS;
                }
                break;

            case VERSIONS:
                string feature;
                if (re_search(line, zpool_supported_version, &feature)) {
                    result.versions.emplace_back(move(feature));
                }
                break;
            }
            return true;
        });
        return result;
    }

}}}  // namespace facter::facts::resolvers

ext: cc

max_stars_repo_name: mihaibuzgau/facter

max_issues_repo_name: mihaibuzgau/facter

max_forks_repo_name: mihaibuzgau/facter


text:
// (C) Copyright Jeremy Siek 2000. Permission to copy, use, modify,
// sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.

#include <boost/concept_check.hpp>

/*

  This file verifies that function_requires() of the Boost Concept
  Checking Library catches errors when it is suppose to.

*/

struct foo { };

int
main()
{
  boost::function_requires< boost::EqualityComparableConcept<foo> >();
  return 0;
}


text:
// ======================================================================
/*!
 * \file
 * \brief Interface of class TextGen::IdGenerator
 */
// ======================================================================

#include "IdGenerator.h"

#include <boost/atomic.hpp>

namespace TextGen
{
// ----------------------------------------------------------------------
/*!
 * \brief Return a new ID
 *
 * \return The generated ID
 */
// ----------------------------------------------------------------------

long IdGenerator::generate()
{
  static boost::atomic<long> id;
  return ++id;
}

}  // namespace TextGen

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

max_stars_repo_name: fmidev/smartmet-library-calculator

max_issues_repo_name: fmidev/smartmet-library-calculator

max_forks_repo_name: fmidev/smartmet-library-calculator


text:
#include <iostream>
#include <assert.h>

//pcl
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
// pcl
#include <pcl/common/transforms.h>
#include <pcl/point_types.h>

//octomap
#include <octomap/octomap.h>
#include <octomap/ColorOcTree.h>
#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

// boost.format 字符串处理
#include <boost/format.hpp>

// 使用Eigen的Geometry模块处理3d运动
#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
using namespace cv;

float camera_scale  = 1000;
float cx     = 620.5;
float cy     = 367.5;
float fx     = 481.0;
float fy     = 479.0;

Vec3b get_color(cv::Mat image,Eigen::Vector2d pixel){

return image.at<Vec3b>(Point(int(pixel[0]),int(pixel[1])));

// for better color, maybe interpolation?

}

int main( int argc, char** argv )
{
    if (argc != 4)
    {
        cout<<"Usage: map_pcd_left_img <file.pcd> <file.png>  xyzq.txt"<<endl;
        return -1;
    }

    string pcd_path = argv[1], img_path = argv[2],transform_path = argv[3];
    pcl::PointCloud<pcl::PointXYZI> cloud;
    pcl::io::loadPCDFile<pcl::PointXYZI> ( pcd_path, cloud );

    cout<<"point cloud loaded, piont size = "<<cloud.points.size()<<endl;

    cv::Mat img = cv::imread(img_path);
    cv::Mat img_fuse = img.clone();
   // cv::imshow("",img);
   // cv::waitKey(0);

//  create the transformation -0.02 -0.17 0.1 0 0 0 1
    ifstream fin;
    fin.open( transform_path );
   // Eigen::Quaterniond q;
   // Eigen::Isometry3d t;
    vector< Eigen::Isometry3d > poses;
   // while( fin.peek() != EOF )
    {
        int index_keyframe;
        float data[7]; // 三个位置加一个姿态四元数x,y,z, w,ux,uy,uz
        fin>>index_keyframe;
        for ( int i=0; i<7; i++ )
        {
            fin>>data[i];
            cout<<data[i]<<" ";
        }
        cout<<endl;
        //if (fin.fail()) break;
        // 注意这里的顺序。g2o文件四元数按 qx, qy, qz, qw来存
        // 但Eigen初始化按照qw, qx, qy, qz来做
        Eigen::Quaterniond q( data[6], data[3], data[4], data[5] );
        Eigen::Isometry3d t(q);
        t(0,3) = data[0]; t(1,3) = data[1]; t(2,3) = data[2];
        poses.push_back(t);
	poses[0] = poses[0];

    }

//transform the point cloud so as to it is in the left cam frame

cout<<poses[0].matrix() <<endl;

    pcl::PointCloud<pcl::PointXYZI>::Ptr trans_cloud_ptr( new     pcl::PointCloud<pcl::PointXYZI>() );
    pcl::transformPointCloud( cloud, *trans_cloud_ptr, poses[0].matrix());

    //声明octomap变量
    cout<<"copy data into octomap..."<<endl;
    // 创建带颜色的八叉树对象，参数为分辨率，这里设成了0.05
    octomap::ColorOcTree tree( 0.005 );

    for (auto p:trans_cloud_ptr->points)
    {

// construct octomap when there are visual content.

		//
		   double x = fx*p.x/p.z+cx;
		   double y = fy*p.y/p.z+cy;
		   Eigen::Vector2d pixel(x,y); //1280 720

			if(pixel[0]>0 && pixel[1]>0 && pixel[0]<1280 && pixel[1]<720){

		   	cout<<"pcd: "<<p.x<<" "<<p.y<<" "<<p.z<<" pixel: "<<pixel[0]<<" "<<pixel[1]<<endl;
			//cout<<p.intensity<<endl;

			img_fuse.at<Vec3b>(Point(int(pixel[0]),int(pixel[1]))) = 250,0,0;//p.intensity,p.intensity,p.intensity;

			// 将点云里的点插入到octomap中
			tree.updateNode( octomap::point3d(p.x, p.y, p.z), true );
			Vec3b color = get_color(img,pixel);
			tree.integrateNodeColor( p.x, p.y, p.z, color[0],color[1],color[2] );

			}

    }

    cv::imshow("",img_fuse);
    cv::waitKey();
    cv::imwrite("fused_img.png",img_fuse);

    // 更新octomap
    tree.updateInnerOccupancy();
    // 存储octomap, 注意要存成.ot文件而非.bt文件
    tree.write( "color_coded.ot" );
    cout<<"done."<<endl;

    return 0;
}


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

namespace dials { namespace algorithms { namespace boost_python {

  using namespace boost::python;

  void export_summation();

  BOOST_PYTHON_MODULE(dials_algorithms_integration_sum_ext) {
    export_summation();
  }

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

max_stars_repo_name: TiankunZhou/dials

max_issues_repo_name: TiankunZhou/dials

max_forks_repo_name: TiankunZhou/dials


text:
#include "data.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>

using namespace std;

Pair::Pair(const std::vector<float>& x1,const std::vector<float>& x2,const int label) :
m_x1(x1), m_x2(x2), m_label(label)
{
}

Pair::~Pair()
{
}

// FileData
/**
 * DataFile Format should be:
 * datatype: eg: int/float/double/etc.)
 * size: eg: numRows numCols
 * data (last column should be the labels)
 */
FileData::FileData()
{
}

FileData::FileData(const std::string& dataFileName, const std::string& labelsFileName) : m_dataFileName( dataFileName ),
        m_labelsFileName( labelsFileName )
{

}

FileData::~FileData()
{
    // Implement me
}

void FileData::setDataFileName(const std::string& fileName)
{
    m_dataFileName = fileName;
}

void FileData::setLabelsFileName(const std::string& fileName)
{
    m_labelsFileName = fileName;
}

void FileData::readData()
{
    std::fstream myfile(m_dataFileName.c_str(),ios::in);
    if (myfile.is_open())
    {
        std::string line;
        // get datatype
        getline(myfile,line);
        // get size
        getline(myfile,line);
        stringstream ss(line);
        string tmp;
        int numRows, numCols;
        ss >> numRows;
        ss >> numCols;
        // pop-up the dense/sparse thing
        getline(myfile,line);

        m_data.resize(numRows,numCols);

        for (int row = 0; row < numRows; row++)
        {
            getline(myfile,line);
            stringstream ss2(line);
            for (int col = 0; col < numCols; col++)
            {
                ss2 >> m_data(row,col);
            }
        }

        myfile.close();
    }

    else
    {
        cout << "Unable to open file" << m_dataFileName << endl;
        exit(-1);
    }
}

void FileData::readLabels()
{
    std::fstream myfile(m_labelsFileName.c_str(),ios::in);
    if (myfile.is_open())
    {
        std::string line;
        // get datatype
        getline(myfile,line);
        // get size
        getline(myfile,line);
        stringstream ss(line);
        string tmp;
        int numLabels;
        ss >> numLabels;

        // pop-up the dense/sparse thing
        getline(myfile,line);

        m_labels.resize(numLabels);
        for (int row = 0; row < numLabels; row++)
        {
            getline(myfile, line);
            stringstream ss2(line);
            ss2 >> m_labels[row];
        }

        myfile.close();
    }

    else
    {
        cout << "Unable to open file" << m_dataFileName << endl;
        exit(-1);
    }
}

void FileData::writeData()
{
    std::fstream myfile;
    std::string dataFileName = m_dataFileName;
    dataFileName += ".data";
    myfile.open(dataFileName.c_str(), std::ios::out);

    myfile << "float" << endl;
    myfile << m_data.size1() << " " << m_data.size2() << endl;
    for (size_t row = 0; row < m_data.size1(); row++  )
    {
        for (size_t col = 0; col < m_data.size2(); col++)
        {
            myfile << m_data(row,col) << " ";
        }
        myfile << endl;
    }

    myfile.flush();
    myfile.close();
}

void FileData::writeLabels()
{
    std::fstream myfile;
    std::string dataFileName = m_labelsFileName;
    dataFileName += ".labels";
    myfile.open(dataFileName.c_str(), std::ios::out);

    myfile << "int" << endl;
    myfile << m_labels.size() << " " << 1 << endl;

    for (size_t row = 0; row < m_labels.size(); row++)
    {
        myfile << m_labels[row];
        myfile << endl;
    }

    myfile.flush();
    myfile.close();
}

void FileData::createPairs()
{
    int numSamples = m_data.size1();
    int numFeatures = m_data.size2();
    for(int p = 0; p < numSamples;p+=2) {
        std::vector<float> x1;
        std::vector<float> x2;
        for( int feat = 0; feat < numFeatures; feat++) {
            x1.push_back(m_data(p,feat));
            x2.push_back(m_data(p+1,feat));
        }
        int label = (m_labels[p] == 1) ? 1 : 0;
        Pair newPair(x1,x2,label);
        m_pairs.push_back(newPair);
    }
}

max_stars_repo_name: tschuls/ETH-SegReg-DLL

max_issues_repo_name: tschuls/ETH-SegReg-DLL

max_forks_repo_name: tschuls/ETH-SegReg-DLL


text:
//
// buffer.hpp
//

#ifndef BUFFER_HPP
#define BUFFER_HPP

#include <memory>
#include <vector>
#include <boost/asio.hpp>

namespace distributor {

/// A reference-counted mutable buffer. The caller is responsible for only
/// writing from one thread.
class buffer {
public:
    /// Construct with the given size.
    explicit buffer(std::size_t size = 0)
        : data_(std::make_shared<std::vector<char>>(size))
    {
    }

    /// Create a mutable buffer to the data.
    boost::asio::mutable_buffer to_buffer()
    {
        return boost::asio::buffer(*data_);
    }
private:
    std::shared_ptr<std::vector<char>> data_;
};

} // namespace distributor

#endif // BUFFER_HPP

max_stars_repo_name: tdepoyfe/distributor

max_issues_repo_name: tdepoyfe/distributor

max_forks_repo_name: tdepoyfe/distributor


text:
//
// select_reactor.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP
#define BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP

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

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/socket_types.hpp> // Must come before posix_time.

#include <boost/asio/detail/push_options.hpp>
#include <cstddef>
#include <boost/config.hpp>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/fd_set_adapter.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/op_queue.hpp>
#include <boost/asio/detail/reactor_op.hpp>
#include <boost/asio/detail/reactor_op_queue.hpp>
#include <boost/asio/detail/select_interrupter.hpp>
#include <boost/asio/detail/select_reactor_fwd.hpp>
#include <boost/asio/detail/service_base.hpp>
#include <boost/asio/detail/signal_blocker.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/thread.hpp>
#include <boost/asio/detail/timer_op.hpp>
#include <boost/asio/detail/timer_queue_base.hpp>
#include <boost/asio/detail/timer_queue_fwd.hpp>
#include <boost/asio/detail/timer_queue_set.hpp>

namespace boost {
namespace asio {
namespace detail {

template <bool Own_Thread>
class select_reactor
  : public boost::asio::detail::service_base<select_reactor<Own_Thread> >
{
public:
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  enum { read_op = 0, write_op = 1, except_op = 2,
    max_select_ops = 3, connect_op = 3, max_ops = 4 };
#else // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  enum { read_op = 0, write_op = 1, except_op = 2,
    max_select_ops = 3, connect_op = 1, max_ops = 3 };
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

  // Per-descriptor data.
  struct per_descriptor_data
  {
  };

  // Constructor.
  select_reactor(boost::asio::io_service& io_service)
    : boost::asio::detail::service_base<
        select_reactor<Own_Thread> >(io_service),
      io_service_(use_service<io_service_impl>(io_service)),
      mutex_(),
      interrupter_(),
      stop_thread_(false),
      thread_(0),
      shutdown_(false)
  {
    if (Own_Thread)
    {
      boost::asio::detail::signal_blocker sb;
      thread_ = new boost::asio::detail::thread(
          bind_handler(&select_reactor::call_run_thread, this));
    }
  }

  // Destructor.
  ~select_reactor()
  {
    shutdown_service();
  }

  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service()
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    shutdown_ = true;
    stop_thread_ = true;
    lock.unlock();

    if (Own_Thread)
    {
      if (thread_)
      {
        interrupter_.interrupt();
        thread_->join();
        delete thread_;
        thread_ = 0;
      }
    }

    op_queue<operation> ops;

    for (int i = 0; i < max_ops; ++i)
      op_queue_[i].get_all_operations(ops);

    timer_queues_.get_all_timers(ops);
  }

  // Initialise the task, but only if the reactor is not in its own thread.
  void init_task()
  {
    io_service_.init_task();
  }

  // Register a socket with the reactor. Returns 0 on success, system error
  // code on failure.
  int register_descriptor(socket_type, per_descriptor_data&)
  {
    return 0;
  }

  // Start a new operation. The reactor operation will be performed when the
  // given descriptor is flagged as ready, or an error has occurred.
  void start_op(int op_type, socket_type descriptor,
      per_descriptor_data&, reactor_op* op, bool)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    if (!shutdown_)
    {
      bool first = op_queue_[op_type].enqueue_operation(descriptor, op);
      io_service_.work_started();
      if (first)
        interrupter_.interrupt();
    }
  }

  // Cancel all operations associated with the given descriptor. The
  // handlers associated with the descriptor will be invoked with the
  // operation_aborted error.
  void cancel_ops(socket_type descriptor, per_descriptor_data&)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    cancel_ops_unlocked(descriptor, boost::asio::error::operation_aborted);
  }

  // Cancel any operations that are running against the descriptor and remove
  // its registration from the reactor.
  void close_descriptor(socket_type descriptor, per_descriptor_data&)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    cancel_ops_unlocked(descriptor, boost::asio::error::operation_aborted);
  }

  // Add a new timer queue to the reactor.
  template <typename Time_Traits>
  void add_timer_queue(timer_queue<Time_Traits>& timer_queue)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    timer_queues_.insert(&timer_queue);
  }

  // Remove a timer queue from the reactor.
  template <typename Time_Traits>
  void remove_timer_queue(timer_queue<Time_Traits>& timer_queue)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    timer_queues_.erase(&timer_queue);
  }

  // Schedule a new operation in the given timer queue to expire at the
  // specified absolute time.
  template <typename Time_Traits>
  void schedule_timer(timer_queue<Time_Traits>& timer_queue,
      const typename Time_Traits::time_type& time, timer_op* op, void* token)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    if (!shutdown_)
    {
      bool earliest = timer_queue.enqueue_timer(time, op, token);
      io_service_.work_started();
      if (earliest)
        interrupter_.interrupt();
    }
  }

  // Cancel the timer operations associated with the given token. Returns the
  // number of operations that have been posted or dispatched.
  template <typename Time_Traits>
  std::size_t cancel_timer(timer_queue<Time_Traits>& timer_queue, void* token)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);
    op_queue<operation> ops;
    std::size_t n = timer_queue.cancel_timer(token, ops);
    lock.unlock();
    io_service_.post_deferred_completions(ops);
    return n;
  }

  // Run select once until interrupted or events are ready to be dispatched.
  void run(bool block, op_queue<operation>& ops)
  {
    boost::asio::detail::mutex::scoped_lock lock(mutex_);

    // Check if the thread is supposed to stop.
    if (Own_Thread)
      if (stop_thread_)
        return;

    // Set up the descriptor sets.
    fd_set_adapter fds[max_select_ops];
    fds[read_op].set(interrupter_.read_descriptor());
    socket_type max_fd = 0;
    bool have_work_to_do = !timer_queues_.all_empty();
    for (int i = 0; i < max_select_ops; ++i)
    {
      have_work_to_do = have_work_to_do || !op_queue_[i].empty();
      op_queue_[i].get_descriptors(fds[i], ops);
      if (fds[i].max_descriptor() > max_fd)
        max_fd = fds[i].max_descriptor();
    }

#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
    // Connection operations on Windows use both except and write fd_sets.
    have_work_to_do = have_work_to_do || !op_queue_[connect_op].empty();
    op_queue_[connect_op].get_descriptors(fds[write_op], ops);
    if (fds[write_op].max_descriptor() > max_fd)
      max_fd = fds[write_op].max_descriptor();
    op_queue_[connect_op].get_descriptors(fds[except_op], ops);
    if (fds[except_op].max_descriptor() > max_fd)
      max_fd = fds[except_op].max_descriptor();
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

    // We can return immediately if there's no work to do and the reactor is
    // not supposed to block.
    if (!block && !have_work_to_do)
      return;

    // Determine how long to block while waiting for events.
    timeval tv_buf = { 0, 0 };
    timeval* tv = block ? get_timeout(tv_buf) : &tv_buf;

    lock.unlock();

    // Block on the select call until descriptors become ready.
    boost::system::error_code ec;
    int retval = socket_ops::select(static_cast<int>(max_fd + 1),
        fds[read_op], fds[write_op], fds[except_op], tv, ec);

    // Reset the interrupter.
    if (retval > 0 && fds[read_op].is_set(interrupter_.read_descriptor()))
      interrupter_.reset();

    lock.lock();

    // Dispatch all ready operations.
    if (retval > 0)
    {
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
      // Connection operations on Windows use both except and write fd_sets.
      op_queue_[connect_op].perform_operations_for_descriptors(
          fds[except_op], ops);
      op_queue_[connect_op].perform_operations_for_descriptors(
          fds[write_op], ops);
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

      // Exception operations must be processed first to ensure that any
      // out-of-band data is read before normal data.
      for (int i = max_select_ops - 1; i >= 0; --i)
        op_queue_[i].perform_operations_for_descriptors(fds[i], ops);
    }
    timer_queues_.get_ready_timers(ops);
  }

  // Interrupt the select loop.
  void interrupt()
  {
    interrupter_.interrupt();
  }

private:
  // Run the select loop in the thread.
  void run_thread()
  {
    if (Own_Thread)
    {
      boost::asio::detail::mutex::scoped_lock lock(mutex_);
      while (!stop_thread_)
      {
        lock.unlock();
        op_queue<operation> ops;
        run(true, ops);
        io_service_.post_deferred_completions(ops);
        lock.lock();
      }
    }
  }

  // Entry point for the select loop thread.
  static void call_run_thread(select_reactor* reactor)
  {
    if (Own_Thread)
    {
      reactor->run_thread();
    }
  }

  // Get the timeout value for the select call.
  timeval* get_timeout(timeval& tv)
  {
    // By default we will wait no longer than 5 minutes. This will ensure that
    // any changes to the system clock are detected after no longer than this.
    long usec = timer_queues_.wait_duration_usec(5 * 60 * 1000 * 1000);
    tv.tv_sec = usec / 1000000;
    tv.tv_usec = usec % 1000000;
    return &tv;
  }

  // Cancel all operations associated with the given descriptor. This function
  // does not acquire the select_reactor's mutex.
  void cancel_ops_unlocked(socket_type descriptor,
      const boost::system::error_code& ec)
  {
    bool need_interrupt = false;
    op_queue<operation> ops;
    for (int i = 0; i < max_ops; ++i)
      need_interrupt = op_queue_[i].cancel_operations(
          descriptor, ops, ec) || need_interrupt;
    io_service_.post_deferred_completions(ops);
    if (need_interrupt)
      interrupter_.interrupt();
  }

  // The io_service implementation used to post completions.
  io_service_impl& io_service_;

  // Mutex to protect access to internal data.
  boost::asio::detail::mutex mutex_;

  // The interrupter is used to break a blocking select call.
  select_interrupter interrupter_;

  // The queues of read, write and except operations.
  reactor_op_queue<socket_type> op_queue_[max_ops];

  // The timer queues.
  timer_queue_set timer_queues_;

  // Does the reactor loop thread need to stop.
  bool stop_thread_;

  // The thread that is running the reactor loop.
  boost::asio::detail::thread* thread_;

  // Whether the service has been shut down.
  bool shutdown_;
};

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
// -*- C++ -*-
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//                                   Jiao Lin
//                      California Institute of Technology
//                         (C) 2007 All Rights Reserved
//
// {LicenseText}
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//

#include <sstream>
#include <boost/python.hpp>
#include "mccomponents/kernels/sample/phonon/PeriodicDispersion_3D.h"

namespace wrap_mccomponents {

  void wrap_PeriodicDispersion_3D()
  {
    using namespace boost::python;
    typedef DANSE::phonon::AbstractDispersion_3D base_t;
    typedef DANSE::phonon::PeriodicDispersion_3D w_t;

    class_<w_t, bases<base_t>, boost::noncopyable>
      ("PeriodicDispersion_3D",
       init<const base_t &, const w_t::ReciprocalCell &>()
       [with_custodian_and_ward<1,2>() ]
       )
      ;

    class_<w_t::ReciprocalCell>
      ("ReciprocalCell", init<>())
      .def_readwrite( "b1", &w_t::ReciprocalCell::b1)
      .def_readwrite( "b2", &w_t::ReciprocalCell::b2)
      .def_readwrite( "b3", &w_t::ReciprocalCell::b3)
      ;
  }

}

// version
// $Id$

// End of file

max_stars_repo_name: mcvine/mcvine

max_issues_repo_name: mcvine/mcvine

max_forks_repo_name: mcvine/mcvine


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 Ripple Labs Inc.

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

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

#include <blocmatrix/ledger/ReadView.h>
#include <boost/optional.hpp>

namespace blocmatrix {

class Rules::Impl
{
private:
    std::unordered_set<uint256,
        hardened_hash<>> set_;
    boost::optional<uint256> digest_;
    std::unordered_set<uint256, beast::uhash<>> const& presets_;

public:
    explicit Impl(
            std::unordered_set<uint256, beast::uhash<>> const& presets)
        : presets_(presets)
    {
    }

    explicit Impl(
        DigestAwareReadView const& ledger,
            std::unordered_set<uint256, beast::uhash<>> const& presets)
        : presets_(presets)
    {
        auto const k = keylet::amendments();
        digest_ = ledger.digest(k.key);
        if (! digest_)
            return;
        auto const sle = ledger.read(k);
        if (! sle)
        {
            // LogicError() ?
            return;
        }

        for (auto const& item :
                sle->getFieldV256(sfAmendments))
            set_.insert(item);
    }

    bool
    enabled (uint256 const& feature) const
    {
        if (presets_.count(feature) > 0)
            return true;
        return set_.count(feature) > 0;
    }

    bool
    changed (DigestAwareReadView const& ledger) const
    {
        auto const digest =
            ledger.digest(keylet::amendments().key);
        if (! digest && ! digest_)
            return false;
        if (! digest || ! digest_)
            return true;
        return *digest != *digest_;
    }

    bool
    operator== (Impl const& other) const
    {
        if (! digest_ && ! other.digest_)
            return true;
        if (! digest_ || ! other.digest_)
            return false;
        return *digest_ == *other.digest_;
    }
};

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

Rules::Rules(
    DigestAwareReadView const& ledger,
        std::unordered_set<uint256, beast::uhash<>> const& presets)
    : impl_(std::make_shared<Impl>(ledger, presets))
{
}

Rules::Rules(std::unordered_set<uint256, beast::uhash<>> const& presets)
    : impl_(std::make_shared<Impl>(presets))
{
}

bool
Rules::enabled (uint256 const& id) const
{
    assert (impl_);
    return impl_->enabled(id);
}

bool
Rules::changed (DigestAwareReadView const& ledger) const
{
    assert (impl_);
    return impl_->changed(ledger);
}

bool
Rules::operator== (Rules const& other) const
{
    assert(impl_ && other.impl_);
    if (impl_.get() == other.impl_.get())
        return true;
    return *impl_ == *other.impl_;
}

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

ReadView::sles_type::sles_type(
        ReadView const& view)
    : ReadViewFwdRange(view)
{
}

auto
ReadView::sles_type::begin() const ->
    iterator
{
    return iterator(view_, view_->slesBegin());
}

auto
ReadView::sles_type::end() const ->
    iterator const&
{
    if (! end_)
        end_ = iterator(view_, view_->slesEnd());
    return *end_;
}

auto
ReadView::sles_type::upper_bound(key_type const& key) const ->
    iterator
{
    return iterator(view_, view_->slesUpperBound(key));
}

ReadView::txs_type::txs_type(
        ReadView const& view)
    : ReadViewFwdRange(view)
{
}

bool
ReadView::txs_type::empty() const
{
    return begin() == end();
}

auto
ReadView::txs_type::begin() const ->
    iterator
{
    return iterator(view_, view_->txsBegin());
}

auto
ReadView::txs_type::end() const ->
    iterator const&
{
    if (! end_)
        end_ = iterator(view_, view_->txsEnd());
    return *end_;
}

} // blocmatrix

max_stars_repo_name: ReddyArunreddy/blocmatrixd

max_issues_repo_name: ReddyArunreddy/blocmatrixd

max_forks_repo_name: ReddyArunreddy/blocmatrixd


text:
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2020 Osimis S.A., Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * In addition, as a special exception, the copyright holders of this
 * program give permission to link the code of its release with the
 * OpenSSL project's "OpenSSL" library (or with modified versions of it
 * that use the same license as the "OpenSSL" library), and distribute
 * the linked executables. You must obey the GNU General Public License
 * in all respects for all of the code used other than "OpenSSL". If you
 * modify file(s) with this exception, you may extend this exception to
 * your version of the file(s), but you are not obligated to do so. If
 * you do not wish to do so, delete this exception statement from your
 * version. If you delete this exception statement from all source files
 * in the program, then also delete it here.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/

#include "Database.h"

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

static OrthancPluginContext*  context_ = NULL;
static std::auto_ptr<OrthancPlugins::IDatabaseBackend>  backend_;

extern "C"
{
  ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* c)
  {
    context_ = c;
    OrthancPluginLogWarning(context_, "Sample plugin is initializing");

    /* Check the version of the Orthanc core */
    if (OrthancPluginCheckVersion(c) == 0)
    {
      char info[256];
      sprintf(info, "Your version of Orthanc (%s) must be above %d.%d.%d to run this plugin",
              c->orthancVersion,
              ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER,
              ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER,
              ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER);
      OrthancPluginLogError(context_, info);
      return -1;
    }

    std::string path = "SampleDatabase.sqlite";
    uint32_t argCount = OrthancPluginGetCommandLineArgumentsCount(context_);
    for (uint32_t i = 0; i < argCount; i++)
    {
      char* tmp = OrthancPluginGetCommandLineArgument(context_, i);
      std::string argument(tmp);
      OrthancPluginFreeString(context_, tmp);

      if (boost::starts_with(argument, "--database="))
      {
        path = argument.substr(11);
      }
    }

    std::string s = "Using the following SQLite database: " + path;
    OrthancPluginLogWarning(context_, s.c_str());

    backend_.reset(new Database(path));
    OrthancPlugins::DatabaseBackendAdapter::Register(context_, *backend_);

    return 0;
  }

  ORTHANC_PLUGINS_API void OrthancPluginFinalize()
  {
    backend_.reset(NULL);
  }

  ORTHANC_PLUGINS_API const char* OrthancPluginGetName()
  {
    return "sample-database";
  }

  ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion()
  {
    return "1.0";
  }
}


text:
#include "platform/UnitTestSupport.hpp"
#include "platform/Regex.hpp"

#include "test/Traits.hpp"
#include "test/Message.hpp"
#include "test/ProcessingFunctor.hpp"
#include "test/Scheduler.hpp"

#include <wield/logging/Log.hpp>
#include <wield/logging/LoggingPolicy.hpp>
#include <wield/platform/thread.hpp>

#include <cstddef>
#include <thread>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wshorten-64-to-32"
#pragma clang diagnostic ignored "-Wsign-conversion"
#pragma clang diagnostic ignored "-Wsign-compare"
#pragma clang diagnostic ignored "-Wswitch"
#pragma clang diagnostic ignored "-Wswitch-enum"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wdeprecated" // OSMemoryBarrier is deprecated in 10.12
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#pragma clang diagnostic pop

namespace {

    using namespace test;

    using Dispatcher = Traits::Dispatcher;
    using Message = Traits::Message;
    using Scheduler = Traits::Scheduler;
    using Stage = Traits::Stage;
    using Queue = Traits::Queue;

    // a timer callback
    void createMessage(
          const boost::system::error_code&
        , boost::asio::deadline_timer& timer
        , Dispatcher& dispatcher
        , Scheduler& scheduler
        , int& count)
    {
        if(count++ < 4)
        {
            // create and dispatch the message.
            Message::smartptr m = new TestMessage();
            dispatcher.dispatch(Stages::Stage1, *m);

            // reschedule the timer
            timer.expires_at(timer.expires_at() + boost::posix_time::milliseconds(250));
            timer.async_wait(
                boost::bind(createMessage, boost::asio::placeholders::error, boost::ref(timer), boost::ref(dispatcher), boost::ref(scheduler), count)
            );
        }
        else
        {
            scheduler.stop();
        }
    }

    TEST(exampleTimerDrivenEventSource)
    {
        Dispatcher d;
        Queue q;
        ProcessingFunctor f;
        Stage s(Stages::Stage1, d, q, f);

        Scheduler scheduler(d, std::thread::hardware_concurrency());

        std::thread producer([&d, &scheduler]()
        {
            boost::asio::io_service io;
            boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(250));
            boost::system::error_code error;
            int count = 0;

            timer.async_wait(
                boost::bind(createMessage, boost::asio::placeholders::error, boost::ref(timer), boost::ref(d), boost::ref(scheduler), count)
            );

            io.run();   // runs until there is no work left on asio
        });

        scheduler.start();

        producer.join();
        scheduler.join();

        // verify there were 4 recieved test messages.
        CHECK_EQUAL(4U, f.message1CallCount_);
    }
}


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * 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_DYN_LINK
#define BOOST_TEST_MODULE modules

#include <memory>

#define timer timer_class
#include <boost/test/unit_test.hpp>
#undef timer

#include <reversible/circuit.hpp>
#include <reversible/functions/add_gates.hpp>
#include <reversible/functions/circuit_from_string.hpp>
#include <reversible/functions/flatten_circuit.hpp>
#include <reversible/io/print_circuit.hpp>

using namespace cirkit;

BOOST_AUTO_TEST_CASE(simple)
{
  /* This is an implementation of the simple ripple-carry adder in Fig. 4 of quant-ph/0410184v1
   *
   * This implementation has no code for constants, garbage, and names.
   */
  const auto maj = circuit_from_string( "t2 c b, t2 c a, t3 a b c" );
  const auto uma = circuit_from_string( "t3 a b c, t2 c a, t2 a b" );

  const auto n = 6u; /* adder  width */

  circuit adder( 2u * n + 2u );
  adder.add_module( "maj", std::make_shared<circuit>( maj ) );
  adder.add_module( "uma", std::make_shared<circuit>( uma ) );

  for ( auto i = 0u; i < 6u; ++i )
  {
    const auto offset = 2u * i;
    insert_module( adder, i, "uma", gate::control_container(), {offset, offset + 1u, offset + 2u} );
    insert_module( adder, i, "maj", gate::control_container(), {offset, offset + 1u, offset + 2u} );
  }

  insert_cnot( adder, n, 2u * n, 2u * n + 1 );

  std::cout << adder << std::endl << std::endl;

  circuit flatten;
  flatten_circuit( adder, flatten );

  std::cout << flatten << std::endl;
}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Surface_mesh.h>

#include <boost/graph/kruskal_min_spanning_tree.hpp>

#include <iostream>
#include <fstream>
#include <list>

typedef CGAL::Simple_cartesian<double>                       Kernel;
typedef Kernel::Point_3                                      Point;
typedef CGAL::Surface_mesh<Point>                            Mesh;

typedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;
typedef boost::graph_traits<Mesh>::vertex_iterator   vertex_iterator;
typedef boost::graph_traits<Mesh>::edge_descriptor   edge_descriptor;

void kruskal(const Mesh& sm)
{
   // We use the default edge weight which is the squared length of the edge

  std::list<edge_descriptor> mst;

  boost::kruskal_minimum_spanning_tree(sm,
                                       std::back_inserter(mst));

  std::cout << "#VRML V2.0 utf8\n"
    "Shape {\n"
    "  appearance Appearance {\n"
    "    material Material { emissiveColor 1 0 0}}\n"
    "    geometry\n"
    "    IndexedLineSet {\n"
    "      coord Coordinate {\n"
    "        point [ \n";

  vertex_iterator vb,ve;
  for(boost::tie(vb, ve) = vertices(sm); vb!=ve; ++vb){
    std::cout <<  "        " << sm.point(*vb) << "\n";
  }

  std::cout << "        ]\n"
               "     }\n"
    "      coordIndex [\n";

  for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it)
  {
    edge_descriptor e = *it ;
    vertex_descriptor s = source(e,sm);
    vertex_descriptor t = target(e,sm);
    std::cout << "      " << s << ", " << t <<  ", -1\n";
  }

  std::cout << "]\n"
    "  }#IndexedLineSet\n"
    "}# Shape\n";
}

int main(int argc, char** argv)
{
  Mesh sm;
  if(argc < 2 || !CGAL::IO::read_polygon_mesh(argv[1], sm))
  {
    std::cerr << "Invalid input file." << std::endl;
    return EXIT_FAILURE;
  }

  kruskal(sm);

  return 0;
}

max_stars_repo_name: antoniospg/cgal

max_issues_repo_name: antoniospg/cgal

max_forks_repo_name: antoniospg/cgal


text:
/*

Copyright (c) 2005-2022, 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 BIDOMAINTISSUE_HPP_
#define BIDOMAINTISSUE_HPP_

#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>

#include <vector>
#include "UblasMatrixInclude.hpp"

#include "AbstractCardiacTissue.hpp"
#include "AbstractConductivityTensors.hpp"

/**
 * BidomainTissue class.
 *
 * See documentation for AbstractCardiacTissue. This class also has extracellular
 * conductivity tensors.
 *
 */
template <unsigned SPACE_DIM>
class BidomainTissue : public virtual AbstractCardiacTissue<SPACE_DIM>
{
private:
    friend class TestBidomainTissue; // for testing.

    /** Needed for serialization. */
    friend class boost::serialization::access;
    /**
     * Archive the member variables.
     *
     * @param archive
     * @param version
     */
    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        archive & boost::serialization::base_object<AbstractCardiacTissue<SPACE_DIM> >(*this);
        // Conductivity tensors are dealt with by HeartConfig, and the caches get regenerated.
    }

    /** Extracellular conductivity tensors. */
    AbstractConductivityTensors<SPACE_DIM,SPACE_DIM> *mpExtracellularConductivityTensors;

    /**
     * Convenience method for extracellular conductivity tensors creation
     */
    void CreateExtracellularConductivityTensors();

public:
    /**
     * Constructor sets up extracellular conductivity tensors.
     * @param pCellFactory factory to pass on to the base class constructor
     * @param exchangeHalos used in state-variable interpolation.  Defaults to false.
     */
    BidomainTissue(AbstractCardiacCellFactory<SPACE_DIM>* pCellFactory, bool exchangeHalos=false);

    /**
     * Archiving constructor
     *
     * @param pMesh  a pointer to the AbstractTetrahedral mesh (recovered from archive).
     */
    BidomainTissue(AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* pMesh);

    /**
     * Destructor
     */
    ~BidomainTissue();

    /**
     * @return the extracellular conductivity tensor for the given element
     * @param elementIndex  index of the element of interest
     */
     const c_matrix<double, SPACE_DIM, SPACE_DIM>& rGetExtracellularConductivityTensor(unsigned elementIndex);
};

// Declare identifier for the serializer
#include "SerializationExportWrapper.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(BidomainTissue)

namespace boost
{
namespace serialization
{

template<class Archive, unsigned SPACE_DIM>
inline void save_construct_data(
    Archive & ar, const BidomainTissue<SPACE_DIM> * t, const unsigned int file_version)
{
    const AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* p_mesh = t->pGetMesh();
    ar & p_mesh;

    // CreateIntracellularConductivityTensor() is called by constructor and uses HeartConfig. So make sure that it is
    // archived too (needs doing before construction so appears here instead of usual archive location).
    HeartConfig* p_config = HeartConfig::Instance();
    ar & *p_config;
    ar & p_config;
}

/**
 * Allow us to not need a default constructor, by specifying how Boost should
 * instantiate an instance (using existing constructor)
 */
template<class Archive, unsigned SPACE_DIM>
inline void load_construct_data(
    Archive & ar, BidomainTissue<SPACE_DIM> * t, const unsigned int file_version)
{
    AbstractTetrahedralMesh<SPACE_DIM,SPACE_DIM>* p_mesh;
    ar & p_mesh;

    // CreateIntracellularConductivityTensor() is called by AbstractCardiacTissue constructor and uses HeartConfig.
    // (as does CreateExtracellularConductivityTensor). So make sure that it is
    // archived too (needs doing before construction so appears here instead of usual archive location).
    HeartConfig* p_config = HeartConfig::Instance();
    ar & *p_config;
    ar & p_config;

    ::new(t)BidomainTissue<SPACE_DIM>(p_mesh);
}
}
} // namespace ...

#endif /*BIDOMAINTISSUE_HPP_*/

max_stars_repo_name: stu-l/Chaste

max_issues_repo_name: stu-l/Chaste

max_forks_repo_name: stu-l/Chaste