<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#undef SC_DLLIMPLEMENTATION

#include "scitems.hxx"

#include <sfx2/objsh.hxx>
#include <sfx2/tabdlg.hxx>
#include <svl/cjkoptions.hxx>

#include "tabpages.hxx"
#include "attrdlg.hxx"
#include "scresid.hxx"
#include "attrdlg.hrc"
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
#include <svx/flagsdef.hxx>
#include <editeng/flstitem.hxx>
#include <sfx2/app.hxx>

#if !LAYOUT_SFX_TABDIALOG_BROKEN
#include <layout/layout-pre.hxx>
#endif

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

ScAttrDlg::ScAttrDlg( SfxViewFrame*     pFrameP,
                      Window*           pParent,
                      const SfxItemSet* pCellAttrs )

    :   SfxTabDialog( pFrameP,
                      pParent,
                      ScResId( RID_SCDLG_ATTR ),
                      pCellAttrs )
{
    SvtCJKOptions aCJKOptions;
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    DBG_ASSERT(pFact, "Dialogdiet fail!");

    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_NUMBERFORMAT ), "GetTabPageCreatorFunc fail!");
#if LAYOUT_SFX_TABDIALOG_BROKEN
    AddTabPage( TP_NUMBER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_NUMBERFORMAT ), 0 );
#else
    String number = rtl::OUString::createFromAscii ("Numbers");
    AddTabPage( TP_NUMBER, number, pFact->GetTabPageCreatorFunc (RID_SVXPAGE_NUMBERFORMAT), 0, FALSE, TAB_APPEND);
#endif
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_NAME ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_FONT, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_NAME ), 0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_EFFECTS ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_FONTEFF, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_EFFECTS ), 0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_ALIGNMENT ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_ALIGNMENT, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_ALIGNMENT ),    0 );

    if ( aCJKOptions.IsAsianTypographyEnabled() )
    {
        DBG_ASSERT(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageCreatorFunc fail!");
        AddTabPage( TP_ASIAN,   pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN),       0 );
    }
    else
        RemoveTabPage( TP_ASIAN );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_BORDER,      pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ),     0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_BACKGROUND,  pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 );
    AddTabPage( TP_PROTECTION,  ScTabPageProtection::Create,    0 );
    FreeResource();
}

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

__EXPORT ScAttrDlg::~ScAttrDlg()
{
}

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

void __EXPORT ScAttrDlg::PageCreated( USHORT nPageId, SfxTabPage& rTabPage )
{
    SfxObjectShell* pDocSh = SfxObjectShell::Current();
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case TP_NUMBER:
        {
            aSet.Put (SfxLinkItem( SID_LINK_TYPE, LINK( this, ScAttrDlg, OkHandler )));
            rTabPage.PageCreated(aSet);
        }
        break;

        case TP_FONT:
        {
            const SfxPoolItem* pInfoItem = pDocSh->GetItem( SID_ATTR_CHAR_FONTLIST );

            DBG_ASSERT( pInfoItem, "FontListItem  not found :-(" );

            aSet.Put (SvxFontListItem(((const SvxFontListItem*)pInfoItem)->GetFontList(), SID_ATTR_CHAR_FONTLIST ));
            rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

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

IMPL_LINK( ScAttrDlg, OkHandler, void*, EMPTYARG )
{
    ((Link&)GetOKButton().GetClickHdl()).Call( NULL );

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use RTL_CONSTASCII_USTRING_PARAM<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#undef SC_DLLIMPLEMENTATION

#include "scitems.hxx"

#include <sfx2/objsh.hxx>
#include <sfx2/tabdlg.hxx>
#include <svl/cjkoptions.hxx>

#include "tabpages.hxx"
#include "attrdlg.hxx"
#include "scresid.hxx"
#include "attrdlg.hrc"
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
#include <svx/flagsdef.hxx>
#include <editeng/flstitem.hxx>
#include <sfx2/app.hxx>

#if !LAYOUT_SFX_TABDIALOG_BROKEN
#include <layout/layout-pre.hxx>
#endif

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

ScAttrDlg::ScAttrDlg( SfxViewFrame*     pFrameP,
                      Window*           pParent,
                      const SfxItemSet* pCellAttrs )

    :   SfxTabDialog( pFrameP,
                      pParent,
                      ScResId( RID_SCDLG_ATTR ),
                      pCellAttrs )
{
    SvtCJKOptions aCJKOptions;
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    DBG_ASSERT(pFact, "Dialogdiet fail!");

    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_NUMBERFORMAT ), "GetTabPageCreatorFunc fail!");
#if LAYOUT_SFX_TABDIALOG_BROKEN
    AddTabPage( TP_NUMBER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_NUMBERFORMAT ), 0 );
#else
    String number(RTL_CONSTASCII_USTRINGPARAM("Numbers"));
    AddTabPage( TP_NUMBER, number, pFact->GetTabPageCreatorFunc (RID_SVXPAGE_NUMBERFORMAT), 0, FALSE, TAB_APPEND);
#endif
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_NAME ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_FONT, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_NAME ), 0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_EFFECTS ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_FONTEFF, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_EFFECTS ), 0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_ALIGNMENT ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_ALIGNMENT, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_ALIGNMENT ),    0 );

    if ( aCJKOptions.IsAsianTypographyEnabled() )
    {
        DBG_ASSERT(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageCreatorFunc fail!");
        AddTabPage( TP_ASIAN,   pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN),       0 );
    }
    else
        RemoveTabPage( TP_ASIAN );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_BORDER,      pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ),     0 );
    DBG_ASSERT(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageCreatorFunc fail!");
    AddTabPage( TP_BACKGROUND,  pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 );
    AddTabPage( TP_PROTECTION,  ScTabPageProtection::Create,    0 );
    FreeResource();
}

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

__EXPORT ScAttrDlg::~ScAttrDlg()
{
}

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

void __EXPORT ScAttrDlg::PageCreated( USHORT nPageId, SfxTabPage& rTabPage )
{
    SfxObjectShell* pDocSh = SfxObjectShell::Current();
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case TP_NUMBER:
        {
            aSet.Put (SfxLinkItem( SID_LINK_TYPE, LINK( this, ScAttrDlg, OkHandler )));
            rTabPage.PageCreated(aSet);
        }
        break;

        case TP_FONT:
        {
            const SfxPoolItem* pInfoItem = pDocSh->GetItem( SID_ATTR_CHAR_FONTLIST );

            DBG_ASSERT( pInfoItem, "FontListItem  not found :-(" );

            aSet.Put (SvxFontListItem(((const SvxFontListItem*)pInfoItem)->GetFontList(), SID_ATTR_CHAR_FONTLIST ));
            rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

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

IMPL_LINK( ScAttrDlg, OkHandler, void*, EMPTYARG )
{
    ((Link&)GetOKButton().GetClickHdl()).Call( NULL );

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <climits>

void readpgm( const std::string &fn,
        unsigned char* &data,
        int &width,
        int &height ) {

    FILE*  stream = 0;

    stream = fopen(fn.c_str(),"r");
    if ( !stream ) {
        std::cerr << " Failed to read pgm." << std::endl;
        exit(-1);
    }

    int bsize;
    int read = fscanf(stream,"P5\n%d %d\n%d%*[\n]",&width,&height,&bsize);
    if ( read < 3 ) {
        std::cerr << " Failed to read pgm header." << std::endl;
        exit(-1);
    }

    data = new unsigned char[width*height];

    read = fread(data,1,width*height,stream);
    if ( read != width*height ) {
        std::cerr << " Failed to read pgm data." << std::endl;
        std::cerr << " Read " << read << " expected " << width*height
            <<  "." << std::endl;
        exit(-1);
    }

    fclose(stream);

}

void writepgm( const std::string &fn,
        unsigned char* &data,
        int &width,
        int &height ) {

    FILE*  stream = 0;

    stream = fopen(fn.c_str(),"w");
    if ( !stream ) {
        std::cerr << " Failed to write pgm." << std::endl;
        exit(-1);
    }

    int wrote = fprintf(stream,"P5\n%d %d\n%d\n",width,height,255);
    if ( wrote < 3 ) {
        std::cerr << " Failed to write pgm header." << std::endl;
        exit(-1);
    }

    wrote = fwrite(data,1,width*height,stream);
    if ( wrote != width*height ) {
        std::cerr << " Failed to write pgm data." << std::endl;
        std::cerr << " Wrote " << wrote << " expected " << width*height
            <<  "." << std::endl;
        exit(-1);
    }

    fclose(stream);

}

typedef struct _im {

    unsigned char *data;
    int width, height;

} im_t;

#define CORR_ALGO_NCC

void patchnxcorr( int rad, im_t &im1, im_t &im2, im_t &disp ) {

    if ( !(im1.width == im2.width && im1.height == im2.height  ) ) {
        std::cerr << " Images are not same dimensions." << std::endl;
        exit(-1);
    }

    int width = im1.width;
    int height = im1.height;

    int disparityrange = width;

    int sz = 2*rad+1;
    unsigned char *cache = new unsigned char[sz*sz];

    // Loop over all scan lines
    for ( int irow = 0; irow < height; ++irow ) {

        for ( int icol = 0; icol < width; ++icol ) {

            for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                    int r = irow + rrow;
                    int c = icol + rcol;
                    if ( r < 0 || r >= height || c < 0 || c >= width ) {
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        cache[pr*sz+pc] = 0;
                        continue;
                    }
                    int pr = rrow + rad;
                    int pc = rcol + rad;
                    cache[pr*sz+pc] = im2.data[r*width+c];
                }
            }

#ifdef CORR_ALGO_NCC
            double maxncc = 0;
#else
            int minssd = 0;
#endif

            int minidx = -1;

            for ( int scol = std::max(0,icol - disparityrange);
                    scol < std::min(width,icol+disparityrange); ++scol ) {

#ifdef CORR_ALGO_NCC
                double ncc = 0;
                double mean1 = 0;
                double mean2 = 0;
                double std1 = 0;
                double std2 = 0;
                double xcorr = 0;
#else
                int ssd = 0;
#endif

#ifdef CORR_ALGO_NCC
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        mean2 += cache[pr*sz+pc];
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            continue;
                        }
                        mean1 += im1.data[r*width+c];
                    }
                }
                mean1 /= sz*sz;
                mean2 /= sz*sz;
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        double v2 = cache[pr*sz+pc] - mean2;
                        std2 += v2*v2;
                        double e;
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            e = 0;
                        } else {
                            e = im1.data[r*width+c];
                        }
                        double v1 =  e - mean1;
                        std1 += v1*v1;
                        xcorr += v1 * v2;
                    }
                }
                std1 = std::sqrt(std1);
                std2 = std::sqrt(std2);
                ncc = xcorr / std1 / std2;

                //std::cout << " ncc: " << ncc << std::endl;

                if ( minidx < 0 || ncc > maxncc ) {
                    maxncc = ncc;
                    minidx = scol;
                }

