text:
/*******************************************************
 * Copyright (c) 2015-2019, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#pragma once

#include <fg/defines.h>
#include <fg/exception.h>
#include <err_common.hpp>
#pragma warning (push, 0)
#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>
#pragma warning (pop)
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>

#include <vector>
#include <iterator>
#include <unordered_map>
#include <utility>

#include <boost/functional/hash.hpp>

using CellIndex = std::tuple<int, int, int>;
using MatrixHashMap = std::unordered_map<CellIndex, glm::mat4>;

namespace std
{

template<> struct hash<CellIndex>
{
    std::size_t operator()(const CellIndex & key) const
    {
        size_t seed = 0;
        boost::hash_combine(seed, std::get<0>(key));
        boost::hash_combine(seed, std::get<1>(key));
        boost::hash_combine(seed, std::get<2>(key));
        return seed;
    }
};

}

typedef unsigned int    uint;
typedef unsigned short  ushort;
typedef unsigned char   uchar;

static const float BLACK[]   = {0.0f    , 0.0f    , 0.0f    , 1.0f};
static const float GRAY[]    = {0.85f   , 0.85f   , 0.85f   , 1.0f};
static const float WHITE[]   = {1.0f    , 1.0f    , 1.0f    , 1.0f};
static const float AF_BLUE[] = {0.0588f , 0.1137f , 0.2745f , 1.0f};
static const glm::mat4 IDENTITY(1.0f);

/* clamp the float to [0-1] range
 *
 * @pValue is the value to be clamped
 */
float clampTo01(const float pValue);

/* Convert forge type enum to OpenGL enum for GL_* type
 *
 * @pValue is the forge type enum
 *
 * @return GL_* typedef for data type
 */
gl::GLenum dtype2gl(const forge::dtype pValue);

/* Convert forge channel format enum to OpenGL enum to indicate color component layout
 *
 * @pValue is the forge type enum
 *
 * @return OpenGL enum indicating color component layout
 */
gl::GLenum ctype2gl(const forge::ChannelFormat pMode);

/* Convert forge channel format enum to OpenGL enum to indicate color component layout
 *
 * This function is used to group color component layout formats based
 * on number of components.
 *
 * @pValue is the forge type enum
 *
 * @return OpenGL enum indicating color component layout
 */
gl::GLenum ictype2gl(const forge::ChannelFormat pMode);

/* Create OpenGL buffer object
 *
 * @pTarget should be either GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER
 * @pSize is the size of the data in bytes
 * @pPtr is the pointer to host data. This can be NULL
 * @pUsage should be either GL_STATIC_DRAW or GL_DYNAMIC_DRAW
 *
 * @return OpenGL buffer object identifier
 */
template<typename T>
gl::GLuint createBuffer(gl::GLenum pTarget, size_t pSize, const T* pPtr, gl::GLenum pUsage)
{
    gl::GLuint retVal = 0;
    gl::glGenBuffers(1, &retVal);
    gl::glBindBuffer(pTarget, retVal);
    gl::glBufferData(pTarget, pSize*sizeof(T), pPtr, pUsage);
    gl::glBindBuffer(pTarget, 0);
    return retVal;
}

#if defined(OS_WIN)
/* Get the paths to font files in Windows system directory
 *
 * @pFiles is the output vector to which font file paths are appended to.
 * @pDir is the directory from which font files are looked up
 * @pExt is the target font file extension we are looking for.
 */
void getFontFilePaths(std::vector<std::string>& pFiles,
                      const std::string& pDir,
                      const std::string& pExt);
#endif

/* Convert float value to string with given precision
 *
 * @pVal is the float value whose string representation is requested.
 * @pFormat is the c-style printf format for floats
 *
 * @return is the string representation of input float value.
 */
std::string toString(const float pVal, const std::string pFormat);

/* Get a vertex buffer object for quad that spans the screen
 */
gl::GLuint screenQuadVBO(const int pWindowId);

/* Get a vertex array object that uses screenQuadVBO
 *
 * This vertex array object when bound and rendered, basically
 * draws a rectangle over the entire screen with standard
 * texture coordinates. Use of this vao would be as follows
 *
 *     `glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);`
 */
gl::GLuint screenQuadVAO(const int pWindowId);

/* Print glm::mat4 to std::cout stream */
std::ostream& operator<<(std::ostream&, const glm::mat4&);

/* get the point of the surface of track ball */
glm::vec3 trackballPoint(const float pX, const float pY,
                         const float pWidth, const float pHeight);

namespace forge
{
namespace opengl
{

typedef unsigned int    uint;
typedef unsigned short  ushort;
typedef unsigned char   uchar;

class ShaderProgram {
    private:
        gl::GLuint mVertex;
        gl::GLuint mFragment;
        gl::GLuint mGeometry;
        gl::GLuint mProgram;

    public:
        ShaderProgram(const char* pVertShaderSrc,
                      const char* pFragShaderSrc,
                      const char* pGeomShaderSrc=NULL);

        ~ShaderProgram();

        gl::GLuint getProgramId() const;

        gl::GLuint getUniformLocation(const char* pAttributeName);
        gl::GLuint getUniformBlockIndex(const char* pAttributeName);
        gl::GLuint getAttributeLocation(const char* pAttributeName);

        void bind();
        void unbind();
};

/* Basic renderable class
 *
 * Any object that is renderable to a window should inherit from this
 * class.
 */
class AbstractRenderable {
    protected:
        /* OpenGL buffer objects */
        gl::GLuint  mVBO;
        gl::GLuint  mCBO;
        gl::GLuint  mABO;
        size_t      mVBOSize;
        size_t      mCBOSize;
        size_t      mABOSize;
        gl::GLfloat mColor[4];
        gl::GLfloat mRange[6];
        std::string mLegend;
        bool        mIsPVCOn;
        bool        mIsPVAOn;

        AbstractRenderable():
            mVBO(0), mCBO(0), mABO(0),
            mVBOSize(0), mCBOSize(0), mABOSize(0),
            mIsPVCOn(0), mIsPVAOn(0)
        {
            mColor[0] = 0;
            mColor[1] = 0;
            mColor[2] = 0;
            mColor[3] = 0;

            mRange[0] = 0;
            mRange[1] = 0;
            mRange[2] = 0;
            mRange[3] = 0;
            mRange[4] = 0;
            mRange[5] = 0;
        }

    public:
        /* Getter functions for OpenGL buffer objects
         * identifiers and their size in bytes
         *
         *  vbo is for vertices
         *  cbo is for colors of those vertices
         *  abo is for alpha values for those vertices
         */
        gl::GLuint vbo() const { return mVBO; }
        gl::GLuint cbo() { mIsPVCOn = true; return mCBO; }
        gl::GLuint abo() { mIsPVAOn = true; return mABO; }
        size_t vboSize() const { return mVBOSize; }
        size_t cboSize() const { return mCBOSize; }
        size_t aboSize() const { return mABOSize; }

        /* Set color for rendering
         */
        void setColor(const float pRed, const float pGreen,
                      const float pBlue, const float pAlpha) {
            mColor[0] = clampTo01(pRed);
            mColor[1] = clampTo01(pGreen);
            mColor[2] = clampTo01(pBlue);
            mColor[3] = clampTo01(pAlpha);
        }

        /* Get renderable solid color
         */
        void getColor(float& pRed, float& pGreen, float& pBlue, float& pAlpha) {
            pRed    = mColor[0];
            pGreen  = mColor[1];
            pBlue   = mColor[2];
            pAlpha  = mColor[3];
        }

        /* Set legend for rendering
         */
        void setLegend(const char* pLegend) {
            mLegend = std::string(pLegend);
        }

        /* Get legend string
         */
        const std::string& legend() const {
            return mLegend;
        }

        /* Set 3d world coordinate ranges
         *
         * This method is mostly used for charts and related renderables
         */
        void setRanges(const float pMinX, const float pMaxX,
                       const float pMinY, const float pMaxY,
                       const float pMinZ, const float pMaxZ) {
            mRange[0] = pMinX; mRange[1] = pMaxX;
            mRange[2] = pMinY; mRange[3] = pMaxY;
            mRange[4] = pMinZ; mRange[5] = pMaxZ;
        }

        /* virtual function to set colormap, a derviced class might
         * use it or ignore it if it doesnt have a need for color maps.
         */
        virtual void setColorMapUBOParams(const gl::GLuint pUBO, const gl::GLuint pSize) {
        }

        /* render is a pure virtual function.
         *
         * @pWindowId is the window identifier
         * @pX is the X coordinate at which the currently bound viewport begins.
         * @pX is the Y coordinate at which the currently bound viewport begins.
         * @pViewPortWidth is the width of the currently bound viewport.
         * @pViewPortHeight is the height of the currently bound viewport.
         *
         * Any concrete class that inherits AbstractRenderable class needs to
         * implement this method to render their OpenGL objects to
         * the currently bound viewport of the Window bearing identifier pWindowId.
         *
         * @return nothing.
         */
        virtual void render(const int pWindowId,
                            const int pX, const int pY, const int pVPW, const int pVPH,
                            const glm::mat4 &pView, const glm::mat4 &pOrient) = 0;
};

}
}

max_stars_repo_name: FloopCZ/forge

max_issues_repo_name: FloopCZ/forge

max_forks_repo_name: FloopCZ/forge


text:
#ifndef N2O_DETAIL_TRANSLATE_EXCEPTION_INCLUDED
#define N2O_DETAIL_TRANSLATE_EXCEPTION_INCLUDED

#include <boost/call_traits.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/function/function0.hpp>

#include <n2o/detail/exception_handler.hpp>

namespace n2o { namespace detail {

template <typename ExceptionType, typename Translate>
struct translate_exception {
    typedef typename boost::add_reference<
        typename boost::add_const<ExceptionType>::type
    >::type exception_cref;

    inline
    bool
    operator()(
          exception_handler const& handler
        , boost::function0<void> const& f
        , typename boost::call_traits<Translate>::param_type translate) const
    {
        try {
            return handler(f);
        } catch (exception_cref ex) {
            translate(ex);
            return true;
        }
    }
};

}} // end of namespace n2o::detail

#endif // N2O_DETAIL_TRANSLATE_EXCEPTION_INCLUDED

ext: hpp


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

#include <cstddef>
#include <iomanip>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "BStr.hh"

#include "NGLM.hpp"
#include "GLMFormat.hpp"

#include "NGeoTestConfig.hpp"

#include "PLOG.hh"

//    "pmtpath=$IDPATH_DPIB_PMT/GMergedMesh/0_"

// TODO: OpticksResource::getBasePath("dpib/GMergedMesh/0")
//       is now used by GPmtLib ... so no need for pmtpath below ?
//

const char* NGeoTestConfig::DEFAULT_CONFIG =
    "mode=PmtInBox_"
    "pmtpath=$OPTICKSINSTALLPREFIX/opticksdata/export/dpib/GMergedMesh/0_"
    "control=1,0,0,0_"
    "analytic=1_"
    "outerfirst=1_"
    "node=box_"
    "boundary=Rock/NONE/perfectAbsorbSurface/MineralOil_"
    "parameters=0,0,0,300_"
    ;

const char* NGeoTestConfig::MODE_ = "mode";
const char* NGeoTestConfig::FRAME_ = "frame";
const char* NGeoTestConfig::BOUNDARY_ = "boundary";
const char* NGeoTestConfig::PARAMETERS_ = "parameters";
const char* NGeoTestConfig::NODE_ = "node";
const char* NGeoTestConfig::ANALYTIC_ = "analytic";
const char* NGeoTestConfig::DEBUG_ = "debug";
const char* NGeoTestConfig::CONTROL_ = "control";
const char* NGeoTestConfig::PMTPATH_ = "pmtpath";
const char* NGeoTestConfig::TRANSFORM_ = "transform";
const char* NGeoTestConfig::CSGPATH_ = "csgpath";
const char* NGeoTestConfig::OFFSETS_ = "offsets";
const char* NGeoTestConfig::NAME_ = "name";
const char* NGeoTestConfig::OUTERFIRST_ = "outerfirst";

const char* NGeoTestConfig::AUTOCONTAINER_ = "autocontainer";
const char* NGeoTestConfig::AUTOOBJECT_ = "autoobject";
const char* NGeoTestConfig::AUTOEMITCONFIG_ = "autoemitconfig";
const char* NGeoTestConfig::AUTOSEQMAP_ = "autoseqmap";

NGeoTestConfig::NGeoTestConfig(const char* config)
    :
    m_config(NULL),
    m_mode(NULL),
    m_pmtpath(NULL),
    m_csgpath(NULL),
    m_name(NULL),
    m_autocontainer(NULL),
    m_autoobject(NULL),
    m_autoemitconfig(NULL),
    m_autoseqmap(NULL),
    m_frame(0,0,0,0),
    m_analytic(0,0,0,0),
    m_outerfirst(1,0,0,0),
    m_debug(1.f,0.f,0.f,0.f),
    m_control(0,0,0,0)
{
    init(config);
}

std::vector<std::pair<std::string, std::string> >& NGeoTestConfig::getCfg()
{
    return m_cfg ;
}

unsigned NGeoTestConfig::getNumBoundaries()
{
    return m_boundaries.size();
}
unsigned NGeoTestConfig::getNumParameters()
{
    return m_parameters.size() ;
}
unsigned NGeoTestConfig::getNumNodes()
{
    return m_nodes.size() ;
}
unsigned NGeoTestConfig::getNumTransforms()
{
    return m_transforms.size() ;
}

bool NGeoTestConfig::getAnalytic()
{
    bool analytic = m_analytic.x > 0 ;
    return analytic ;
}

bool NGeoTestConfig::getOuterFirst()
{
    return m_outerfirst.x > 0 ;
}

bool NGeoTestConfig::isNCSG()
{
    return m_csgpath != NULL  ;
}
bool NGeoTestConfig::isPmtInBox()
{
    return strcmp(m_mode, "PmtInBox") == 0 ;
}
bool NGeoTestConfig::isBoxInBox()
{
    return strcmp(m_mode, "BoxInBox") == 0 ;
}

const char* NGeoTestConfig::getMode()
{
    return m_mode ;
}
const char* NGeoTestConfig::getPmtPath()
{
    return m_pmtpath ;
}
const char* NGeoTestConfig::getCSGPath()
{
    return m_csgpath ;
}
const char* NGeoTestConfig::getName()
{
    return m_name ;
}

int NGeoTestConfig::getVerbosity()
{
    return m_control.x  ;
}

void NGeoTestConfig::init(const char* config)
{
    configure(config);
}

void NGeoTestConfig::configure(const char* config)
{
    LOG(debug) << "NGeoTestConfig::configure" ;
    m_config = config ? strdup(config) : DEFAULT_CONFIG ;

    m_cfg = BStr::ekv_split(m_config,'_',"="); // element-delim, keyval-delim

    for(std::vector<KV>::const_iterator it=m_cfg.begin() ; it!=m_cfg.end() ; it++)
    {
        LOG(debug)
                  << std::setw(20) << it->first
                  << " : "
                  << it->second
                  ;

        Arg_t arg = getArg(it->first.c_str()) ;

        set(arg, it->second.c_str());
        if(arg == NODE)
        {
            set(TRANSFORM, NULL); // default transform for each "shape" is identity  ("shape" in becoming "node")
        }
    }
}

NGeoTestConfig::Arg_t NGeoTestConfig::getArg(const char* k)
{
    Arg_t arg = UNRECOGNIZED ;
    if(     strcmp(k,MODE_)==0)       arg = MODE ;
    else if(strcmp(k,FRAME_)==0)      arg = FRAME ;
    else if(strcmp(k,BOUNDARY_)==0)   arg = BOUNDARY ;
    else if(strcmp(k,PARAMETERS_)==0) arg = PARAMETERS ;
    else if(strcmp(k,NODE_)==0)       arg = NODE ;
    else if(strcmp(k,ANALYTIC_)==0)   arg = ANALYTIC ;
    else if(strcmp(k,DEBUG_)==0)      arg = DEBUG ;
    else if(strcmp(k,CONTROL_)==0)    arg = CONTROL ;
    else if(strcmp(k,PMTPATH_)==0)    arg = PMTPATH ;
    else if(strcmp(k,TRANSFORM_)==0)  arg = TRANSFORM ;
    else if(strcmp(k,CSGPATH_)==0)    arg = CSGPATH ;
    else if(strcmp(k,OFFSETS_)==0)    arg = OFFSETS ;
    else if(strcmp(k,NAME_)==0)       arg = NAME ;
    else if(strcmp(k,OUTERFIRST_)==0)  arg = OUTERFIRST ;
    else if(strcmp(k,AUTOCONTAINER_)==0)  arg = AUTOCONTAINER ;
    else if(strcmp(k,AUTOOBJECT_)==0)  arg = AUTOOBJECT ;
    else if(strcmp(k,AUTOEMITCONFIG_)==0)  arg = AUTOEMITCONFIG ;
    else if(strcmp(k,AUTOSEQMAP_)==0)  arg = AUTOSEQMAP ;

    if(arg == UNRECOGNIZED)
    {
        LOG(warning) << "NGeoTestConfig::getArg UNRECOGNIZED arg " << k ;
    }

    return arg ;
}

void NGeoTestConfig::set(Arg_t arg, const char* s)
{
    switch(arg)
    {
        case MODE           : setMode(s)           ;break;
        case FRAME          : setFrame(s)          ;break;
        case BOUNDARY       : addBoundary(s)       ;break;
        case PARAMETERS     : addParameters(s)     ;break;
        case NODE           : addNode(s)           ;break;
        case ANALYTIC       : setAnalytic(s)       ;break;
        case DEBUG          : setDebug(s)          ;break;
        case CONTROL        : setControl(s)        ;break;
        case PMTPATH        : setPmtPath(s)        ;break;
        case TRANSFORM      : addTransform(s)      ;break;
        case CSGPATH        : setCsgPath(s)        ;break;
        case OFFSETS        : setOffsets(s)        ;break;
        case NAME           : setName(s)           ;break;
        case OUTERFIRST     : setOuterFirst(s)     ;break;
        case AUTOCONTAINER  : setAutoContainer(s)  ;break;
        case AUTOOBJECT     : setAutoObject(s)     ;break;
        case AUTOEMITCONFIG : setAutoEmitConfig(s)     ;break;
        case AUTOSEQMAP     : setAutoSeqMap(s)     ;break;
        case UNRECOGNIZED   :
             LOG(warning) << "NGeoTestConfig::set WARNING ignoring unrecognized parameter " << s  ;
    }
}

unsigned NGeoTestConfig::getNumElements()
{
    unsigned nbnd = getNumBoundaries();
    unsigned nnod = getNumNodes();
    unsigned npar = getNumParameters();
    unsigned ntra = getNumTransforms();

    bool equal = nbnd == npar && nbnd == nnod && ntra == npar ;

    if(!equal)
    {
    LOG(fatal) << "NGeoTestConfig::getNumElements"
               << " ELEMENT MISMATCH IN TEST GEOMETRY CONFIGURATION "
               << " nbnd (boundaries) " << nbnd
               << " nnod (nodes) " << nnod
               << " npar (parameters) " << npar
               << " ntra (transforms) " << ntra
               ;
    }

    //assert( equal && "need equal number of boundaries, parameters, transforms and nodes");
    //assert(nbnd > 0);
    return equal ? nbnd : 0u ;
}

void NGeoTestConfig::dump(const char* msg)
{
    unsigned int n = getNumElements();
    LOG(info) << msg
              << " config " << m_config
              << " mode " << m_mode
              << " nelem " << n
              ;

    for(unsigned int i=0 ; i < n ; i++)
    {
        //char csgChar = getNode(i) ;
        OpticksCSG_t type = getTypeCode(i) ;
        const char* spec = getBoundary(i);
        glm::vec4 param = getParameters(i);

        std::cout
                  << " i " << std::setw(2) << i
                  << " type " << std::setw(2) << type
                  << " csgName " << std::setw(15) << CSG::Name(type)
                  << " param " << std::setw(50) << gformat(param)
                  << " spec " << std::setw(30) << spec
                  << std::endl
                  ;
    }
}

void NGeoTestConfig::setMode(const char* s)
{
    m_mode = strdup(s);
}
void NGeoTestConfig::setPmtPath(const char* s)
{
    m_pmtpath = strdup(s);
}
void NGeoTestConfig::setCsgPath(const char* s)
{
    m_csgpath = strdup(s);
}
void NGeoTestConfig::setName(const char* s)
{
    m_name = strdup(s);
}

void NGeoTestConfig::setOffsets(const char* s)
{
    BStr::usplit(m_offsets, s, ',' );
}
unsigned NGeoTestConfig::getNumOffsets()
{
    return m_offsets.size();
}
unsigned NGeoTestConfig::getOffset(unsigned idx)
{
    assert(idx < m_offsets.size());
    return m_offsets[idx] ;
}