#else
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        int delta;
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            delta =  (int)cache[pr*sz+pc];
                            ssd   += delta * delta;
                            continue;
                        }
                        delta = (int)cache[pr*sz+pc] - (int)im1.data[r*width+c];
                        ssd += delta*delta;
                    }
                }

                if ( minidx < 0 || ssd < minssd ) {
                    minssd = ssd;
                    minidx = scol;
                }
#endif

            }

            //int disparity = icol - minidx;
            //std::cout << " disparity: " << disparity << std::endl;

            disp.data[irow*width + icol] = (icol-minidx) / 16 + 127.;

        }

    }

}

void sgmscan(int ndisp,
        int mindisp,
        int p1,
        int p2,
        int npix,
        unsigned char *ref,
        unsigned char *match,
        unsigned char *out ) {

    int* matrix = new int[ndisp*npix];
    std::fill(matrix,matrix+ndisp*npix,0); /* May be not required. */

    int* pathmatrix = new int[ndisp*npix];
    std::fill(pathmatrix,pathmatrix+ndisp*npix,0); /* May be not required. */

    int* displut = new int[ndisp];
    int* dispdifflut = new int[ndisp*ndisp];
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        displut[idisp] = idisp + mindisp;
    }
    for ( int idisp1 = 0; idisp1 < ndisp; ++idisp1 ) {
        for ( int idisp2 = 0; idisp2 < ndisp; ++idisp2 ) {
            dispdifflut[idisp1*ndisp+idisp2] =
                std::abs( displut[idisp1] - displut[idisp2] );
        }
    }

    // Initialize the 0th column first dependent on the data term only
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        int matchpos = 0+displut[idisp];
        if ( matchpos >= 0 && matchpos < npix ) {
            matrix[idisp] = std::abs((int)(ref[0])-(int)(match[matchpos]));
        } else {
            matrix[idisp] = -1; /* Negative values will indicate invalid matching */
        }
        pathmatrix[idisp] = -1;
    }

    for ( int ipix = 1; ipix < npix; ++ipix ) {
        for ( int idisp = 0; idisp < ndisp; ++idisp ) {
                int matchpos = ipix+displut[idisp];
                int dataterm = INT_MAX;
                if ( matchpos >= 0 && matchpos < npix ) {
                    dataterm = std::abs((int)(ref[ipix])-(int)(match[matchpos]));
                } else {
                    matrix[ipix*ndisp + idisp] = -1; /* Negative values will indicate invalid matching */
                    pathmatrix[ipix*ndisp + idisp] = -1;
                    continue;
                }
                int mintotalterm = INT_MAX;
                int minidx = -1;
                for ( int idispprev = 0; idispprev < ndisp; ++idispprev ) {
                    int smoothterm = -1;
                    int v = matrix[ (ipix-1)*ndisp + idispprev ];
                    if ( v < 0 ) {
                        continue;
                    }

                    // mg: According to profiling, the line below is incredibly slow,
                    // thus recommend a lut to replace for speed.
                    //int absdisp = std::abs(displut[idispprev]-displut[idisp]);
                    int absdisp = dispdifflut[idisp*ndisp + idispprev];

                    if ( absdisp == 0 ) {
                        smoothterm = v;
                    } else if (  absdisp == 1 ) {
                        smoothterm = v + p1;
                    } else {
                        smoothterm = v + p2;
                    }

                    int totalterm = smoothterm + dataterm;

                    if ( totalterm  < mintotalterm ) {
                        mintotalterm = totalterm;
                        minidx = idispprev;
                    }

                }
                matrix[ipix*ndisp + idisp ] = mintotalterm;
                pathmatrix[ipix*ndisp + idisp ] = minidx;
        }
    }

    // Decode from optimal
    int minenergy = INT_MAX;
    int minenergyidx = -1;
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        int energy = matrix[(npix-1)*ndisp + idisp ];
        if ( energy < 0 ) {
            continue;
        }
        if ( energy < minenergy ) {
            minenergy = energy;
            minenergyidx = idisp;
        }
    }

    out[npix-1] = minenergyidx;

    for ( int ipix = npix-2; ipix >= 0; --ipix ) {
        out[ipix] = pathmatrix[ (ipix+1)*ndisp + out[ipix+1] ];
    }

    delete[] matrix;
    delete[] pathmatrix;
    delete[] displut;
    delete[] dispdifflut;

}

void sgm( int ndisp,
        int mindisp,
        int p1,
        int p2,
        im_t &im1,
        im_t &im2,
        im_t &disp ) {

    if ( !(im1.width == im2.width && im1.height == im2.height  ) ) {
        std::cerr << " Images are not same dimensions." << std::endl;
        exit(-1);
    }

    int width = im1.width;
    int height = im1.height;

    for ( int irow = 0; irow < height; ++irow ) {
        int npix = width;
        unsigned char *ref   = im1.data + irow*width;
        unsigned char *match = im2.data + irow*width;
        unsigned char *out   = disp.data + irow*width;
        sgmscan(ndisp,mindisp,p1,p2,npix,ref,match,out);
        std::cout << "\r done row " << irow+1 << " of " << height << std::flush;
    }
    std::cout << std::endl;

}

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

    //int rad = 7;
    im_t im1, im2, disp;

    std::cout << " Reading im1 " << std::endl;
    readpgm("cones_left.pgm",
            im1.data,
            im1.width,
            im1.height);

    std::cout << " Reading im2 " << std::endl;
    readpgm("cones_right.pgm",
            im2.data,
            im2.width,
            im2.height);

    disp.width  = im1.width;
    disp.height = im1.height;
    disp.data   = new unsigned char[disp.width*disp.height];

    //patchnxcorr(rad,im1,im2,disp);
    int ndisp = 128;
    int mindisp = -(ndisp-1);
    int p1 = 10;
    int p2 = 150;
    std::cout << " ndisp: " << ndisp << std::endl;
    std::cout << " mindisp: " << mindisp << std::endl;
    sgm(ndisp,mindisp,p1,p2,im1,im2,disp);

    writepgm("disp.pgm",
            disp.data,
            disp.width,
            disp.height);

    delete[] im1.data, im2.data, disp.data;

    return 0;
}
<commit_msg>Updated algorithm to allow for arbitriary direction.<commit_after>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <climits>

void readpgm( const std::string &fn,
        unsigned char* &data,
        int &width,
        int &height ) {

    FILE*  stream = 0;

    stream = fopen(fn.c_str(),"r");
    if ( !stream ) {
        std::cerr << " Failed to read pgm." << std::endl;
        exit(-1);
    }

    int bsize;
    int read = fscanf(stream,"P5\n%d %d\n%d%*[\n]",&width,&height,&bsize);
    if ( read < 3 ) {
        std::cerr << " Failed to read pgm header." << std::endl;
        exit(-1);
    }

    data = new unsigned char[width*height];

    read = fread(data,1,width*height,stream);
    if ( read != width*height ) {
        std::cerr << " Failed to read pgm data." << std::endl;
        std::cerr << " Read " << read << " expected " << width*height
            <<  "." << std::endl;
        exit(-1);
    }

    fclose(stream);

}

void writepgm( const std::string &fn,
        unsigned char* &data,
        int &width,
        int &height ) {

    FILE*  stream = 0;

    stream = fopen(fn.c_str(),"w");
    if ( !stream ) {
        std::cerr << " Failed to write pgm." << std::endl;
        exit(-1);
    }

    int wrote = fprintf(stream,"P5\n%d %d\n%d\n",width,height,255);
    if ( wrote < 3 ) {
        std::cerr << " Failed to write pgm header." << std::endl;
        exit(-1);
    }

    wrote = fwrite(data,1,width*height,stream);
    if ( wrote != width*height ) {
        std::cerr << " Failed to write pgm data." << std::endl;
        std::cerr << " Wrote " << wrote << " expected " << width*height
            <<  "." << std::endl;
        exit(-1);
    }

    fclose(stream);

}

typedef struct _im {

    unsigned char *data;
    int width, height;

} im_t;

#define CORR_ALGO_NCC