bool NGeoTestConfig::isStartOfOptiXPrimitive(unsigned nodeIdx )
{
    return std::find(m_offsets.begin(), m_offsets.end(), nodeIdx) != m_offsets.end() ;
}

void NGeoTestConfig::setFrame(const char* s)
{
    std::string ss(s);
    m_frame = givec4(ss);
}
void NGeoTestConfig::setAnalytic(const char* s)
{
    std::string ss(s);
    m_analytic = givec4(ss);
}

void NGeoTestConfig::setOuterFirst(const char* s)
{
    std::string ss(s);
    m_outerfirst = givec4(ss);
}

void NGeoTestConfig::setAutoContainer(const char* s)
{
    m_autocontainer = strdup(s) ;
}
void NGeoTestConfig::setAutoObject(const char* s)
{
    m_autoobject = strdup(s) ;
}
void NGeoTestConfig::setAutoEmitConfig(const char* s)
{
    m_autoemitconfig = strdup(s) ;
}
void NGeoTestConfig::setAutoSeqMap(const char* s)
{
    m_autoseqmap = strdup(s) ;
}

const char* NGeoTestConfig::getAutoContainer() const
{
    return m_autocontainer ;
}
const char* NGeoTestConfig::getAutoObject() const
{
    return m_autoobject ;
}
const char* NGeoTestConfig::getAutoEmitConfig() const
{
    return m_autoemitconfig ;
}
const char* NGeoTestConfig::getAutoSeqMap() const
{
    return m_autoseqmap ;
}

void NGeoTestConfig::setDebug(const char* s)
{
    std::string ss(s);
    m_debug = gvec4(ss);
}

void NGeoTestConfig::setControl(const char* s)
{
    std::string ss(s);
    m_control = givec4(ss);
}

void NGeoTestConfig::addParameters(const char* s)
{
    std::string ss(s);
    m_parameters.push_back(gvec4(ss));
}

void NGeoTestConfig::addTransform(const char* s)
{
    std::string ss(s == NULL ? "" : s);

    // when adding non-default pop_back first to replace the identity default
    if(!ss.empty() && m_transforms.size() > 0)
    {
        m_transforms.pop_back();
    }

    m_transforms.push_back(gmat4(ss));
}

void NGeoTestConfig::addBoundary(const char* s)
{
    m_boundaries.push_back(s);
}

void NGeoTestConfig::addNode(const char* s)
{
    m_nodes.push_back(s);
}

glm::vec4 NGeoTestConfig::getParameters(unsigned int i)
{
    unsigned int npars = m_parameters.size();
    assert( i < npars ) ;
    glm::vec4 param = m_parameters[i] ;
    return param ;
}

glm::mat4 NGeoTestConfig::getTransform(unsigned int i)
{
    unsigned int ntra = m_transforms.size();
    assert( i < ntra ) ;
    glm::mat4 trans = m_transforms[i] ;
    return trans ;
}

/*
char NGeoTestConfig::getNode(unsigned int i)
{
    assert( i < m_nodes.size() );
    char nodecode = CSGChar(m_nodes[i].c_str());
    return nodecode ;
}
*/

OpticksCSG_t NGeoTestConfig::getTypeCode(unsigned int i)
{
    assert( i < m_nodes.size() );
    return CSG::TypeCode(m_nodes[i].c_str());
}

std::string NGeoTestConfig::getNodeString(unsigned int i)
{
    assert( i < m_nodes.size() );
    return m_nodes[i] ;
}

const char* NGeoTestConfig::getBoundary(unsigned int i)
{
    assert( i < m_boundaries.size() );
    const char* spec = m_boundaries[i].c_str() ;
    return spec ;
}

ext: cpp

max_stars_repo_name: hanswenzel/opticks

max_issues_repo_name: hanswenzel/opticks

max_forks_repo_name: hanswenzel/opticks


text:
// --------------------------------------------------------------------------
//                   OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2017.
//
// This software is released under a three-clause BSD license:
//  * 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 any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Witold Wolski, Hannes Roest, $
// --------------------------------------------------------------------------

#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/TraMLFile.h>

#include <boost/assign/std/vector.hpp>
#include <boost/assign/list_of.hpp>

///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
///////////////////////////

using namespace OpenMS;
using namespace std;

START_TEST(OpenSwathDataAccessHelper, "$Id$")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

OpenSwathDataAccessHelper* ptr = nullptr;
OpenSwathDataAccessHelper* nullPointer = nullptr;

START_SECTION(OpenSwathDataAccessHelper())
{
  ptr = new OpenSwathDataAccessHelper();
  TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION

START_SECTION(~OpenSwathDataAccessHelper())
{
  delete ptr;
}
END_SECTION

START_SECTION(OpenSwathDataAccessHelper::convertToSpectrumPtr(sptr))
{

  MSSpectrum sptr,omsptr;
  Peak1D p1;
  p1.setIntensity(1.0f);
  p1.setMZ(2.0);

  Peak1D p2;
  p2.setIntensity(2.0f);
  p2.setMZ(10.0);

  Peak1D p3;
  p3.setIntensity(3.0f);
  p3.setMZ(30.0);

  TEST_STRING_EQUAL(sptr.getName(), "")
  sptr.setName("my_fancy_name");
  sptr.push_back(p1);
  sptr.push_back(p2);
  sptr.push_back(p3);
  OpenSwath::SpectrumPtr p = OpenSwathDataAccessHelper::convertToSpectrumPtr(sptr);
  OpenSwathDataAccessHelper::convertToOpenMSSpectrum(p,omsptr);
  TEST_REAL_SIMILAR(p->getMZArray()->data[0],2.0);
  TEST_REAL_SIMILAR(p->getMZArray()->data[1],10.0);
  TEST_REAL_SIMILAR(p->getMZArray()->data[2],30.0);

  TEST_REAL_SIMILAR(p->getIntensityArray()->data[0],1.0f);
  TEST_REAL_SIMILAR(p->getIntensityArray()->data[1],2.0f);
  TEST_REAL_SIMILAR(p->getIntensityArray()->data[2],3.0f);
}
END_SECTION

START_SECTION(OpenSwathDataAccessHelper::convertToOpenMSChromatogram(cptr, chromatogram))
{
  //void OpenSwathDataAccessHelper::convertToOpenMSChromatogram(OpenMS::MSChromatogram & chromatogram,
  //                                                          const OpenSwath::ChromatogramPtr cptr)
  OpenSwath::ChromatogramPtr cptr(new OpenSwath::Chromatogram());
  cptr->getTimeArray()->data.push_back(1.0);
  cptr->getTimeArray()->data.push_back(2.0);
  cptr->getTimeArray()->data.push_back(3.0);
  cptr->getTimeArray()->data.push_back(4.0);

  cptr->getIntensityArray()->data.push_back(4.0);
  cptr->getIntensityArray()->data.push_back(3.0);
  cptr->getIntensityArray()->data.push_back(2.0);
  cptr->getIntensityArray()->data.push_back(1.0);

  MSChromatogram chromatogram;
  OpenSwathDataAccessHelper::convertToOpenMSChromatogram(cptr, chromatogram);

  TEST_REAL_SIMILAR(chromatogram[0].getRT(),1.);
  TEST_REAL_SIMILAR(chromatogram[0].getIntensity(),4.);
  TEST_REAL_SIMILAR(chromatogram[1].getRT(),2.);
  TEST_REAL_SIMILAR(chromatogram[1].getIntensity(),3.);
  TEST_REAL_SIMILAR(chromatogram[2].getRT(),3.);
  TEST_REAL_SIMILAR(chromatogram[2].getIntensity(),2.);

}
END_SECTION

START_SECTION(convertToOpenMSSpectrum(spectrum,sptr))
{
  OpenSwath::SpectrumPtr cptr(new OpenSwath::Spectrum());
  cptr->getMZArray()->data.push_back(1.0);
  cptr->getMZArray()->data.push_back(2.0);
  cptr->getMZArray()->data.push_back(3.0);
  cptr->getMZArray()->data.push_back(4.0);

  cptr->getIntensityArray()->data.push_back(4.0);
  cptr->getIntensityArray()->data.push_back(3.0);
  cptr->getIntensityArray()->data.push_back(2.0);
  cptr->getIntensityArray()->data.push_back(1.0);

  MSSpectrum spectrum;
  OpenSwathDataAccessHelper::convertToOpenMSSpectrum(cptr, spectrum);

  TEST_REAL_SIMILAR(spectrum[0].getMZ(),1.);
  TEST_REAL_SIMILAR(spectrum[0].getIntensity(),4.);
  TEST_REAL_SIMILAR(spectrum[1].getMZ(),2.);
  TEST_REAL_SIMILAR(spectrum[1].getIntensity(),3.);
  TEST_REAL_SIMILAR(spectrum[2].getMZ(),3.);
  TEST_REAL_SIMILAR(spectrum[2].getIntensity(),2.);
}
END_SECTION

START_SECTION(convertTargetedExp(transition_exp_, transition_exp))
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST


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

#include <gtest/gtest.h>
#include "AnalysisFixture.hpp"

#include "../RubyMeasure.hpp"

#include "../../ruleset/OSArgument.hpp"

#include "../../utilities/bcl/BCLMeasure.hpp"

#include "../../utilities/core/Containers.hpp"
#include "../../utilities/core/FileReference.hpp"

#include <OpenStudio.hxx>
#include <resources.hxx>

#include <boost/filesystem.hpp>

using namespace openstudio;
using namespace openstudio::ruleset;
using namespace openstudio::analysis;

TEST_F(AnalysisFixture, RubyMeasure_FreeFormScript) {
  // construct
  openstudio::path scriptPath = toPath("myCrazyScript.rb");
  RubyMeasure measure(scriptPath,
                      FileReferenceType::OSM,
                      FileReferenceType::OSM);
  EXPECT_EQ(FileReferenceType(FileReferenceType::OSM),measure.inputFileType());
  EXPECT_EQ(FileReferenceType(FileReferenceType::OSM),measure.outputFileType());
  EXPECT_FALSE(measure.usesBCLMeasure());
  EXPECT_ANY_THROW(measure.measure());
  EXPECT_ANY_THROW(measure.measureDirectory());
  EXPECT_ANY_THROW(measure.measureUUID());
  EXPECT_ANY_THROW(measure.measureVersionUUID());
  FileReference scriptReference = measure.perturbationScript();
  EXPECT_EQ(scriptPath,scriptReference.path().filename());
  EXPECT_EQ(boost::filesystem::system_complete(scriptPath),scriptReference.path());
  EXPECT_EQ(FileReferenceType(FileReferenceType::RB),scriptReference.fileType());
  EXPECT_TRUE(measure.arguments().empty());
  EXPECT_FALSE(measure.isUserScript());
  EXPECT_FALSE(measure.hasIncompleteArguments());

  // add arguments the old way
  measure.addArgument("verbose");
  measure.addArgument("numRandomChanges","10");

  // verify status of arguments
  EXPECT_EQ(2u,measure.arguments().size());
  EXPECT_TRUE(measure.hasIncompleteArguments()); // name-only argument has no value
  OSArgumentVector incompleteArgs = measure.incompleteArguments();
  ASSERT_EQ(1u,incompleteArgs.size());
  EXPECT_EQ("verbose",incompleteArgs[0].name());
}

TEST_F(AnalysisFixture, RubyMeasure_FreeStandingUserScript) {
  // construct
  openstudio::path scriptPath = toPath("myUserScript.rb");
  RubyMeasure measure(scriptPath,
                                FileReferenceType::IDF,
                                FileReferenceType::IDF,
                                true);
  EXPECT_EQ(FileReferenceType(FileReferenceType::IDF),measure.inputFileType());
  EXPECT_EQ(FileReferenceType(FileReferenceType::IDF),measure.outputFileType());
  EXPECT_FALSE(measure.usesBCLMeasure());
  EXPECT_ANY_THROW(measure.measure());
  EXPECT_ANY_THROW(measure.measureDirectory());
  EXPECT_ANY_THROW(measure.measureUUID());
  EXPECT_ANY_THROW(measure.measureVersionUUID());
  FileReference scriptReference = measure.perturbationScript();
  EXPECT_EQ(scriptPath,scriptReference.path().filename());
  EXPECT_EQ(boost::filesystem::system_complete(scriptPath),scriptReference.path());
  EXPECT_EQ(FileReferenceType(FileReferenceType::RB),scriptReference.fileType());
  EXPECT_TRUE(measure.arguments().empty());
  EXPECT_TRUE(measure.isUserScript());
  EXPECT_FALSE(measure.hasIncompleteArguments());

  // add arguments to fill in
  OSArgument numBoilers = OSArgument::makeIntegerArgument("numBoilers");
  OSArgument numChillers = OSArgument::makeIntegerArgument("numChillers");
  StringVector choices;
  choices.push_back("parallel");
  choices.push_back("series");
  OSArgument topology = OSArgument::makeChoiceArgument("topology",choices);
  EXPECT_TRUE(topology.setDefaultValue("parallel"));
  measure.setArgument(numBoilers);
  measure.setArgument(numChillers);
  measure.setArgument(topology);

  // verify that arguments are incomplete
  EXPECT_EQ(3u,measure.arguments().size());
  EXPECT_EQ(2u,measure.incompleteArguments().size());
  EXPECT_TRUE(measure.hasIncompleteArguments());

  // set to different script and verify that arguments cleared
  scriptPath = toPath("myOtherUserScript.rb");
  measure.setPerturbationScript(scriptPath,
                                FileReferenceType::OSM,
                                FileReferenceType::OSM,
                                true);
  EXPECT_EQ(FileReferenceType(FileReferenceType::OSM),measure.inputFileType());
  EXPECT_EQ(FileReferenceType(FileReferenceType::OSM),measure.outputFileType());
  scriptReference = measure.perturbationScript();
  EXPECT_EQ(scriptPath,scriptReference.path().filename());
  EXPECT_TRUE(measure.arguments().empty());
  EXPECT_TRUE(measure.isUserScript());
  EXPECT_FALSE(measure.hasIncompleteArguments());
}

TEST_F(AnalysisFixture, RubyMeasure_BCLMeasure) {
  // construct
  openstudio::path measuresPath = resourcesPath() / toPath("/utilities/BCL/Measures/v2");
  openstudio::path dir = measuresPath / toPath("SetWindowToWallRatioByFacade");
  ASSERT_TRUE(BCLMeasure::load(dir));
  BCLMeasure bclMeasure = BCLMeasure::load(dir).get();
  RubyMeasure measure(bclMeasure);
  EXPECT_TRUE(measure.usesBCLMeasure());
  ASSERT_TRUE(measure.bclMeasure());
  EXPECT_TRUE(measure.bclMeasure().get() == bclMeasure);
  EXPECT_EQ(dir,measure.bclMeasureDirectory());
  EXPECT_TRUE(bclMeasure.uuid() == measure.bclMeasureUUID());
  EXPECT_TRUE(bclMeasure.versionUUID() == measure.bclMeasureVersionUUID());
  EXPECT_ANY_THROW(measure.perturbationScript());
  // isUserScript value is ignored in this case
  EXPECT_TRUE(measure.arguments().empty());
  EXPECT_FALSE(measure.hasIncompleteArguments());

  // add arguments to fill in
  OSArgumentVector args;
  args.push_back(OSArgument::makeDoubleArgument("wwr"));
  args.push_back(OSArgument::makeDoubleArgument("sillHeight"));
  measure.setArguments(args);

  // verify that arguments are incomplete
  EXPECT_EQ(2u,measure.incompleteArguments().size());

  // fill in argument values
  OSArgument arg = OSArgument::makeDoubleArgument("wwr");
  EXPECT_TRUE(arg.setValue(0.8));
  measure.setArgument(arg);
  EXPECT_EQ(2u,measure.arguments().size());
  EXPECT_EQ(1u,measure.incompleteArguments().size());
  EXPECT_TRUE(measure.hasIncompleteArguments());
  arg = OSArgument::makeDoubleArgument("sillHeight");
  arg.setValue("0.1");
  measure.setArgument(arg);
  EXPECT_EQ(2u,measure.arguments().size());
  EXPECT_EQ(0u,measure.incompleteArguments().size());
  EXPECT_FALSE(measure.hasIncompleteArguments());

  // update measure
  openstudio::path tempDir = measuresPath / toPath(toString(createUUID()));
  {
    BCLMeasure newVersion = bclMeasure.clone(tempDir).get();
    newVersion.setDescription("Window to wall ratio by wwr and offset.");
    newVersion.save();
    EXPECT_TRUE(newVersion.uuid() == bclMeasure.uuid());
    EXPECT_FALSE(newVersion.versionUUID() == bclMeasure.versionUUID());
    args.pop_back();
    args.push_back(OSArgument::makeDoubleArgument("offset"));
    measure.updateMeasure(newVersion,args);
    EXPECT_TRUE(measure.usesBCLMeasure());
    ASSERT_TRUE(measure.bclMeasure());
    EXPECT_TRUE(measure.bclMeasure().get() == newVersion);
    EXPECT_EQ(tempDir,measure.bclMeasureDirectory());
    EXPECT_TRUE(newVersion.uuid() == measure.bclMeasureUUID());
    EXPECT_TRUE(newVersion.versionUUID() == measure.bclMeasureVersionUUID());
    EXPECT_ANY_THROW(measure.perturbationScript());

    // verify that arguments updated correctly, values retained
    EXPECT_EQ(2u,measure.arguments().size());
    ASSERT_EQ(1u,measure.incompleteArguments().size());
    EXPECT_TRUE(measure.hasIncompleteArguments());
    EXPECT_EQ("offset",measure.incompleteArguments()[0].name());
    EXPECT_EQ("wwr",measure.arguments()[0].name());
    EXPECT_EQ(0.8,measure.arguments()[0].valueAsDouble());

    // set measure and verify that arguments cleared
    measure.setMeasure(newVersion); // always goes through setting motions, even if same
    EXPECT_TRUE(measure.usesBCLMeasure());
    ASSERT_TRUE(measure.bclMeasure());
    EXPECT_TRUE(measure.bclMeasure().get() == newVersion);
    EXPECT_EQ(tempDir,measure.bclMeasureDirectory());
    EXPECT_TRUE(newVersion.uuid() == measure.bclMeasureUUID());
    EXPECT_TRUE(newVersion.versionUUID() == measure.bclMeasureVersionUUID());
    EXPECT_ANY_THROW(measure.perturbationScript());
    // isUserScript value is ignored in this case
    EXPECT_TRUE(measure.arguments().empty());
    EXPECT_FALSE(measure.hasIncompleteArguments());
  }
  boost::filesystem::remove_all(tempDir);
}


text:
/**
 * Copyright (c) 2018 Melown Technologies SE
 *
 * 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.
 *
 * 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 pysupport_converters_hpp_included_
#define pysupport_converters_hpp_included_

#include <new>

#include <boost/python.hpp>
#include <boost/optional.hpp>

namespace pysupport {

/** Creates to-python converter for boost::optional<T>
 *  boost::none is mapped to None
 */
template <typename T>
struct to_python_optional {
    static ::PyObject* convert(const boost::optional<T> &obj) {
        using namespace boost::python;
        if (obj) {
            return incref(object(*obj).ptr());
        }
        return incref(object().ptr());
    }
};

/** Creates from-python converter for boost::optional<T>
 *  None is mapped to boost::none
 */
template <typename T>
struct from_python_optional
{
    typedef boost::optional<T> Optional;
    typedef boost::python::converter::rvalue_from_python_stage1_data Data;
    typedef boost::python::converter::rvalue_from_python_storage<
        Optional> Storage;

    from_python_optional() {
        boost::python::converter::registry::push_back
            (&convertible, &construct, boost::python::type_id<Optional>());
    }

    // Determine if ptr can be converted in a Optional
    static void* convertible(::PyObject *ptr) {
        if (ptr == Py_None) { return ptr; }
        if (boost::python::extract<T>(ptr).check()) { return ptr; }
        return nullptr;
    }

    // Convert ptr into a Optional
    static void construct(::PyObject *ptr, Data *data) {
        // get memory
        void *storage(((Storage*) data)->storage.bytes);

        // in-place construct the Optional
        if (ptr == Py_None) {
            new (storage) Optional();
        } else {
            new (storage) Optional(boost::python::extract<T>(ptr));
        }

        // Stash the memory chunk pointer for later use by boost.python
        data->convertible = storage;
    }
};

/** Convenient macro for boost::optional<T> two-way converter registration.
 */
#define PYSUPPORT_OPTIONAL(type)                                        \
    boost::python::to_python_converter<                                 \
        boost::optional<type>                                           \
    , pysupport::to_python_optional<type>>();                           \
    pysupport::from_python_optional<type>()

} // namespace pysupport

#endif // pysupport_converters_hpp_included_

max_stars_repo_name: Melown/libpysupport

max_issues_repo_name: Melown/libpysupport

max_forks_repo_name: Melown/libpysupport