void patchnxcorr( int rad, im_t &im1, im_t &im2, im_t &disp ) {

    if ( !(im1.width == im2.width && im1.height == im2.height  ) ) {
        std::cerr << " Images are not same dimensions." << std::endl;
        exit(-1);
    }

    int width = im1.width;
    int height = im1.height;

    int disparityrange = width;

    int sz = 2*rad+1;
    unsigned char *cache = new unsigned char[sz*sz];

    // Loop over all scan lines
    for ( int irow = 0; irow < height; ++irow ) {

        for ( int icol = 0; icol < width; ++icol ) {

            for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                    int r = irow + rrow;
                    int c = icol + rcol;
                    if ( r < 0 || r >= height || c < 0 || c >= width ) {
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        cache[pr*sz+pc] = 0;
                        continue;
                    }
                    int pr = rrow + rad;
                    int pc = rcol + rad;
                    cache[pr*sz+pc] = im2.data[r*width+c];
                }
            }

#ifdef CORR_ALGO_NCC
            double maxncc = 0;
#else
            int minssd = 0;
#endif

            int minidx = -1;

            for ( int scol = std::max(0,icol - disparityrange);
                    scol < std::min(width,icol+disparityrange); ++scol ) {

#ifdef CORR_ALGO_NCC
                double ncc = 0;
                double mean1 = 0;
                double mean2 = 0;
                double std1 = 0;
                double std2 = 0;
                double xcorr = 0;
#else
                int ssd = 0;
#endif

#ifdef CORR_ALGO_NCC
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        mean2 += cache[pr*sz+pc];
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            continue;
                        }
                        mean1 += im1.data[r*width+c];
                    }
                }
                mean1 /= sz*sz;
                mean2 /= sz*sz;
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        double v2 = cache[pr*sz+pc] - mean2;
                        std2 += v2*v2;
                        double e;
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            e = 0;
                        } else {
                            e = im1.data[r*width+c];
                        }
                        double v1 =  e - mean1;
                        std1 += v1*v1;
                        xcorr += v1 * v2;
                    }
                }
                std1 = std::sqrt(std1);
                std2 = std::sqrt(std2);
                ncc = xcorr / std1 / std2;

                //std::cout << " ncc: " << ncc << std::endl;

                if ( minidx < 0 || ncc > maxncc ) {
                    maxncc = ncc;
                    minidx = scol;
                }

#else
                for ( int rrow = -rad; rrow <= rad; ++rrow ) {
                    for ( int rcol = -rad; rcol <= rad; ++rcol ) {
                        int r = irow + rrow;
                        int c = scol + rcol;
                        int pr = rrow + rad;
                        int pc = rcol + rad;
                        int delta;
                        if ( r < 0 || r >= height || c < 0 || c >= width ) {
                            delta =  (int)cache[pr*sz+pc];
                            ssd   += delta * delta;
                            continue;
                        }
                        delta = (int)cache[pr*sz+pc] - (int)im1.data[r*width+c];
                        ssd += delta*delta;
                    }
                }

                if ( minidx < 0 || ssd < minssd ) {
                    minssd = ssd;
                    minidx = scol;
                }
#endif

            }

            //int disparity = icol - minidx;
            //std::cout << " disparity: " << disparity << std::endl;

            disp.data[irow*width + icol] = (icol-minidx) / 16 + 127.;

        }

    }

}

void sgmscan(int ndisp,
        int mindisp,
        int p1,
        int p2,
        int width, /* Image width */
        int *unravel,
        int npix,
        unsigned char *ref,
        unsigned char *match,
        unsigned char *out ) {

    int* matrix = new int[ndisp*npix];
    std::fill(matrix,matrix+ndisp*npix,0); /* May be not required. */

    int* pathmatrix = new int[ndisp*npix];
    std::fill(pathmatrix,pathmatrix+ndisp*npix,0); /* May be not required. */

    int* displut = new int[ndisp];
    int* dispdifflut = new int[ndisp*ndisp];
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        displut[idisp] = idisp + mindisp;
    }
    for ( int idisp1 = 0; idisp1 < ndisp; ++idisp1 ) {
        for ( int idisp2 = 0; idisp2 < ndisp; ++idisp2 ) {
            dispdifflut[idisp1*ndisp+idisp2] =
                std::abs( displut[idisp1] - displut[idisp2] );
        }
    }

    // Initialize the 0th column first dependent on the data term only
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        int refy = unravel[0];
        int refx = unravel[1];
        int matchposx = refx+displut[idisp];
        int matchposy = refy;
        if ( matchposx >= 0 && matchposx < npix ) {
            matrix[idisp] = std::abs((int)(ref[refy*width+refx])-
                    (int)(match[matchposy*width+matchposx]));
        } else {
            matrix[idisp] = -1; /* Negative values will indicate invalid matching */
        }
        pathmatrix[idisp] = -1;
    }

    for ( int ipix = 1; ipix < npix; ++ipix ) {
        for ( int idisp = 0; idisp < ndisp; ++idisp ) {
            int refy = unravel[2*ipix+0];
            int refx = unravel[2*ipix+1];
            int matchposx = refx+displut[idisp];
            int matchposy = refy;
            //int matchpos = ipix+displut[idisp];
            int dataterm = INT_MAX;
            if ( matchposx >= 0 && matchposx < npix ) {
                //dataterm = std::abs((int)(ref[ipix])-(int)(match[matchpos]));
                dataterm = std::abs((int)(ref[refy*width+refx])-
                        (int)(match[matchposy*width+matchposx]));
            } else {
                matrix[ipix*ndisp + idisp] = -1; /* Negative values will indicate invalid matching */
                pathmatrix[ipix*ndisp + idisp] = -1;
                continue;
            }
            int mintotalterm = INT_MAX;
            int minidx = -1;
            for ( int idispprev = 0; idispprev < ndisp; ++idispprev ) {
                int smoothterm = -1;
                int v = matrix[ (ipix-1)*ndisp + idispprev ];
                if ( v < 0 ) {
                    continue;
                }

                // mg: According to profiling, the line below is incredibly slow,
                // thus recommend a lut to replace for speed.
                //int absdisp = std::abs(displut[idispprev]-displut[idisp]);
                int absdisp = dispdifflut[idisp*ndisp + idispprev];

                if ( absdisp == 0 ) {
                    smoothterm = v;
                } else if (  absdisp == 1 ) {
                    smoothterm = v + p1;
                } else {
                    smoothterm = v + p2;
                }

                int totalterm = smoothterm + dataterm;

                if ( totalterm  < mintotalterm ) {
                    mintotalterm = totalterm;
                    minidx = idispprev;
                }

            }
            matrix[ipix*ndisp + idisp ] = mintotalterm;
            pathmatrix[ipix*ndisp + idisp ] = minidx;
        }
    }

    // Decode from optimal
    int minenergy = INT_MAX;
    int minenergyidx = -1;
    for ( int idisp = 0; idisp < ndisp; ++idisp ) {
        int energy = matrix[(npix-1)*ndisp + idisp ];
        if ( energy < 0 ) {
            continue;
        }
        if ( energy < minenergy ) {
            minenergy = energy;
            minenergyidx = idisp;
        }
    }

    int *_out = new int[npix];

    _out[npix-1] = minenergyidx;

    for ( int ipix = npix-2; ipix >= 0; --ipix ) {
        _out[ipix] = pathmatrix[ (ipix+1)*ndisp + _out[ipix+1] ];
    }

    for ( int ipix = 0; ipix < npix; ++ipix ) {
        int y = unravel[2*ipix + 0];
        int x = unravel[2*ipix + 1];
        out[y*width+x] = _out[ipix];
    }

    delete[] _out;

    delete[] matrix;
    delete[] pathmatrix;
    delete[] displut;
    delete[] dispdifflut;

}

void sgm( int ndisp,
        int mindisp,
        int p1,
        int p2,
        im_t &im1,
        im_t &im2,
        im_t &disp ) {

    if ( !(im1.width == im2.width && im1.height == im2.height  ) ) {
        std::cerr << " Images are not same dimensions." << std::endl;
        exit(-1);
    }

    int width = im1.width;
    int height = im1.height;

    int npix = width;
    int *unravel = new int[2*npix];

    for ( int irow = 0; irow < height; ++irow ) {
        //unsigned char *ref   = im1.data + irow*width;
        //unsigned char *match = im2.data + irow*width;
        //unsigned char *out   = disp.data + irow*width;
        unsigned char *ref   = im1.data;
        unsigned char *match = im2.data;
        unsigned char *out   = disp.data;
        for ( int icol = 0; icol < width; ++icol ) {
            unravel[2*icol+0] = irow;
            unravel[2*icol+1] = icol;
        }
        sgmscan(ndisp,mindisp,p1,p2,width,unravel,npix,ref,match,out);
        std::cout << "\r done row " << irow+1 << " of " << height << std::flush;
    }
    std::cout << std::endl;

    delete[] unravel;

}

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

    //int rad = 7;
    im_t im1, im2, disp;

    std::cout << " Reading im1 " << std::endl;
    readpgm("cones_left.pgm",
            im1.data,
            im1.width,
            im1.height);

    std::cout << " Reading im2 " << std::endl;
    readpgm("cones_right.pgm",
            im2.data,
            im2.width,
            im2.height);

    disp.width  = im1.width;
    disp.height = im1.height;
    disp.data   = new unsigned char[disp.width*disp.height];

    //patchnxcorr(rad,im1,im2,disp);
    int ndisp = 128;
    int mindisp = -(ndisp-1);
    int p1 = 10;
    int p2 = 150;
    std::cout << " ndisp: " << ndisp << std::endl;
    std::cout << " mindisp: " << mindisp << std::endl;
    sgm(ndisp,mindisp,p1,p2,im1,im2,disp);

    writepgm("disp.pgm",
            disp.data,
            disp.width,
            disp.height);

    delete[] im1.data, im2.data, disp.data;

    return 0;
}
<|endoftext|>


<commit_before>
#include "manager.hpp"

#ifdef _WIN32
#include "dirent.h"
#include "fnmatch.h"
#else
#include <dirent.h>
#include <sys/stat.h>
#include <fnmatch.h>
#endif

#include <algorithm>
#include <cstring>
#include <fstream>
#include <sstream>
#include <vector>

#include "../archives/bsaarchive.hpp"

namespace
{

std::vector<std::string> gRootPaths;
Archives::BsaArchive gGlobalBsa;

}