text:
#pragma once

#include <ctime>
#include <cstdlib>

#include <opencv2/highgui.hpp>
#include <vpp/vpp.hh>
#include <Eigen/Core>
#include <vpp/utils/opencv_bridge.hh>
#include <vpp/utils/opencv_utils.hh>
#include "dense_one_to_one_hough.hh"
#include "vpp/algorithms/line_tracker_4_sfm.hh"
#include "vpp/algorithms/line_tracker_4_sfm/miscellanous/define.hh"

using namespace vpp;
using namespace std;
using namespace Eigen;
using namespace iod;
using namespace cv;

namespace vpp{

float get_vector_val(std::vector<float> t_array, int vert,int hori,int i ,int j);
void hough_accumulator(image2d<uchar> img, int T_theta, Mat &bv, float acc_threshold);
cv::Mat hough_accumulator_video_map_and_clusters(image2d<vuchar1> img, int mode , int T_theta,
                                                 std::vector<float>& t_accumulator, std::list<vint2>& interestedPoints,
                                                 float rhomax);
cv::Mat hough_accumulator_video_clusters(image2d<vuchar1> img, int mode , int T_theta,
                                         std::vector<float>& t_accumulator,std::list<vint2>& interestedPoints,
                                         float rhomax);
int get_theta_max(Theta_max discr);
cv::Mat accumulator_to_frame(std::vector<float> t_accumulator, float max, int rhomax, int T_theta);
cv::Mat accumulator_to_frame(std::list<vint2> interestedPoints, int rhomax, int T_theta);
void hough_image(int T_theta, float acc_threshold);

/*
template <typename... OPTS>
void Capture_Image(int mode, Theta_max discr , Sclare_rho scale
                   ,Type_video_hough type_video
                   , Type_output type_sortie,
                   Type_Lines type_line,Frequence freq,Mode mode_type,
                   OPTS... options);*/

}

#include "fast_hough.hpp"

ext: hh

max_stars_repo_name: WLChopSticks/vpp

max_issues_repo_name: WLChopSticks/vpp

max_forks_repo_name: WLChopSticks/vpp


text: #include <boost/mpl/aux_/preprocessed/dmc/divides.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <http_server/http_msg.hpp>
#include <sstream>
#include <ctime>
#include <boost/tokenizer.hpp>
#include <algorithm>