namespace VFS
{

Manager::Manager()
{
}

void Manager::initialize(std::string&& root_path)
{
    if(root_path.empty())
        root_path += "./";
    else if(root_path.back() != '/' && root_path.back() != '\\')
        root_path += "/";

    gGlobalBsa.load(root_path+"GLOBAL.BSA");

    gRootPaths.push_back(std::move(root_path));
}

void Manager::addDataPath(std::string&& path)
{
    if(path.empty())
        path += "./";
    else if(path.back() != '/' && path.back() != '\\')
        path += "/";
    gRootPaths.push_back(std::move(path));
}

IStreamPtr Manager::open(const char *name)
{
    std::unique_ptr<std::ifstream> stream(new std::ifstream());
    // Search in reverse, so newer paths take precedence.
    auto piter = gRootPaths.rbegin();
    while(piter != gRootPaths.rend())
    {
        stream->open((*piter+name).c_str(), std::ios_base::binary);
        if(stream->good()) return IStreamPtr(std::move(stream));
        ++piter;
    }

    return gGlobalBsa.open(name);
}

bool Manager::exists(const char *name)
{
    std::ifstream file;
    for(const std::string &path : gRootPaths)
    {
        file.open((path+name).c_str(), std::ios_base::binary);
        if(file.is_open()) return true;
    }

    return gGlobalBsa.exists(name);
}

void Manager::add_dir(const std::string &path, const std::string &pre, const char *pattern, std::vector<std::string> &names)
{
    DIR *dir = opendir(path.c_str());
    if(!dir) return;

    dirent *ent;
    while((ent=readdir(dir)) != nullptr)
    {
        if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
            continue;

        if(!S_ISDIR(ent->d_type))
        {
            std::string fname = pre + ent->d_name;
            if(!pattern || fnmatch(pattern, fname.c_str(), 0) == 0)
                names.push_back(fname);
        }
        else
        {
            std::string newpath = path+"/"+ent->d_name;
            std::string newpre = pre+ent->d_name+"/";
            add_dir(newpath, newpre, pattern, names);
        }
    }

    closedir(dir);
}

std::vector<std::string> Manager::list(const char *pattern) const
{
    std::vector<std::string> files;

    auto piter = gRootPaths.rbegin();
    while(piter != gRootPaths.rend())
    {
        add_dir(*piter+".", "", pattern, files);
        ++piter;
    }

    if(!pattern)
    {
        const auto &list = gGlobalBsa.list();
        std::copy(list.begin(), list.end(), std::back_inserter(files));
    }
    else
    {
        const auto &list = gGlobalBsa.list();
        std::copy_if(list.begin(), list.end(), std::back_inserter(files),
            [pattern](const std::string &name) -> bool
            {
                const char *dirsep = strrchr(name.c_str(), '/');
                return (fnmatch(pattern, dirsep?dirsep:name.c_str(), 0) == 0);
            }
        );
    }

    return files;
}

} // namespace VFS
<commit_msg>Modified path to fnmatch.h.<commit_after>
#include "manager.hpp"

#ifdef _WIN32
#include "dirent.h"
#include "../misc/fnmatch.h"
#else
#include <dirent.h>
#include <sys/stat.h>
#include <fnmatch.h>
#endif

#include <algorithm>
#include <cstring>
#include <fstream>
#include <sstream>
#include <vector>

#include "../archives/bsaarchive.hpp"

namespace
{

std::vector<std::string> gRootPaths;
Archives::BsaArchive gGlobalBsa;

}

namespace VFS
{

Manager::Manager()
{
}

void Manager::initialize(std::string&& root_path)
{
    if(root_path.empty())
        root_path += "./";
    else if(root_path.back() != '/' && root_path.back() != '\\')
        root_path += "/";

    gGlobalBsa.load(root_path+"GLOBAL.BSA");

    gRootPaths.push_back(std::move(root_path));
}

void Manager::addDataPath(std::string&& path)
{
    if(path.empty())
        path += "./";
    else if(path.back() != '/' && path.back() != '\\')
        path += "/";
    gRootPaths.push_back(std::move(path));
}

IStreamPtr Manager::open(const char *name)
{
    std::unique_ptr<std::ifstream> stream(new std::ifstream());
    // Search in reverse, so newer paths take precedence.
    auto piter = gRootPaths.rbegin();
    while(piter != gRootPaths.rend())
    {
        stream->open((*piter+name).c_str(), std::ios_base::binary);
        if(stream->good()) return IStreamPtr(std::move(stream));
        ++piter;
    }

    return gGlobalBsa.open(name);
}

bool Manager::exists(const char *name)
{
    std::ifstream file;
    for(const std::string &path : gRootPaths)
    {
        file.open((path+name).c_str(), std::ios_base::binary);
        if(file.is_open()) return true;
    }

    return gGlobalBsa.exists(name);
}

void Manager::add_dir(const std::string &path, const std::string &pre, const char *pattern, std::vector<std::string> &names)
{
    DIR *dir = opendir(path.c_str());
    if(!dir) return;

    dirent *ent;
    while((ent=readdir(dir)) != nullptr)
    {
        if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
            continue;

        if(!S_ISDIR(ent->d_type))
        {
            std::string fname = pre + ent->d_name;
            if(!pattern || fnmatch(pattern, fname.c_str(), 0) == 0)
                names.push_back(fname);
        }
        else
        {
            std::string newpath = path+"/"+ent->d_name;
            std::string newpre = pre+ent->d_name+"/";
            add_dir(newpath, newpre, pattern, names);
        }
    }

    closedir(dir);
}

std::vector<std::string> Manager::list(const char *pattern) const
{
    std::vector<std::string> files;

    auto piter = gRootPaths.rbegin();
    while(piter != gRootPaths.rend())
    {
        add_dir(*piter+".", "", pattern, files);
        ++piter;
    }

    if(!pattern)
    {
        const auto &list = gGlobalBsa.list();
        std::copy(list.begin(), list.end(), std::back_inserter(files));
    }
    else
    {
        const auto &list = gGlobalBsa.list();
        std::copy_if(list.begin(), list.end(), std::back_inserter(files),
            [pattern](const std::string &name) -> bool
            {
                const char *dirsep = strrchr(name.c_str(), '/');
                return (fnmatch(pattern, dirsep?dirsep:name.c_str(), 0) == 0);
            }
        );
    }

    return files;
}

} // namespace VFS
<|endoftext|>


<commit_before>#ifndef STAN_MATH_OPENCL_IS_CONSTANT_HPP
#define STAN_MATH_OPENCL_IS_CONSTANT_HPP
#ifdef STAN_OPENCL

#include <stan/math/prim/meta/is_constant.hpp>
#include <stan/math/opencl/matrix_cl.hpp>

namespace stan {

/** \ingroup type_trait
 * Defines a static member named value and sets it to true
 * if the type of the elements in the provided matrix_cl
 * is constant, false otherwise. This is used in
 * the is_constant_all metaprogram.
 * @tparam type of the elements in the matrix_cl
 */
template <typename T>
struct is_constant<math::matrix_cl<T>> : is_constant<std::decay_t<T>> {};

}  // namespace stan

#endif
#endif
<commit_msg>fix is_constant for kernel expressions<commit_after>#ifndef STAN_MATH_OPENCL_IS_CONSTANT_HPP
#define STAN_MATH_OPENCL_IS_CONSTANT_HPP
#ifdef STAN_OPENCL

#include <stan/math/prim/meta/is_constant.hpp>
#include <stan/math/opencl/matrix_cl.hpp>

namespace stan {

/** \ingroup type_trait
 * Defines a static member named value and sets it to true
 * if the type of the elements in the provided matrix_cl
 * is constant, false otherwise. This is used in
 * the is_constant_all metaprogram.
 * @tparam type of the elements in the matrix_cl
 */
template <typename T>
struct is_constant<T, require_all_kernel_expressions_and_none_scalar_t<T>> : std::true_type {};

}  // namespace stan

#endif
#endif
<|endoftext|>


<commit_before>#include <сomplex_t.hpp>
#include <catch.hpp>
SCENARIO("def constructor")
{
	complex_t Complex;
	REQUIRE(Complex.a_() == 0);
	REQUIRE(Complex.b_() == 0);
}

SCENARIO("param constructor")
{
	complex_t Complex(1, 2);
	REQUIRE(Complex.a_() == 1);
	REQUIRE(Complex.b_() == 2);
}

SCENARIO("copy constructor")
{
	complex_t Complex(1, 2);
	complex_t cop(Complex);
	REQUIRE(cop.a_() == 1);
	REQUIRE(cop.b_() == 2);
}

SCENARIO("operator *")
{
	complex_t c1(3, 2);
	complex_t c2(5, 4);
	complex_t c3(15, 8);
	REQUIRE((c1*c2) == c3);
}

SCENARIO("operator /")
{
	complex_t c1(4, 5);
	complex_t c2(4, 5);
	complex_t c3(1, 0);
	REQUIRE((c1 / c2) == c3);
}

SCENARIO("operator +=")
{
	complex_t c1(11, 1);
	complex_t c2(8, 3);
	complex_t c3(19, 4);
	REQUIRE((c1 += c2) == c3);
}

SCENARIO("operator -=")
{
	complex_t c1(6, 10);
	complex_t c2(3, 6);
	complex_t c3(3, 4);
	REQUIRE((c1 -= c2) == c3);
}

SCENARIO("operator *=")
{
	complex_t c1(7, 6);
	complex_t c2(5, 4);
	complex_t c3(11, 58);
	REQUIRE((c1 *= c2) == c3);
}

SCENARIO("operator /=")
{
	complex_t c1(2, 1);
	complex_t c2(2, 1);
	complex_t c3(1, 0);
	REQUIRE((c1 /= c2) == c3);
}

SCENARIO("operator =")
{
	complex_t c1(5, 7);
	complex_t c2 = c1;
	REQUIRE(c2 == c1);
}

SCENARIO("operator ==")
{
	complex_t c1(2, 5);
	complex_t c2(2, 5);
	REQUIRE(c1 == c2);
}
<commit_msg>Update init.cpp<commit_after>#include <сomplex_t.hpp>
#include <catch.hpp>
SCENARIO("def constructor")
{
	complex_t Complex;
	REQUIRE(Complex.a_() == 0);
	REQUIRE(Complex.b_() == 0);
}

SCENARIO("param constructor")
{
	complex_t Complex(1, 2);
	REQUIRE(Complex.a_() == 1);
	REQUIRE(Complex.b_() == 2);
}

SCENARIO("copy constructor")
{
	complex_t Complex(1, 2);
	complex_t cop(Complex);
	REQUIRE(cop.a_() == 1);
	REQUIRE(cop.b_() == 2);
}

SCENARIO("operator *")
{
	complex_t c1(7, 6);
	complex_t c2(5, 4);
	complex_t c3(11, 58);
	REQUIRE((c1*c2) == c3);
}

SCENARIO("operator /")
{
	complex_t c1(4, 5);
	complex_t c2(4, 5);
	complex_t c3(1, 0);
	REQUIRE((c1 / c2) == c3);
}

SCENARIO("operator +=")
{
	complex_t c1(11, 1);
	complex_t c2(8, 3);
	complex_t c3(19, 4);
	REQUIRE((c1 += c2) == c3);
}

SCENARIO("operator -=")
{
	complex_t c1(6, 10);
	complex_t c2(3, 6);
	complex_t c3(3, 4);
	REQUIRE((c1 -= c2) == c3);
}

SCENARIO("operator *=")
{
	complex_t c1(7, 6);
	complex_t c2(5, 4);
	complex_t c3(11, 58);
	REQUIRE((c1 *= c2) == c3);
}

SCENARIO("operator /=")
{
	complex_t c1(2, 1);
	complex_t c2(2, 1);
	complex_t c3(1, 0);
	REQUIRE((c1 /= c2) == c3);
}

SCENARIO("operator =")
{
	complex_t c1(5, 7);
	complex_t c2 = c1;
	REQUIRE(c2 == c1);
}

SCENARIO("operator ==")
{
	complex_t c1(2, 5);
	complex_t c2(2, 5);
	REQUIRE(c1 == c2);
}
<|endoftext|>


<commit_before>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
SCENARIO("add")
{
	Tree <int> a;
	bool b=a.add(5);
	REQUIRE(b == 1);
}
SCENARIO("find")
{
	Tree<int> a;
	a.add(5);
	bool b = a.find(5);
	REQUIRE(b == 1);
}
SCENARIO("del1")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.del(7);
	bool b = a.find(7);
	REQUIRE(b == 0);
}
SCENARIO("del2")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del3")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(1);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del4")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(3);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del5")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(3);
	bool b = a.del(15);;
	REQUIRE(b == 0);
}
SCENARIO("file")
{
	Tree<int> a, c;
	c.add(3);
	c.add(2);
	c.add(1);
	c.add(5);
	c.pr("Tr.txt");
	a.file_tree("Tr.txt");
	bool b = a.find(3);
	REQUIRE(b == 1);
	b = a.find(2);
	REQUIRE(b == 1);
	b = a.find(1);
	REQUIRE(b == 1);
	b = a.find(5);
	REQUIRE(b == 1);
}
SCENARIO("BST delete non inserted element", "[delete]")
{
	Tree<int> tree = {8};
	REQUIRE( !tree.del(4) );
	REQUIRE( !tree.isEmpty() );
}
SCENARIO("BST delete root without children", "[delete]")
{
	Tree<int> tree = {8};
	REQUIRE( tree.del(8) );
	REQUIRE( tree.isEmpty() );
}
SCENARIO("BST delete root with one child", "[delete]")
{
	Tree<int> tree = {8, 4, 3};
	REQUIRE( tree.remove(8) );
	REQUIRE( tree == Tree<int>({4, 3}) );
}
SCENARIO("BST delete root with children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.remove(8) );
	REQUIRE( tree == BinarySearchTree<int>({9, 4, 3, 10, 13, 11, 12}) );
}
SCENARIO("BST delete non root without children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.remove(3) );
	REQUIRE( tree == BinarySearchTree<int>({8, 4, 10, 9, 13, 11, 12}) );
}
SCENARIO("BST delete non root with one child", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.remove(11) );
	REQUIRE( tree == BinarySearchTree<int>({8, 4, 3, 10, 9, 13, 12}) );
}
SCENARIO("BST delete non root with children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.remove(10) );
	REQUIRE( tree == BinarySearchTree<int>({8, 4, 3, 11, 9, 13, 12}) );
}
<commit_msg>Update init.cpp<commit_after>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
SCENARIO("add")
{
	Tree <int> a;
	bool b=a.add(5);
	REQUIRE(b == 1);
}
SCENARIO("find")
{
	Tree<int> a;
	a.add(5);
	bool b = a.find(5);
	REQUIRE(b == 1);
}
SCENARIO("del1")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.del(7);
	bool b = a.find(7);
	REQUIRE(b == 0);
}
SCENARIO("del2")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del3")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(1);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del4")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(3);
	a.del(2);
	bool b = a.find(2);
	REQUIRE(b == 0);
}
SCENARIO("del5")
{
	Tree<int> a;
	a.add(5);
	a.add(4);
	a.add(7);
	a.add(8);
	a.add(2);
	a.add(6);
	a.add(3);
	bool b = a.del(15);;
	REQUIRE(b == 0);
}
SCENARIO("file")
{
	Tree<int> a, c;
	c.add(3);
	c.add(2);
	c.add(1);
	c.add(5);
	c.pr("Tr.txt");
	a.file_tree("Tr.txt");
	bool b = a.find(3);
	REQUIRE(b == 1);
	b = a.find(2);
	REQUIRE(b == 1);
	b = a.find(1);
	REQUIRE(b == 1);
	b = a.find(5);
	REQUIRE(b == 1);
}
SCENARIO("BST delete non inserted element", "[delete]")
{
	Tree<int> tree = {8};
	REQUIRE( !tree.del(4) );
	REQUIRE( !tree.isEmpty() );
}
SCENARIO("BST delete root without children", "[delete]")
{
	Tree<int> tree = {8};
	REQUIRE( tree.del(8) );
	REQUIRE( tree.isEmpty() );
}
SCENARIO("BST delete root with one child", "[delete]")
{
	Tree<int> tree = {8, 4, 3};
	REQUIRE( tree.del(8) );
	REQUIRE( tree == Tree<int>({4, 3}) );
}
SCENARIO("BST delete root with children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.del(8) );
	REQUIRE( tree == Tree<int>({9, 4, 3, 10, 13, 11, 12}) );
}
SCENARIO("BST delete non root without children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.del(3) );
	REQUIRE( tree == Tree<int>({8, 4, 10, 9, 13, 11, 12}) );
}
SCENARIO("BST delete non root with one child", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.del(11) );
	REQUIRE( tree == Tree<int>({8, 4, 3, 10, 9, 13, 12}) );
}
SCENARIO("BST delete non root with children", "[delete]")
{
	Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
	REQUIRE( tree.del(10) );
	REQUIRE( tree == Tree<int>({8, 4, 3, 11, 9, 13, 12}) );
}
<|endoftext|>


<commit_before>#include "SharedResource.h"

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

BOOST_AUTO_TEST_CASE(Basic_construction)
{
    SharedResource<int> shared_int;
}

BOOST_AUTO_TEST_CASE(Construction_with_argument)
{
    SharedResource<int> shared_int(5);
}

BOOST_AUTO_TEST_CASE(Construction_no_default_constructor)
{
    struct TestClass
    {
        TestClass() = delete;
        TestClass(int) { }
    };

    SharedResource<TestClass> stc2(5);
}

BOOST_AUTO_TEST_CASE(Basic_Locking)
{
    SharedResource<int> shared_int(0);
    shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Locking_with_accessor)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Accessor_isValid)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
    BOOST_CHECK(shared_int_accessor.isValid());
    auto shared_int_accessor_new(std::move(shared_int_accessor));
    BOOST_CHECK(!shared_int_accessor.isValid());
    BOOST_CHECK(shared_int_accessor_new.isValid());
}

<commit_msg>Tests for SharedResource dereferencing<commit_after>#include "SharedResource.h"

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

BOOST_AUTO_TEST_CASE(Basic_construction)
{
    SharedResource<int> shared_test_class;
}

BOOST_AUTO_TEST_CASE(Construction_with_argument)
{
    SharedResource<int> shared_test_class(5);
}

BOOST_AUTO_TEST_CASE(Construction_no_default_constructor)
{
    struct TestClass
    {
        TestClass() = delete;
        TestClass(int) { }
    };

    SharedResource<TestClass> stc2(5);
}

BOOST_AUTO_TEST_CASE(Basic_Locking)
{
    SharedResource<int> shared_test_class(0);
    shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Locking_with_accessor)
{
    SharedResource<int> shared_test_class(0);
    auto shared_int_accessor = shared_test_class.lock();
}

BOOST_AUTO_TEST_CASE(Accessor_isValid)
{
    SharedResource<int> shared_test_class(0);
    auto shared_int_accessor = shared_test_class.lock();
    BOOST_CHECK(shared_int_accessor.isValid());
    auto shared_int_accessor_new(std::move(shared_int_accessor));
    BOOST_CHECK(!shared_int_accessor.isValid());
    BOOST_CHECK(shared_int_accessor_new.isValid());
}

BOOST_AUTO_TEST_CASE(Acessor_dereferencing_1)
{
    SharedResource<int> shared_test_class(0);
    auto shared_int_accessor = shared_test_class.lock();
    BOOST_CHECK_EQUAL(0, *shared_int_accessor);
    *shared_int_accessor = 5;
    BOOST_CHECK_EQUAL(5, *shared_int_accessor);
}