namespace FBi
{

/**
 * @brief Function to transfer the HTTP request message to c++ standard string.
 *
 * @param[in] msg The HTTP request message.
 * @param[out] result The string contains all HTTP request message.
 */
void HttpMsgUtility::ComposeHttpRequestMsg(const HttpRequestMsg& msg, std::string& result)
{
	std::stringstream sstream;
	sstream << "HTTP/" << msg.http_version_major << "." << msg.http_version_minor;

	result = msg.method;
	result += " ";
	result += msg.uri.path;

	if(!msg.uri.query_strings.empty())
	{
		URI_Struct::Query_Str_Container::const_iterator iter = msg.uri.query_strings.begin();
		if(iter != msg.uri.query_strings.end())
			result += "?";
		for(; iter != msg.uri.query_strings.end(); ++iter)
		{
			result += iter->first;
			result += "=";
			result += iter->second;
		}
	}

	if(!msg.uri.fragment_id.empty())
	{
		result += "#";
		result += msg.uri.fragment_id;
	}

	result += " ";
	result += sstream.str();
	result += "\r\n";

	HTTPMsgHeadersConstIter iter = msg.headers.begin();
	for(; iter != msg.headers.end(); iter++)
	{
		result += iter->first;
		result += ": ";
		result += iter->second;
		result += "\r\n";
	}

	result += "\r\n";
	result += msg.entity_body;
}

/**
 * @brief Function to transfer the HTTP request message to c++ standard string.
 *
 * @param[in] method The method name of HTTP request message.
 * @param[in] uri The URI of HTTP request message.
 * @param[in] http_version_major The major number of HTTP version of HTTP request message.
 * @param[in] http_version_minor The minor number of HTTP version of HTTP request message.
 * @param[in] headers The headers. Each header has already contain the field name and field value.
 * @param[in] body The entity body of HTTP request message.
 * @param[out] result The string contains all HTTP request message.
 */
template <typename InputContainer, typename InputContainerConstIter>
void HttpMsgUtility::ComposeHttpRequestMsg(const std::string& method,
		const std::string& uri,
		int http_version_major,
		int http_version_minor,
		const InputContainer& headers,
		const std::string& body,
		std::string& result)
{
	std::stringstream sstream;
	sstream << "HTTP/" << http_version_major << "." << http_version_minor;

	result = method;
	result += " ";
	result += uri;
	result += " ";
	result += sstream.str();
	result += "\r\n";

	InputContainerConstIter iter = headers.begin();
	for(; iter != headers.end(); iter++)
	{
		result += (*iter);
		result += "\r\n";
	}

	result += "\r\n";
	result += body;

}

/**
 * @brief Function to transfer the HTTP response message to c++ standard string.
 *
 * @param[in] msg The HTTP response message.
 * @param[out] result The string contains all HTTP response message.
 */
void HttpMsgUtility::ComposeHttpResponseMsg(const HttpResponseMsg& msg, std::string& result)
{
	std::stringstream sstream;
	sstream << "HTTP/" << msg.http_version_major << "." << msg.http_version_minor << " " << msg.status_code;

	result = sstream.str();
	result += " ";
	result += msg.reason_phrase;
	result += "\r\n";

	HTTPMsgHeadersConstIter iter = msg.headers.begin();
	for(; iter != msg.headers.end(); iter++)
	{
		result += iter->first;
		result += ": ";
		result += iter->second;
		result += "\r\n";
	}

	result += "\r\n";
	result += msg.entity_body;

}

/**
 * @brief Function to transfer the HTTP response message to c++ standard string.
 *
 * @param[in] http_version_major The major number of HTTP version of HTTP response message.
 * @param[in] http_version_minor The minor number of HTTP version of HTTP response message.
 * @param[in] status_code The status code of HTTP response message.
 * @param[in] reason_phrase The reason phrase of HTTP response message.
 * @param[in] headers The headers. Each header has already contain the field name and field value.
 * @param[in] body The entity body of HTTP response message.
 * @param[out] result The string contains all HTTP response message.
 */
template <typename InputContainer, typename InputContainerConstIter>
void HttpMsgUtility::ComposeHttpResponseMsg(int http_version_major,
		int http_version_minor,
		int status_code,
		const std::string& reason_phrase,
		const InputContainer& headers,
		const std::string& body,
		std::string& result)
{
	std::stringstream sstream;
	sstream << "HTTP/" << http_version_major << "." << http_version_minor << " " << status_code;

	result = sstream.str();
	result += " ";
	result += reason_phrase;
	result += "\r\n";

	InputContainerConstIter iter = headers.begin();
	for(; iter != headers.end(); iter++)
	{
		result += (*iter);
		result += "\r\n";
	}

	result += "\r\n";
	result += body;
}

/**
 * @brief Function to calculate the length of the entity body of HTTP message then set the Content-Length header into the HTTP message.
 *
 * @param[in] msg The HTTP message.
 */
void HttpMsgUtility::SetContentLength(HttpMsg& msg)
{
	std::stringstream sstream;
	sstream << msg.entity_body.length();
	msg.headers["Content-Length"] = sstream.str();
}

/**
 * @brief Function to set HTTP version and date into the HTTP response message.
 *
 * @param[out] response The HTTP response message.
 */
void HttpMsgUtility::SetGeneralHttpResponseHeaders(HttpResponseMsg& response)
{
	response.http_version_major = 1;
	response.http_version_minor = 1;

	std::time_t result = std::time(NULL);
	struct tm* timeinfo = NULL;
	char buffer[128] = {'\0'};
	timeinfo = std::gmtime(&result);

	strftime(buffer, 128, "%a, %d %b %Y %X GMT", timeinfo);

	response.headers["Date"] = buffer;
}

/**
 * @brief Function to set the default status code and reason phrase of the HTTP response message.
 *
 * @param[out] msg The HTTP response message.
 * @param[in] status_code The status code of HTTP response message.
 * @return true: If the status code can be found in the default list. Otherwise, it is false.
 */
bool HttpMsgUtility::SetDefaultStatusCode(HttpResponseMsg& msg, int status_code)
{
	msg.reason_phrase = HttpMsgUtility::GetReasonPhrase(status_code);
	msg.status_code = status_code;

	return (msg.reason_phrase.empty()) ? false : true;
}

/**
 * @brief Function to get the reason phrase of HTTP response message corresponds with the input status code.
 *
 * @param[in] status_code The status code of HTTP response message.
 * @return The reason phrase of HTTP response message.
 */
std::string HttpMsgUtility::GetReasonPhrase(int status_code)
{
	switch(status_code)
	{
	case 100:
		return "Continue";
	case 101:
		return "Switching Protocols";
	case 200:
		return "OK";
	case 201:
		return "Created";
	case 202:
		return "Accepted";
	case 203:
		return "Non-Authoritative Information";
	case 204:
		return "No Content";
	case 205:
		return "Reset Content";
	case 206:
		return "Partial Content";
	case 300:
		return "Multiple Choices";
	case 301:
		return "Moved Permanently";
	case 302:
		return "Found";
	case 303:
		return "See Other";
	case 304:
		return "Not Modified";
	case 305:
		return "Use Proxy";
	case 306:
		return "";
	case 307:
		return "Temporary Redirect";
	case 400:
		return "Bad Request";
	case 401:
		return "Unauthorized";
	case 402:
		return "Payment Required";
	case 403:
		return "Forbidden";
	case 404:
		return "Not Found";
	case 405:
		return "Method Not Allowed";
	case 406:
		return "Not Acceptable";
	case 407:
		return "Proxy Authentication Required";
	case 408:
		return "Request Timeout";
	case 409:
		return "Conflict";
	case 410:
		return "Gone";
	case 411:
		return "Length Required";
	case 412:
		return "Precondition Failed";
	case 413:
		return "Request Entity Too Large";
	case 414:
		return "Request-URI Too Long";
	case 415:
		return "Unsupported Media Type";
	case 416:
		return "Requested Range Not Satisfiable";
	case 417:
		return "Expectation Failed";
	case 500:
		return "Internal Server Error";
	case 501:
		return "Not Implemented";
	case 502:
		return "Bad Gateway";
	case 503:
		return "Service Unavailable";
	case 504:
		return "Gateway Timeout";
	case 505:
		return "HTTP Version Not Supported";
	default:
		return "";
	}
}

/**
 * @brief Function to parse the quality value of HTTP.
 *
 * @param[in] qvalue_str The string of quality value of HTTP (ex: q=0.4).
 * @return The quality value.
 */
float HttpMsgUtility::ParseHttpQualityValue(const std::string qvalue_str)
{
	float retval = 0.0;
	if( (qvalue_str.length() >= 3) || (qvalue_str.length() <= 7))
	{
		int integer = 0;
		int decimal = 0;
		bool is_need_break = false;
		for(size_t i = 0; i < qvalue_str.length(); ++i)
		{
			switch(i)
			{
			case 0:
				if(qvalue_str[i] != 'q')
					is_need_break = true;
				break;
			case 1:
				if(qvalue_str[i] != '=')
					is_need_break = true;
				break;
			case 2:
				if((qvalue_str[i] == '0') || (qvalue_str[i] == '1'))
					integer = qvalue_str[i] - '0';
				else
					is_need_break = true;
				break;
			case 3:
				break;
			case 4:
			case 5:
			case 6:
				if((qvalue_str[i] >= '0') && (qvalue_str[i] <= '9'))
					decimal = decimal*10 + (qvalue_str[i] - '0');
				else
					is_need_break = true;
				break;
			default:
				is_need_break = true;
				break;
			}
			if(is_need_break)
			{
				retval = 0.0;
				break;
			}
		}

		if(!is_need_break)
		{
			retval = (float)integer + (float)decimal / 1000.0;
		}
	}
	else
	{
		retval = 0.0;
	}

	return retval;
}

/// Private compare function for sorting the encoding and quality value in HTTP headers.
bool compare_http_accpet_encoding(const HttpEncodingWithQualityValue& i, const HttpEncodingWithQualityValue& j)
{
	return (i.qvalue > j.qvalue);
}

/**
 * @brief Function to parse the encoding and quality value in HTTP headers.
 *
 * @param[in] coding_str The string contains enconding and quality value. (ex: gzip;q=0.4, bzip2; q=0.74).
 * @param[out] out_vector The vector contains string of enconding and quality value.
 */
void HttpMsgUtility::ParseEncodingWithQualityValue(const std::string& coding_str, std::vector<HttpEncodingWithQualityValue>& out_vector)
{
	// Separate each pair of encoding and quality value.
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer_t;
	boost::char_separator<char> sep(",");
	tokenizer_t tokens(coding_str, sep);

	// Get each encodings of HTTP message and parse them.
	for(tokenizer_t::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
	{
		// Separate each encoding and quality value.
		boost::char_separator<char> sep2("; ");
		tokenizer_t tokens2(*tok_iter, sep2);
		int i = 0;
		HttpEncodingWithQualityValue coding;
		for(tokenizer_t::iterator tok_iter2 = tokens2.begin(); tok_iter2 != tokens2.end(); ++tok_iter2, ++i)
		{
			if(i==0)
			{
				// Get the encoding string.
				coding.content_coding = *tok_iter2;
				// The content codings are case-insensitive.
				for(size_t i = 0; i < coding.content_coding.length(); ++i)
					coding.content_coding[i] = tolower(coding.content_coding[i]);
			}
			else if (i == 1)
			{
				// Get the quality value.
				coding.qvalue = ParseHttpQualityValue(*tok_iter2);
			}
		}
		out_vector.push_back(coding);
	}

	// Sorting the accepted encodings by quality values.
	stable_sort(out_vector.begin(), out_vector.end(), compare_http_accpet_encoding);
}

/**
 * @brief Function to parse the encoding without quality value.
 *
 * @param[in] coding_str The string contains enconding (ex: gzip, bzip2).
 * @param[out] encoding_vector The vector contains string of enconding and quality value.
 */
void HttpMsgUtility::ParseEnconding(const std::string& coding_str, std::vector<std::string>& encoding_vector)
{
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer_t;
	boost::char_separator<char> sep(", ");
	tokenizer_t tokens(coding_str, sep);

	// Get each encodings of HTTP message and parse them.
	for(tokenizer_t::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
	{
		// The codings are case-insensitive.
		std::string temp_str;
		for(size_t i = 0; i < tok_iter->length(); ++i)
			temp_str.push_back(tolower(tok_iter->at(i)));

		encoding_vector.push_back(temp_str);
	}
}

/**
 * @brief Function to compress string.
 *
 * @param[in] mode The compression mode.
 * @param[in] input The input string.
 * @param[out] output The output compressed string.
 * @return The result of compression (mode, failed or unsupported).
 */
HttpMsgUtility::CompressedResult HttpMsgUtility::CompressString(const std::string& mode, const std::string& input, std::string& output)
{
	bool is_successful;
	if( (mode.compare("gzip") == 0) || (mode.compare("*") == 0) )
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::gzip_compressor(boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedGzip;
		else
			return HttpMsgUtility::CompressedFailed;
	}
	/*else if(mode.compare("bzip2") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::bzip2_compressor(boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedBzip2;
		else
			return HttpMsgUtility::CompressedFailed;
	}*/
	else if(mode.compare("deflate") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::zlib_compressor(boost::iostreams::zlib::deflated | boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedDeflate;
		else
			return HttpMsgUtility::CompressedFailed;
	}
	else if(mode.compare("identity") == 0)
	{
		output = input;
		return HttpMsgUtility::CompressedIdentity;
	}

	return HttpMsgUtility::CompressedUnsupported;
}

/**
 * @brief Function to compress string.
 *
 * @param[in] mode The compression mode.
 * @param[out] output_msg The output HTTP message.
 * @return The result of compression (mode, failed or unsupported).
 */
HttpMsgUtility::CompressedResult HttpMsgUtility::CompressString(const std::string& mode, HttpMsg& output_msg)
{
	bool is_successful;
	std::string output;
	if( (mode.compare("gzip") == 0) || (mode.compare("*") == 0) )
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::gzip_compressor(boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(output_msg.entity_body),
				boost::iostreams::back_inserter(output));
		if(is_successful)
		{
			// Set the Content-Encoding header.
			output_msg.headers["Content-Encoding"] = "gzip";
			output_msg.entity_body = output;
			return HttpMsgUtility::CompressedGzip;
		}
		else
			return HttpMsgUtility::CompressedFailed;
	}
	/*else if(mode.compare("bzip2") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::bzip2_compressor(boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(output_msg.entity_body),
				boost::iostreams::back_inserter(output));
		if(is_successful)
		{
			output_msg.headers["Content-Encoding"] = "bzip2";
			output_msg.entity_body = output;
			return HttpMsgUtility::CompressedBzip2;
		}
		else
			return HttpMsgUtility::CompressedFailed;
	}*/
	else if(mode.compare("deflate") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::zlib_compressor(boost::iostreams::zlib::deflated | boost::iostreams::zlib::best_compression),
				boost::make_iterator_range(output_msg.entity_body),
				boost::iostreams::back_inserter(output));
		if(is_successful)
		{
			output_msg.headers["Content-Encoding"] = "deflate";
			output_msg.entity_body = output;
			return HttpMsgUtility::CompressedDeflate;
		}
		else
			return HttpMsgUtility::CompressedFailed;

	}
	else if(mode.compare("identity") == 0)
	{
		return HttpMsgUtility::CompressedIdentity;
	}

	return HttpMsgUtility::CompressedUnsupported;
}

/**
 * @brief Function to decompress string.
 *
 * @param[in] mode The compression mode.
 * @param[in] input The input compressed string.
 * @param[out] output The output deconpressed string.
 * @return The result of compression (mode, failed or unsupported).
 */
HttpMsgUtility::CompressedResult HttpMsgUtility::DecompressString(const std::string& mode, const std::string& input, std::string& output)
{
	bool is_successful;
	if(mode.compare("gzip") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::gzip_decompressor(),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedGzip;
		else
			return HttpMsgUtility::CompressedFailed;
	}
	/*else if(mode.compare("bzip2") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::bzip2_decompressor(),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedBzip2;
		else
			return HttpMsgUtility::CompressedFailed;
	}*/
	else if(mode.compare("deflate") == 0)
	{
		is_successful = HttpMsgUtility::compress(boost::iostreams::zlib_decompressor(),
				boost::make_iterator_range(input),
				boost::iostreams::back_inserter(output));
		if(is_successful)
			return HttpMsgUtility::CompressedDeflate;
		else
			return HttpMsgUtility::CompressedFailed;
	}
	else if(mode.compare("identity") == 0)
	{
		output = input;
		return HttpMsgUtility::CompressedIdentity;
	}

	return HttpMsgUtility::CompressedUnsupported;

}

/**
 * @brief Function to compress the entity body of response message.
 *
 * @param[in] request_msg The input HTTP request message.
 * @param[out] response_msg The output HTTP response message.
 * @return The result of compression (success, failed, unsupported or no compressed).
 */
HttpMsgUtility::CompressedResult HttpMsgUtility::CompressBodyOfResponseMsg(HttpRequestMsg& request_msg, HttpResponseMsg& response_msg)
{
	HTTPMsgHeadersConstIter iter = request_msg.headers.find("accept-encoding");
	if(iter != request_msg.headers.end())
	{
		// Parse Accept-Encoding
		std::vector<HttpEncodingWithQualityValue> codings_vector;
		HttpMsgUtility::ParseEncodingWithQualityValue((request_msg.headers["accept-encoding"]), codings_vector);

		// Prepare to compress the entity body of HTTP response message.
		if(codings_vector.size() >= 1)
		{
			HttpMsgUtility::CompressedResult compressed_result = HttpMsgUtility::NoCompressed;
			for(size_t i = 0; i < codings_vector.size(); ++i)
			{
				// Skip the encoding with zero quality value.
				if(codings_vector[i].qvalue == 0.0)
					continue;

				compressed_result = HttpMsgUtility::CompressString(codings_vector[i].content_coding, response_msg);
				if((compressed_result != HttpMsgUtility::CompressedFailed) && (compressed_result != HttpMsgUtility::CompressedUnsupported))
					return HttpMsgUtility::CompressedSuccess;
			}

			// Set response message of error.
			response_msg.Reset();
			if(compressed_result == HttpMsgUtility::CompressedFailed)
			{
				// Internal Server Error
				HttpMsgUtility::SetDefaultStatusCode(response_msg, 500);
				return HttpMsgUtility::CompressedFailed;
			}

			// Not Acceptable
			if(compressed_result == HttpMsgUtility::CompressedUnsupported)
			{
				HttpMsgUtility::SetDefaultStatusCode(response_msg, 406);
				return HttpMsgUtility::CompressedUnsupported;
			}
		}
	}

	return HttpMsgUtility::NoCompressed;
}

/**
 * @brief Function to decompress the entity body of HTTP message.
 *
 * @param[in] encoding_vector The input encoding vector without quality value.
 * @param[out] msg The output HTTP message with decompressed body.
 * @return The result of compression (mode, failed or unsupported).
 */
HttpMsgUtility::CompressedResult HttpMsgUtility::DecompressBodyOfHttpMsg(const std::vector<std::string>& encoding_vector, HttpMsg& msg)
{
	std::string temp_str;
	std::vector<std::string>::const_reverse_iterator r_iter;
	HttpMsgUtility::CompressedResult compressed_result = HttpMsgUtility::CompressedSuccess;

	// We decompress the body of HTTP message according to the "reverse order" of Content-Encoding.
	for(r_iter = encoding_vector.rbegin() ; r_iter < encoding_vector.rend(); ++r_iter)
	{
		compressed_result = HttpMsgUtility::DecompressString(*r_iter, msg.entity_body, temp_str);

		if((compressed_result == HttpMsgUtility::CompressedFailed) || (compressed_result == HttpMsgUtility::CompressedUnsupported))
			return compressed_result;

		if(compressed_result != HttpMsgUtility::CompressedIdentity)
			msg.entity_body.swap(temp_str);

		temp_str.clear();
	}

	return compressed_result;
}

/**
 * @brief Function to generate the boundary string for HTTP server push mode.
 *
 * @return The boundary string for HTTP server push mode.
 */
const std::string HttpMsgUtility::GenerateServerPushBoundary()
{
	return "XD/E?5F_=,Q2-Xi(52+f";
}

/**
 * @brief Function to compose the body and headers for HTTP server push mode.
 *
 * @param[in] push_headers MIME headers for HTTP server push mode.
 * @param[in] data body for HTTP server push mode.
 * @param[in] boundary_str boundary string for HTTP server push mode.
 * @param[in] is_end The flag to indicate whether it is end of push mode.
 * @param[out] result The composed result data.
 */
void HttpMsgUtility::ComposeServerPushBody(std::map<std::string, std::string>& push_headers, std::string& data, const std::string& boundary_str, bool is_end, std::string& result)
{
	std::stringstream sstream;
	sstream << data.length();
	push_headers["Content-Length"] = sstream.str();

	std::map<std::string, std::string>::iterator iter = push_headers.begin();
	for(; iter != push_headers.end(); iter++)
	{
		result += iter->first;
		result += ": ";
		result += iter->second;
		result += "\r\n";
	}

	result += "\r\n";
	result += data;
	result += "\r\n\r\n";

	result += "--";
	result += boundary_str;
	if(!is_end)
		result += "\r\n";
	else
		result += "--\r\n";
}

} // namespace FBi


text:
/*
    Copyright 2013 Adobe
    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)
*/
/**************************************************************************************************/

#ifdef ADOBE_STD_SERIALIZATION

/**************************************************************************************************/

#include <string>

#include <boost/cstdint.hpp>

#include <adobe/array.hpp>
#include <adobe/dictionary.hpp>
#include <adobe/implementation/expression_filter.hpp>
#include <adobe/iomanip_xml.hpp>

using namespace std;

/**************************************************************************************************/

namespace adobe {

/**************************************************************************************************/

constexpr static_name_t xml_name_k = "xml"_name;

/**************************************************************************************************/

//!\ingroup manipulator
std::ostream& begin_xml(std::ostream& os) {
    replace_pword<format_base, xml_format>(os, format_base_idx());
    return os << begin_format;
}

/**************************************************************************************************/

//!\ingroup manipulator
std::ostream& end_xml(std::ostream& os) { return os << end_format; }

/**************************************************************************************************/

void xml_format::begin_format(stream_type& os) { push_stack(os, format_element_t(xml_name_k)); }

/**************************************************************************************************/

void xml_format::begin_bag(stream_type& os, const std::string& ident) {
    push_stack(os, format_element_t(bag_name_g, ident));
}

/**************************************************************************************************/

void xml_format::begin_sequence(stream_type& os) { push_stack(os, format_element_t(seq_name_g)); }

/**************************************************************************************************/

void xml_format::begin_atom(stream_type& os, const serializable_t& value) {
    push_stack(os, format_element_t(atom_name_g, value));
}

/**************************************************************************************************/

void xml_format::stack_event(stream_type& os, bool is_push) {
    const format_element_t& top(stack_top());
    name_t self(top.tag());
    name_t parent(stack_depth() >= 2 ? stack_n(1).tag() : name_t());

    if (is_push) {
        if (self == xml_name_k) {
            os << indents(depth()) << "<xml>\n";
        } else if (self == bag_name_g) {
            os << "<dict>\n";
            up();
        } else if (self == seq_name_g) {
            if (parent != bag_name_g) {
                os << "<array>\n";
                up();
            }
        } else if (self == atom_name_g) {
            handle_atom(os, is_push);
        }
    } else {
        if (self == xml_name_k) {
            os << indents(depth()) << "</xml>";
        } else if (self == bag_name_g) {
            down();
            os << indents(depth()) << "</dict>";
            if (parent != atom_name_g)
                os << "\n";
        } else if (self == seq_name_g) {
            if (parent != bag_name_g) {
                down();
                os << indents(depth()) << "</array>";
                if (parent != atom_name_g)
                    os << "\n";
            }
        } else if (self == atom_name_g) {
            handle_atom(os, is_push);
        }
    }
}

/**************************************************************************************************/

void xml_format::handle_atom(stream_type& os, bool is_push) {
    const format_element_t& top(stack_top());
    name_t self(top.tag());
    name_t parent(stack_depth() >= 2 ? stack_n(1).tag() : name_t());
    name_t grandparent(stack_depth() >= 3 ? stack_n(2).tag() : name_t());
    const serializable_t& value(top.value());

    if (is_push) {
        if (self != seq_name_g)
            os << indents(depth());

        if (parent == seq_name_g && grandparent == bag_name_g && stack_n(1).num_out_m == 0) {
            os << "<key>" << value.cast<adobe::name_t>().c_str() << "</key>";
        } else if (value.type_info() == typeid(string)) {
            os << "<string>" << entity_escape(value.cast<string>()) << "</string>";
        } else if (value.type_info() == typeid(name_t)) {
            os << "<ident>" << value.cast<adobe::name_t>() << "</ident>";
        } else if (value.type_info() == typeid(bool)) {
            os << "<bool>" << (value.cast<bool>() ? "true" : "false") << "</bool>";
        } else if (value.type_info() == typeid(double)) {
            double dbl_val(value.cast<double>());
            boost::int64_t int_val(static_cast<boost::int64_t>(dbl_val));

            if (dbl_val == int_val)
                os << "<integer>" << int_val << "</integer>";
            else
                os << "<double>" << dbl_val << "</double>";
        } else if (value.type_info() == typeid(empty_t)) {
            os << "<" << value.cast<empty_t>() << "/>";
        } else if (value.type_info() == typeid(dictionary_t)) {
            os << value.cast<dictionary_t>();
        } else if (value.type_info() == typeid(array_t)) {
            os << value.cast<array_t>();
        } else {
            os << "<xml_unknown>" << value.type_info().name() << "</xml_unknown>";
        }
    } else {
        if (parent == seq_name_g)
            stack_n(1).num_out_m++;

        if (self != seq_name_g)
            os << "\n";
    }
}

/**************************************************************************************************/

} // namespace adobe

/**************************************************************************************************/

#endif

/**************************************************************************************************/


text:
/*=============================================================================
    Copyright (c) 2004 Joao Abecasis
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

#include <boost/spirit/core.hpp>

#include <boost/spirit/attribute/closure.hpp>

#include <boost/spirit/tree/ast.hpp>
#include <boost/spirit/tree/parse_tree.hpp>

using namespace boost::spirit;

struct test_closure : public closure<test_closure, int>
{
    member1 value;
};

struct test_grammar : public grammar<test_grammar>
{
    template <typename ScannerT>
    struct definition
    {
        definition(const test_grammar&)
        {
        }

        rule<ScannerT, test_closure::context_t> const & start() const
        {
            return first;
        }

        rule<ScannerT, test_closure::context_t> first;
    };
};

int main()
{
    parse("abcd", test_grammar());
    pt_parse("abcd", test_grammar());
    ast_parse("abcd", test_grammar());
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


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

#include <fstream>

#include "../plotter/Matplotlib/Plot.h"
#include "Core/ArrowUtilities.h"
#include "IO/IO.h"

BOOST_AUTO_TEST_CASE(Plots)
{
    std::vector<int64_t> ints{ 1,2,3,4,5 };
    auto intsColumn = toColumn(ints);

    init(800, 600, nullptr);
    plot(intsColumn.get(), intsColumn.get(), "label", "", "", 1.0, nullptr);
    auto p = getPNG();
    const auto pngHeaderSignature = "\x89PNG\r\n\x1a\n"; // first 8 bytes of PNG header
    BOOST_CHECK_EQUAL(p.substr(0, 8), pngHeaderSignature); // bytes we got look like PNG file
    writeFile("temp.png", p);
}

max_stars_repo_name: mwu-tow/Dataframes

max_issues_repo_name: mwu-tow/Dataframes

max_forks_repo_name: mwu-tow/Dataframes


text:
//               Copyright Marek Dalewski 2017
// Distributed under the Boost Software License, Version 1.0.
//        (See accompanying file LICENSE.md or copy at
//           http://www.boost.org/LICENSE_1_0.txt)

#include <commander/pack_position.hpp>

#include <boost/test/unit_test.hpp>

#include <commander/algorithm.hpp>

#include <algorithm>
#include <iterator>
#include <type_traits>
#include <vector>

#define PP_MSG(pack) "{" << (pack).is_first << ',' << (pack).exact << ',' << (pack).is_last << "}"
#define PP_OP_PP_MSG(lhs, op, rhs) PP_MSG(lhs) << " " << (op) << " " << PP_MSG(rhs)

template <typename It, typename Callback, typename... Indexes>
void each_except(It begin, It end, Callback callback, Indexes... indexes)
{
    size_t pos = size_t(-1);
    std::for_each(begin, end, [&](const auto& v) {
        if (!commander::compare_disjunction(++pos, size_t(-1), size_t(indexes)...))
            callback(v);
    });
}

template <typename It, typename Callback, typename... Indexes>
void each_of(It begin, It end, Callback callback, Indexes... indexes)
{
    size_t pos = size_t(-1);
    std::for_each(begin, end, [&](const auto& v) {
        if (commander::compare_disjunction(++pos, size_t(-1), size_t(indexes)...))
            callback(v);
    });
}

BOOST_AUTO_TEST_CASE( pack_position )
{
    namespace com = commander;

    std::vector<com::pack_position<size_t>> pos;

    pos.push_back(com::pack_position<size_t> {false, 0, false});
    pos.push_back(com::pack_position<size_t> {false, 0, true });
    pos.push_back(com::pack_position<size_t> {true,  0, false});
    pos.push_back(com::pack_position<size_t> {true,  0, true });

    pos.push_back(com::pack_position<size_t> {false, 1, false});
    pos.push_back(com::pack_position<size_t> {false, 1, true });
    pos.push_back(com::pack_position<size_t> {true,  1, false});
    pos.push_back(com::pack_position<size_t> {true,  1, true });

    pos.push_back(com::pack_position<size_t> {false, 2, false});
    pos.push_back(com::pack_position<size_t> {false, 2, true });
    pos.push_back(com::pack_position<size_t> {true,  2, false});
    pos.push_back(com::pack_position<size_t> {true,  2, true });

    pos.push_back(com::pack_position<size_t> {false, 3, false});
    pos.push_back(com::pack_position<size_t> {false, 3, true });
    pos.push_back(com::pack_position<size_t> {true,  3, false});
    pos.push_back(com::pack_position<size_t> {true,  3, true });

    {
        static_assert(std::is_same_v<int, com::pack_position<int>::size_type>);
        static_assert(std::is_same_v<size_t, com::pack_position<size_t>::size_type>);
    }

    {
        BOOST_CHECK(pos.at( 0).is_first == false); BOOST_CHECK(pos.at( 0).exact == 0); BOOST_CHECK(pos.at( 0).is_last == false);
        BOOST_CHECK(pos.at( 1).is_first == false); BOOST_CHECK(pos.at( 1).exact == 0); BOOST_CHECK(pos.at( 1).is_last == true);
        BOOST_CHECK(pos.at( 2).is_first == true);  BOOST_CHECK(pos.at( 2).exact == 0); BOOST_CHECK(pos.at( 2).is_last == false);
        BOOST_CHECK(pos.at( 3).is_first == true);  BOOST_CHECK(pos.at( 3).exact == 0); BOOST_CHECK(pos.at( 3).is_last == true);
        BOOST_CHECK(pos.at( 4).is_first == false); BOOST_CHECK(pos.at( 4).exact == 1); BOOST_CHECK(pos.at( 4).is_last == false);
        BOOST_CHECK(pos.at( 5).is_first == false); BOOST_CHECK(pos.at( 5).exact == 1); BOOST_CHECK(pos.at( 5).is_last == true);
        BOOST_CHECK(pos.at( 6).is_first == true);  BOOST_CHECK(pos.at( 6).exact == 1); BOOST_CHECK(pos.at( 6).is_last == false);
        BOOST_CHECK(pos.at( 7).is_first == true);  BOOST_CHECK(pos.at( 7).exact == 1); BOOST_CHECK(pos.at( 7).is_last == true);
        BOOST_CHECK(pos.at( 8).is_first == false); BOOST_CHECK(pos.at( 8).exact == 2); BOOST_CHECK(pos.at( 8).is_last == false);
        BOOST_CHECK(pos.at( 9).is_first == false); BOOST_CHECK(pos.at( 9).exact == 2); BOOST_CHECK(pos.at( 9).is_last == true);
        BOOST_CHECK(pos.at(10).is_first == true);  BOOST_CHECK(pos.at(10).exact == 2); BOOST_CHECK(pos.at(10).is_last == false);
        BOOST_CHECK(pos.at(11).is_first == true);  BOOST_CHECK(pos.at(11).exact == 2); BOOST_CHECK(pos.at(11).is_last == true);
        BOOST_CHECK(pos.at(12).is_first == false); BOOST_CHECK(pos.at(12).exact == 3); BOOST_CHECK(pos.at(12).is_last == false);
        BOOST_CHECK(pos.at(13).is_first == false); BOOST_CHECK(pos.at(13).exact == 3); BOOST_CHECK(pos.at(13).is_last == true);
        BOOST_CHECK(pos.at(14).is_first == true);  BOOST_CHECK(pos.at(14).exact == 3); BOOST_CHECK(pos.at(14).is_last == false);
        BOOST_CHECK(pos.at(15).is_first == true);  BOOST_CHECK(pos.at(15).exact == 3); BOOST_CHECK(pos.at(15).is_last == true);
    }

    {
        for (size_t cur_idx = 0; cur_idx < 4; ++cur_idx) {
            const auto& cur = pos.at(cur_idx);
            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == true,  PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == false, PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == false, PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == true,  PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == false, PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == true,  PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == false, PP_OP_PP_MSG(cur, "<=", p)); });
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == true,  PP_OP_PP_MSG(cur, "<=", p)); });

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == true,  PP_OP_PP_MSG(cur, ">",  p)); });
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == false, PP_OP_PP_MSG(cur, ">",  p)); });

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == true,  PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == false, PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3);
        }
    }

    {
        for (size_t cur_idx = 4; cur_idx < 8; ++cur_idx) {
            const auto& cur = pos.at(cur_idx);
            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == true,  PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == false, PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == false, PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == true,  PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == false, PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == true,  PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == false, PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == true,  PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == true,  PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == false, PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == true,  PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == false, PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7);
        }
    }

    {
        for (size_t cur_idx = 8; cur_idx < 12; ++cur_idx) {
            const auto& cur = pos.at(cur_idx);
            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == true,  PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == false, PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == false, PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == true,  PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == false, PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == true,  PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == false, PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == true,  PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == true,  PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == false, PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == true,  PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == false, PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
        }
    }

    {
        for (size_t cur_idx = 12; cur_idx < 16; ++cur_idx) {
            const auto& cur = pos.at(cur_idx);
            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == true,  PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur == p) == false, PP_OP_PP_MSG(cur, "==", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == false, PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur != p) == true,  PP_OP_PP_MSG(cur, "!=", p)); }, cur_idx);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == false, PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <  p) == true,  PP_OP_PP_MSG(cur, "<",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == false, PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur <= p) == true,  PP_OP_PP_MSG(cur, "<=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == true,  PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >  p) == false, PP_OP_PP_MSG(cur, ">",  p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

            each_of    (pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == true,  PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
            each_except(pos.begin(), pos.end(), [&](const auto& p) { BOOST_CHECK_MESSAGE((cur >= p) == false, PP_OP_PP_MSG(cur, ">=", p)); }, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
        }
    }
}

max_stars_repo_name: daishe/commander

max_issues_repo_name: daishe/commander

max_forks_repo_name: daishe/commander


text:
//  (C) Copyright Gennadiy Rozental 2001.
//  Use, modification, and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : parameter modifiers
// ***************************************************************************

#ifndef BOOST_TEST_UTILS_RUNTIME_MODIFIER_HPP
#define BOOST_TEST_UTILS_RUNTIME_MODIFIER_HPP

// Boost.Test Runtime parameters
#include <boost/test/utils/runtime/fwd.hpp>

// Boost.Test
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/utils/named_params.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

// New CLA API available only for some C++11 compilers
#if !defined(BOOST_NO_CXX11_AUTO_DECLARATIONS) &&                              \
    !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) &&                               \
    !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) &&                           \
    !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX)
#define BOOST_TEST_CLA_NEW_API
#endif

namespace boost {
namespace runtime {

// ************************************************************************** //
// **************         environment variable modifiers       ************** //
// ************************************************************************** //

namespace {

#ifdef BOOST_TEST_CLA_NEW_API
auto const &description = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct description_t>>::value;
auto const &help = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct help_t>>::value;
auto const &env_var = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct env_var_t>>::value;
auto const &end_of_params = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct end_of_params_t>>::value;
auto const &negation_prefix = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct neg_prefix_t>>::value;
auto const &value_hint = unit_test::static_constant<
    nfp::typed_keyword<cstring, struct value_hint_t>>::value;
auto const &optional_value =
    unit_test::static_constant<nfp::keyword<struct optional_value_t>>::value;
auto const &default_value =
    unit_test::static_constant<nfp::keyword<struct default_value_t>>::value;
auto const &callback =
    unit_test::static_constant<nfp::keyword<struct callback_t>>::value;

template <typename EnumType>
using enum_values = unit_test::static_constant<nfp::typed_keyword<
    std::initializer_list<std::pair<const cstring, EnumType>>,
    struct enum_values_t>>;

#else

nfp::typed_keyword<cstring, struct description_t> description;
nfp::typed_keyword<cstring, struct help_t> help;
nfp::typed_keyword<cstring, struct env_var_t> env_var;
nfp::typed_keyword<cstring, struct end_of_params_t> end_of_params;
nfp::typed_keyword<cstring, struct neg_prefix_t> negation_prefix;
nfp::typed_keyword<cstring, struct value_hint_t> value_hint;
nfp::keyword<struct optional_value_t> optional_value;
nfp::keyword<struct default_value_t> default_value;
nfp::keyword<struct callback_t> callback;

template <typename EnumType> struct enum_values_list {
  typedef std::pair<cstring, EnumType> ElemT;
  typedef std::vector<ElemT> ValuesT;

  enum_values_list const &operator()(cstring k, EnumType v) const {
    const_cast<enum_values_list *>(this)->m_values.push_back(ElemT(k, v));

    return *this;
  }

  operator ValuesT const &() const { return m_values; }

private:
  ValuesT m_values;
};

template <typename EnumType>
struct enum_values
    : unit_test::static_constant<nfp::typed_keyword<enum_values_list<EnumType>,
                                                    struct enum_values_t>> {};

#endif

} // namespace

} // namespace runtime
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_UTILS_RUNTIME_MODIFIER_HPP

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#define BOOST_TEST_MODULE SolutionTest

#include "solution.hpp"

//#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(SolutionSuite)

BOOST_AUTO_TEST_CASE(PlainTest1)
{
    string s = "aab";
    vector<vector<string>> results = Solution().partition(s);

    vector<vector<string>> expected{
        {"a","a","b"},
        {"aa","b"}
    };

    BOOST_CHECK_EQUAL(results.size(), expected.size());
    for (int i = 0; i < results.size(); i++)
        BOOST_CHECK_EQUAL_COLLECTIONS(results[i].begin(), results[i].end(), expected[i].begin(), expected[i].end());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: johnhany/leetcode

max_issues_repo_name: johnhany/leetcode

max_forks_repo_name: johnhany/leetcode