BOOST_AUTO_TEST_CASE(Acessor_dereferencing_2)
{
    struct TestClass
    {
        TestClass(int a) : m_a(a) { }
        void set(int a) noexcept { m_a = a; }
        int get() const noexcept { return m_a; }
    private:
        int m_a;
    };

    SharedResource<TestClass> shared_test_class(0);
    auto shared_int_accessor = shared_test_class.lock();
    BOOST_CHECK_EQUAL(0, shared_int_accessor->get());
    shared_int_accessor->set(5);
    BOOST_CHECK_EQUAL(5, shared_int_accessor->get());
}

<|endoftext|>


<commit_before>/* Copyright (c) 2015, Daniel C. Dillon
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "../include/cpuaff/cpuaff.hpp"

TEST_CASE("affinity_manager", "[affinity_manager]")
{
    cpuaff::affinity_manager manager;

    SECTION("affinity_manager::initialize()")
    {
        REQUIRE(manager.initialize());
        REQUIRE(manager.has_cpus());

#if defined(CPUAFF_PCI_SUPPORTED)
        REQUIRE(manager.has_pci_devices());
#endif
    }

    SECTION("affinity_manager member functions")
    {
        REQUIRE(manager.initialize());

        cpuaff::cpu cpu;
        cpuaff::cpu_set cpus;

#if defined(CPUAFF_PCI_SUPPORTED)
        cpuaff::pci_device_set devices;
        cpuaff::pci_device device;
#endif

        REQUIRE(manager.get_cpu_from_index(cpu, 0));
        REQUIRE(manager.get_cpu_from_id(cpu, cpu.id()));
        REQUIRE(manager.get_cpu_from_id(cpu, cpu.id().get()));
        REQUIRE(manager.get_cpu_from_spec(
            cpu,
            cpuaff::cpu_spec(cpu.socket(), cpu.core(), cpu.processing_unit())));

        REQUIRE(manager.get_cpus(cpus));
        REQUIRE(manager.get_cpus_by_numa(cpus, cpu.numa()));
        REQUIRE(manager.get_cpus_by_socket(cpus, cpu.socket()));
        REQUIRE(manager.get_cpus_by_core(cpus, cpu.core()));
        REQUIRE(
            manager.get_cpus_by_processing_unit(cpus, cpu.processing_unit()));
        REQUIRE(manager.get_cpus_by_socket_and_core(
            cpus, cpu.socket(), cpu.core()));

#if defined(CPUAFF_PCI_SUPPORTED)
        REQUIRE(manager.get_pci_devices(devices));
        device = *devices.begin();
        REQUIRE(manager.get_pci_device_for_address(device, device.address()));
        REQUIRE(
            manager.get_pci_device_for_address(device, device.address().get()));
        REQUIRE(manager.get_pci_devices_by_spec(
            devices,
            cpuaff::pci_device_spec(device.vendor(), device.device())));
        REQUIRE(manager.get_pci_devices_by_numa(devices, device.numa()));
        REQUIRE(manager.get_pci_devices_by_vendor(devices, device.vendor()));
        REQUIRE(manager.get_nearby_cpus(cpus, device));
#endif

        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() > 0);

        cpuaff::cpu_set new_affinity;
        new_affinity.insert(cpu);
        REQUIRE(manager.set_affinity(new_affinity));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == new_affinity.size());

        if (cpus.size() == new_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = new_affinity.begin();
            cpuaff::cpu_set::iterator jend = new_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        REQUIRE(manager.get_cpus(new_affinity));
        REQUIRE(manager.set_affinity(new_affinity));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == new_affinity.size());

        if (cpus.size() == new_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = new_affinity.begin();
            cpuaff::cpu_set::iterator jend = new_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        REQUIRE(manager.pin(cpu));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == 1);
        REQUIRE(*cpus.begin() == cpu);
    }
}

TEST_CASE("affinity_stack", "[affinity_stack]")
{
    SECTION("affinity_stack member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::affinity_stack stack(manager);

        cpuaff::cpu_set original_affinity;
        cpuaff::cpu_set new_affinity;
        cpuaff::cpu_set cpus;

        REQUIRE(stack.get_affinity(original_affinity));
        REQUIRE(original_affinity.size() > 0);
        REQUIRE(stack.push_affinity());
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == original_affinity.size());

        if (cpus.size() == original_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = original_affinity.begin();
            cpuaff::cpu_set::iterator jend = original_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        new_affinity.insert(*original_affinity.begin());

        REQUIRE(stack.set_affinity(new_affinity));
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == 1);
        REQUIRE(*cpus.begin() == *new_affinity.begin());

        REQUIRE(stack.pop_affinity());
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == original_affinity.size());

        if (cpus.size() == original_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = original_affinity.begin();
            cpuaff::cpu_set::iterator jend = original_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }
    }
}

TEST_CASE("round_robin_allocator", "[round_robin_allocator]")
{
    SECTION("round_robin_allocator member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::round_robin_allocator allocator;
        cpuaff::cpu_set cpus;
        cpuaff::cpu_set allocated_cpus;
        cpuaff::cpu cpu;

        REQUIRE(manager.get_cpus(cpus));
        REQUIRE(allocator.initialize(cpus));

        for (int i = 0; i < cpus.size() * 2; ++i)
        {
            cpu = allocator.allocate();
            bool test = cpu.socket() >= 0 && cpu.core() >= 0 &&
                        cpu.processing_unit() >= 0;
            REQUIRE(test);
        }

        REQUIRE(allocator.allocate(allocated_cpus, 4));

        bool test =
            allocated_cpus.size() == 4 ||
            (allocated_cpus.size() < 4 && allocated_cpus.size() == cpus.size());
        REQUIRE(test);
    }
}

TEST_CASE("native_cpu_mapper", "[native_cpu_mapper]")
{
    SECTION("native_cpu_mapper member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::native_cpu_mapper mapper;

        if (mapper.initialize(manager))
        {
            cpuaff::cpu_set cpus;
            manager.get_cpus(cpus);

            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();

            for (; i != iend; ++i)
            {
                cpuaff::native_cpu_mapper::native_cpu_wrapper_type native;
                cpuaff::cpu cpu;

                REQUIRE(mapper.get_native_from_cpu(native, *i));
                REQUIRE(mapper.get_cpu_from_native(cpu, native));
                REQUIRE(mapper.get_cpu_from_native(cpu, native.get()));
            }
        }
    }
}
<commit_msg>changed test to only test for pci devices if they could be properly loaded<commit_after>/* Copyright (c) 2015, Daniel C. Dillon
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "../include/cpuaff/cpuaff.hpp"

TEST_CASE("affinity_manager", "[affinity_manager]")
{
    cpuaff::affinity_manager manager;

    SECTION("affinity_manager::initialize()")
    {
        REQUIRE(manager.initialize());
        REQUIRE(manager.has_cpus());
    }

    SECTION("affinity_manager member functions")
    {
        REQUIRE(manager.initialize());

        cpuaff::cpu cpu;
        cpuaff::cpu_set cpus;

#if defined(CPUAFF_PCI_SUPPORTED)
        cpuaff::pci_device_set devices;
        cpuaff::pci_device device;
#endif

        REQUIRE(manager.get_cpu_from_index(cpu, 0));
        REQUIRE(manager.get_cpu_from_id(cpu, cpu.id()));
        REQUIRE(manager.get_cpu_from_id(cpu, cpu.id().get()));
        REQUIRE(manager.get_cpu_from_spec(
            cpu,
            cpuaff::cpu_spec(cpu.socket(), cpu.core(), cpu.processing_unit())));

        REQUIRE(manager.get_cpus(cpus));
        REQUIRE(manager.get_cpus_by_numa(cpus, cpu.numa()));
        REQUIRE(manager.get_cpus_by_socket(cpus, cpu.socket()));
        REQUIRE(manager.get_cpus_by_core(cpus, cpu.core()));
        REQUIRE(
            manager.get_cpus_by_processing_unit(cpus, cpu.processing_unit()));
        REQUIRE(manager.get_cpus_by_socket_and_core(
            cpus, cpu.socket(), cpu.core()));

#if defined(CPUAFF_PCI_SUPPORTED)
        if (manager.has_pci_devices())
        {
            REQUIRE(manager.get_pci_devices(devices));
            device = *devices.begin();
            REQUIRE(manager.get_pci_device_for_address(device, device.address()));
            REQUIRE(
                manager.get_pci_device_for_address(device, device.address().get()));
            REQUIRE(manager.get_pci_devices_by_spec(
                devices,
                cpuaff::pci_device_spec(device.vendor(), device.device())));
            REQUIRE(manager.get_pci_devices_by_numa(devices, device.numa()));
            REQUIRE(manager.get_pci_devices_by_vendor(devices, device.vendor()));
            REQUIRE(manager.get_nearby_cpus(cpus, device));
        }
#endif

        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() > 0);

        cpuaff::cpu_set new_affinity;
        new_affinity.insert(cpu);
        REQUIRE(manager.set_affinity(new_affinity));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == new_affinity.size());

        if (cpus.size() == new_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = new_affinity.begin();
            cpuaff::cpu_set::iterator jend = new_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        REQUIRE(manager.get_cpus(new_affinity));
        REQUIRE(manager.set_affinity(new_affinity));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == new_affinity.size());

        if (cpus.size() == new_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = new_affinity.begin();
            cpuaff::cpu_set::iterator jend = new_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        REQUIRE(manager.pin(cpu));
        REQUIRE(manager.get_affinity(cpus));
        REQUIRE(cpus.size() == 1);
        REQUIRE(*cpus.begin() == cpu);
    }
}

TEST_CASE("affinity_stack", "[affinity_stack]")
{
    SECTION("affinity_stack member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::affinity_stack stack(manager);

        cpuaff::cpu_set original_affinity;
        cpuaff::cpu_set new_affinity;
        cpuaff::cpu_set cpus;

        REQUIRE(stack.get_affinity(original_affinity));
        REQUIRE(original_affinity.size() > 0);
        REQUIRE(stack.push_affinity());
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == original_affinity.size());

        if (cpus.size() == original_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = original_affinity.begin();
            cpuaff::cpu_set::iterator jend = original_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }

        new_affinity.insert(*original_affinity.begin());

        REQUIRE(stack.set_affinity(new_affinity));
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == 1);
        REQUIRE(*cpus.begin() == *new_affinity.begin());

        REQUIRE(stack.pop_affinity());
        REQUIRE(stack.get_affinity(cpus));
        REQUIRE(cpus.size() == original_affinity.size());

        if (cpus.size() == original_affinity.size())
        {
            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();
            cpuaff::cpu_set::iterator j = original_affinity.begin();
            cpuaff::cpu_set::iterator jend = original_affinity.end();

            for (; i != iend && j != jend; ++i, ++j)
            {
                REQUIRE((*i) == (*j));
            }
        }
    }
}

TEST_CASE("round_robin_allocator", "[round_robin_allocator]")
{
    SECTION("round_robin_allocator member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::round_robin_allocator allocator;
        cpuaff::cpu_set cpus;
        cpuaff::cpu_set allocated_cpus;
        cpuaff::cpu cpu;

        REQUIRE(manager.get_cpus(cpus));
        REQUIRE(allocator.initialize(cpus));

        for (int i = 0; i < cpus.size() * 2; ++i)
        {
            cpu = allocator.allocate();
            bool test = cpu.socket() >= 0 && cpu.core() >= 0 &&
                        cpu.processing_unit() >= 0;
            REQUIRE(test);
        }

        REQUIRE(allocator.allocate(allocated_cpus, 4));

        bool test =
            allocated_cpus.size() == 4 ||
            (allocated_cpus.size() < 4 && allocated_cpus.size() == cpus.size());
        REQUIRE(test);
    }
}

TEST_CASE("native_cpu_mapper", "[native_cpu_mapper]")
{
    SECTION("native_cpu_mapper member functions")
    {
        cpuaff::affinity_manager manager;

        REQUIRE(manager.initialize());

        cpuaff::native_cpu_mapper mapper;

        if (mapper.initialize(manager))
        {
            cpuaff::cpu_set cpus;
            manager.get_cpus(cpus);

            cpuaff::cpu_set::iterator i = cpus.begin();
            cpuaff::cpu_set::iterator iend = cpus.end();

            for (; i != iend; ++i)
            {
                cpuaff::native_cpu_mapper::native_cpu_wrapper_type native;
                cpuaff::cpu cpu;

                REQUIRE(mapper.get_native_from_cpu(native, *i));
                REQUIRE(mapper.get_cpu_from_native(cpu, native));
                REQUIRE(mapper.get_cpu_from_native(cpu, native.get()));
            }
        }
    }
}
<|endoftext|>


<commit_before>#include "./importer.h"
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <QDebug>
#include <string>
#include <vector>
#include "./utils/path_helper.h"

Importer::Importer()
{
}

Importer::~Importer()
{
}

const aiScene *Importer::readScene(std::string filename)
{
  if (scenes.count(filename))
    return scenes[filename];

  std::string path = absolutePathOfProjectRelativePath(filename);
  const aiScene *scene = importer.ReadFile(
      path, aiProcess_CalcTangentSpace | aiProcess_Triangulate |
                aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);

  if (!scene)
  {
    qCritical() << "Could not load " << path.c_str();
    exit(1);
  }

  scenes[filename] = scene;

  return scene;
}

std::shared_ptr<Graphics::Mesh> Importer::import(std::string filename,
                                                 int meshIndex)
{
  const aiScene *scene = readScene(filename);
  auto importedMesh = scene->mMeshes[meshIndex];
  return std::shared_ptr<Graphics::Mesh>(new Graphics::Mesh(
      importedMesh, scene->mMaterials[importedMesh->mMaterialIndex]));
}

std::vector<std::shared_ptr<Graphics::Mesh>>
Importer::importAll(std::string filename)
{
  const aiScene *scene = readScene(filename);

  std::vector<std::shared_ptr<Graphics::Mesh>> result;
  for (unsigned int i = 0; i < scene->mNumMeshes; ++i)
    result.push_back(import(filename, i));

  return result;
}

<commit_msg>Add debug message to Importer.<commit_after>#include "./importer.h"
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <QDebug>
#include <string>
#include <vector>
#include "./utils/path_helper.h"

Importer::Importer()
{
}

Importer::~Importer()
{
}

const aiScene *Importer::readScene(std::string filename)
{
  qDebug() << "readScene:" << filename.c_str();

  if (scenes.count(filename))
    return scenes[filename];

  std::string path = absolutePathOfProjectRelativePath(filename);
  const aiScene *scene = importer.ReadFile(
      path, aiProcess_CalcTangentSpace | aiProcess_Triangulate |
                aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);

  if (!scene)
  {
    qCritical() << "Could not load " << path.c_str();
    exit(1);
  }

  scenes[filename] = scene;

  return scene;
}

std::shared_ptr<Graphics::Mesh> Importer::import(std::string filename,
                                                 int meshIndex)
{
  const aiScene *scene = readScene(filename);
  auto importedMesh = scene->mMeshes[meshIndex];
  return std::shared_ptr<Graphics::Mesh>(new Graphics::Mesh(
      importedMesh, scene->mMaterials[importedMesh->mMaterialIndex]));
}

std::vector<std::shared_ptr<Graphics::Mesh>>
Importer::importAll(std::string filename)
{
  const aiScene *scene = readScene(filename);

  std::vector<std::shared_ptr<Graphics::Mesh>> result;
  for (unsigned int i = 0; i < scene->mNumMeshes; ++i)
    result.push_back(import(filename, i));

  return result;
}

<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/core.hxx>
#include <abc/iostream.hxx>
#include <abc/trace.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::stream_base

namespace abc {

stream_base::stream_base() :
   m_enc(text::encoding::unknown),
   m_lterm(text::line_terminator::unknown) {
}

/*virtual*/ stream_base::~stream_base() {
}

/*virtual*/ void stream_base::set_encoding(text::encoding enc) {
   m_enc = enc;
}

/*virtual*/ void stream_base::set_line_terminator(text::line_terminator lterm) {
   m_lterm = lterm;
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::istream

namespace abc {

/*virtual*/ istream::~istream() {
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::ostream

namespace abc {

/*virtual*/ ostream::~ostream() {
}

/*virtual*/ void ostream::flush() {
}

_ostream_print_helper_impl::_ostream_print_helper_impl(ostream * pos, istr const & sFormat) :
   m_pos(pos),
   // write_format_up_to_next_repl() will increment this to 0 or set it to a non-negative number.
   m_iSubstArg(unsigned(-1)),
   m_sFormat(sFormat),
   m_itFormatToWriteBegin(sFormat.cbegin()) {
}

void _ostream_print_helper_impl::run() {
   // Since this specialization has no replacements, verify that the format string doesn’t specify
   // any either.
   if (write_format_up_to_next_repl()) {
      ABC_THROW(index_error, (m_iSubstArg));
   }
}

void _ostream_print_helper_impl::throw_index_error() {
   ABC_THROW(index_error, (m_iSubstArg));
}

bool _ostream_print_helper_impl::write_format_up_to_next_repl() {
   ABC_TRACE_FN((this));

   // Search for the next replacement, if any.
   istr::const_iterator it(m_itFormatToWriteBegin), itReplFieldBegin, itEnd(m_sFormat.cend());
   char_t ch;
   for (;;) {
      if (it >= itEnd) {
         // The format string is over; write any characters not yet written.
         write_format_up_to(itEnd);
         // Report that no more replacement fields were found.
         return false;
      }
      ch = *it++;
      if (ch == CL('{') || ch == CL('}')) {
         if (ch == CL('{')) {
            // Mark the beginning of the replacement field.
            itReplFieldBegin = it - 1;
            if (it >= itEnd) {
               throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
            }
            ch = *it;
            if (ch != CL('{')) {
               // We found the beginning of a replacement field.
               break;
            }
         } else if (ch == CL('}')) {
            if (it >= itEnd || *it != CL('}')) {
               throw_syntax_error(SL("single '}' encountered in format string"), it - 1);
            }
         }
         // Convert “{{” into “{” or “}}” into “}”.
         // Write up to and including the first brace.
         write_format_up_to(it);
         // The next call to write_format_up_to() will skip the second brace.
         m_itFormatToWriteBegin = ++it;
      }
   }

   // Check if we have an argument index.
   if (ch >= CL('0') && ch <= CL('9')) {
      // Consume as many digits as there are, and convert them into the argument index.
      unsigned iArg(0);
      do {
         iArg *= 10;
         iArg += unsigned(ch - CL('0'));
      } while (++it < itEnd && (ch = *it, ch >= CL('0') && ch <= CL('9')));
      if (it >= itEnd) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      // Save this index as the last used one.
      m_iSubstArg = iArg;
   } else {
      // The argument index is missing, so just use the next one.
      ++m_iSubstArg;
   }

   // Check for a conversion specifier; defaults to string.
   char_t chConversion(CL('s'));
   if (ch == CL('!')) {
      if (++it >= itEnd) {
         throw_syntax_error(SL("expected conversion specifier"), it);
      }
      ch = *it;
      switch (ch) {
         case CL('s'):
// TODO: case CL('r'):
// TODO: case CL('a'):
            chConversion = ch;
            ABC_UNUSED_ARG(chConversion);
            break;
         default:
            throw_syntax_error(SL("unknown conversion specifier"), it);
      }
      if (++it >= itEnd) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      ch = *it;
   }

   // Check for a format specification.
   if (ch == CL(':')) {
      if (++it >= itEnd) {
         throw_syntax_error(SL("expected format specification"), it);
      }
      m_pchReplFormatSpecBegin = it.base();
      // Find the end of the replacement field.
      it = m_sFormat.find(U32CL('}'), it);
      if (it == m_sFormat.cend()) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      m_pchReplFormatSpecEnd = it.base();
   } else {
      // If there’s no format specification, it must be the end of the replacement field.
      if (ch != CL('}')) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      // Set the format specification to nothing.
      m_pchReplFormatSpecBegin = NULL;
      m_pchReplFormatSpecEnd = NULL;
   }

   // Write the format string characters up to the beginning of the replacement.
   write_format_up_to(itReplFieldBegin);
   // Update this, so the next call to write_format_up_to() will skip over this replacement field.
   m_itFormatToWriteBegin = it + 1 /*'}'*/;
   // Report that a substitution must be written.
   return true;
}

void _ostream_print_helper_impl::throw_syntax_error(
   istr const & sDescription, istr::const_iterator it
) const {
   // +1 because the first character is 1, to human beings.
   ABC_THROW(syntax_error, (sDescription, m_sFormat, unsigned(it - m_sFormat.cbegin() + 1)));
}

void _ostream_print_helper_impl::write_format_up_to(istr::const_iterator itUpTo) {
   ABC_TRACE_FN((this/*, itUpTo*/));

   if (itUpTo > m_itFormatToWriteBegin) {
      m_pos->write_raw(
         m_itFormatToWriteBegin.base(),
         sizeof(char_t) * size_t(itUpTo - m_itFormatToWriteBegin),
         text::utf_traits<>::host_encoding
      );
      m_itFormatToWriteBegin = itUpTo;
   }
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::iostream

namespace abc {

iostream::iostream() :
   stream_base(),
   istream(),
   ostream() {
}

/*virtual*/ iostream::~iostream() {
}

} //namespace abc

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

<commit_msg>Include iterator in ABC_TRACE_FN() arguments<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/core.hxx>
#include <abc/iostream.hxx>
#include <abc/trace.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::stream_base

namespace abc {

stream_base::stream_base() :
   m_enc(text::encoding::unknown),
   m_lterm(text::line_terminator::unknown) {
}

/*virtual*/ stream_base::~stream_base() {
}

/*virtual*/ void stream_base::set_encoding(text::encoding enc) {
   m_enc = enc;
}

/*virtual*/ void stream_base::set_line_terminator(text::line_terminator lterm) {
   m_lterm = lterm;
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::istream

namespace abc {

/*virtual*/ istream::~istream() {
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::ostream

namespace abc {

/*virtual*/ ostream::~ostream() {
}

/*virtual*/ void ostream::flush() {
}

_ostream_print_helper_impl::_ostream_print_helper_impl(ostream * pos, istr const & sFormat) :
   m_pos(pos),
   // write_format_up_to_next_repl() will increment this to 0 or set it to a non-negative number.
   m_iSubstArg(unsigned(-1)),
   m_sFormat(sFormat),
   m_itFormatToWriteBegin(sFormat.cbegin()) {
}

void _ostream_print_helper_impl::run() {
   // Since this specialization has no replacements, verify that the format string doesn’t specify
   // any either.
   if (write_format_up_to_next_repl()) {
      ABC_THROW(index_error, (m_iSubstArg));
   }
}

void _ostream_print_helper_impl::throw_index_error() {
   ABC_THROW(index_error, (m_iSubstArg));
}

bool _ostream_print_helper_impl::write_format_up_to_next_repl() {
   ABC_TRACE_FN((this));

   // Search for the next replacement, if any.
   istr::const_iterator it(m_itFormatToWriteBegin), itReplFieldBegin, itEnd(m_sFormat.cend());
   char_t ch;
   for (;;) {
      if (it >= itEnd) {
         // The format string is over; write any characters not yet written.
         write_format_up_to(itEnd);
         // Report that no more replacement fields were found.
         return false;
      }
      ch = *it++;
      if (ch == CL('{') || ch == CL('}')) {
         if (ch == CL('{')) {
            // Mark the beginning of the replacement field.
            itReplFieldBegin = it - 1;
            if (it >= itEnd) {
               throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
            }
            ch = *it;
            if (ch != CL('{')) {
               // We found the beginning of a replacement field.
               break;
            }
         } else if (ch == CL('}')) {
            if (it >= itEnd || *it != CL('}')) {
               throw_syntax_error(SL("single '}' encountered in format string"), it - 1);
            }
         }
         // Convert “{{” into “{” or “}}” into “}”.
         // Write up to and including the first brace.
         write_format_up_to(it);
         // The next call to write_format_up_to() will skip the second brace.
         m_itFormatToWriteBegin = ++it;
      }
   }

   // Check if we have an argument index.
   if (ch >= CL('0') && ch <= CL('9')) {
      // Consume as many digits as there are, and convert them into the argument index.
      unsigned iArg(0);
      do {
         iArg *= 10;
         iArg += unsigned(ch - CL('0'));
      } while (++it < itEnd && (ch = *it, ch >= CL('0') && ch <= CL('9')));
      if (it >= itEnd) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      // Save this index as the last used one.
      m_iSubstArg = iArg;
   } else {
      // The argument index is missing, so just use the next one.
      ++m_iSubstArg;
   }

   // Check for a conversion specifier; defaults to string.
   char_t chConversion(CL('s'));
   if (ch == CL('!')) {
      if (++it >= itEnd) {
         throw_syntax_error(SL("expected conversion specifier"), it);
      }
      ch = *it;
      switch (ch) {
         case CL('s'):
// TODO: case CL('r'):
// TODO: case CL('a'):
            chConversion = ch;
            ABC_UNUSED_ARG(chConversion);
            break;
         default:
            throw_syntax_error(SL("unknown conversion specifier"), it);
      }
      if (++it >= itEnd) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      ch = *it;
   }

   // Check for a format specification.
   if (ch == CL(':')) {
      if (++it >= itEnd) {
         throw_syntax_error(SL("expected format specification"), it);
      }
      m_pchReplFormatSpecBegin = it.base();
      // Find the end of the replacement field.
      it = m_sFormat.find(U32CL('}'), it);
      if (it == m_sFormat.cend()) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      m_pchReplFormatSpecEnd = it.base();
   } else {
      // If there’s no format specification, it must be the end of the replacement field.
      if (ch != CL('}')) {
         throw_syntax_error(SL("unmatched '{' in format string"), itReplFieldBegin);
      }
      // Set the format specification to nothing.
      m_pchReplFormatSpecBegin = NULL;
      m_pchReplFormatSpecEnd = NULL;
   }

   // Write the format string characters up to the beginning of the replacement.
   write_format_up_to(itReplFieldBegin);
   // Update this, so the next call to write_format_up_to() will skip over this replacement field.
   m_itFormatToWriteBegin = it + 1 /*'}'*/;
   // Report that a substitution must be written.
   return true;
}

void _ostream_print_helper_impl::throw_syntax_error(
   istr const & sDescription, istr::const_iterator it
) const {
   // +1 because the first character is 1, to human beings.
   ABC_THROW(syntax_error, (sDescription, m_sFormat, unsigned(it - m_sFormat.cbegin() + 1)));
}

void _ostream_print_helper_impl::write_format_up_to(istr::const_iterator itUpTo) {
   ABC_TRACE_FN((this, itUpTo));

   if (itUpTo > m_itFormatToWriteBegin) {
      m_pos->write_raw(
         m_itFormatToWriteBegin.base(),
         sizeof(char_t) * size_t(itUpTo - m_itFormatToWriteBegin),
         text::utf_traits<>::host_encoding
      );
      m_itFormatToWriteBegin = itUpTo;
   }
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::iostream

namespace abc {

iostream::iostream() :
   stream_base(),
   istream(),
   ostream() {
}

/*virtual*/ iostream::~iostream() {
}

} //namespace abc

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

<|endoftext|>


<commit_before>// stdafx.cpp : source file that includes just the standard includes
// Boost Unit Test Project.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#define BOOST_TEST_MODULE MyTest

#include "stdafx.h"
#include <stdlib.h>
#include <string>
#include <exception>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

string get_env(const string& env)
{
	// getenv is depracated for microsoft compiler
#pragma warning(disable:4996)
	auto c_res = getenv(env.c_str());
#pragma warning(default:4996)

	if(!c_res)
		throw logic_error("Environment variable "s + env + " is not set.");

	return c_res;
}

string get_test_file_full_path(const string& filename)
{
	path p(get_env("TEST_FILES_PATH"));
	p /= filename;

	if (!exists(p))
		throw logic_error(p.string() + ": don't exist. Did you set TEST_FILES_PATH environment variable correctly?");

	return p.string();
}
<commit_msg>setting TEST_FILES_PATH is now optional<commit_after>// stdafx.cpp : source file that includes just the standard includes
// Boost Unit Test Project.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#define BOOST_TEST_MODULE MyTest

#include "stdafx.h"
#include <stdlib.h>
#include <string>
#include <exception>
#include <boost/filesystem.hpp>
#include <Windows.h>

using namespace std;
using namespace boost::filesystem;

string get_default_test_files_dir_path()
{
	char pBuf[MAX_PATH + 1];
	int bytes = GetModuleFileNameA(NULL, pBuf, MAX_PATH);
	path p(pBuf);
	p.remove_filename();
	p /= "../../test_files/";
	if (!exists(p))
		throw logic_error("test_files path not found. Please set TEST_FILES_PATH environment variable.");

	return p.string();
}

string get_env(const string& env)
{
	// getenv is depracated for microsoft compiler
#pragma warning(disable:4996)
	auto c_res = getenv(env.c_str());
#pragma warning(default:4996)

	return (c_res ? c_res : get_default_test_files_dir_path());
}

string get_test_file_full_path(const string& filename)
{
	path p(get_env("TEST_FILES_PATH"));
	p /= filename;

	if (!exists(p))
		throw logic_error(p.string() + ": don't exist. Did you set TEST_FILES_PATH environment variable correctly?");

	return p.string();
}
<|endoftext|>