<commit_before>#include <iostream>
#include "ctvm.h"
#include "ctvm_util.h"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <Magick++.h>

int main(int argc, char **argv)
{
	/* Test CTVM.dylib Link */
	std::cout << std::endl;
	std::cout << "Testing libctvm Link." << std::endl;
	BoostDoubleMatrix DummySinogram(0, 0);
	BoostDoubleVector DummyAngles(0);
	// BoostDoubleMatrix DummyReconstruction = tval3_reconstruction(DummySinogram,DummyAngles);
	std::cout << "    " << "Passed." << std::endl;

	/* Test CTVM_util.dylib Link */
	std::cout << std::endl;
	std::cout << "Allocating tiny(3x3) random matrix..." << std::endl;
	BoostDoubleMatrix RandomMatrix = CreateRandomMatrix(3, 3);
	std::cout << "    " << RandomMatrix << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Rasterized Version..." << std::endl;
	std::cout << "    " << MatrixToVector(RandomMatrix) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Back to Matrix..." << std::endl;
	std::cout << "    " << VectorToMatrix(MatrixToVector(RandomMatrix), 3, 3) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Allocating large(1000x1000) random matrix..." << std::endl;
	BoostDoubleMatrix RandomMatrixLarge = CreateRandomMatrix(1000, 1000);
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Testing Normalization" << std::endl;
	BoostDoubleMatrix TestMatrix(3, 3);
	TestMatrix(0, 0) = 1; TestMatrix(0, 1) = 5; TestMatrix(0, 2) = 3;
	TestMatrix(1, 0) = 2; TestMatrix(1, 1) = 11; TestMatrix(1, 2) = 5;
	TestMatrix(2, 0) = 1; TestMatrix(2, 1) = 10; TestMatrix(2, 2) = 6;
	std::cout << "Original Matrix: " << TestMatrix << std::endl;
	std::cout << "Normalized: " << NormalizeMatrix(TestMatrix) << std::endl;

	/* Test ImageMagick */
	std::cout << std::endl;
	using namespace Magick;
	InitializeMagick("");

	std::cout << "Testing ImageMagick Link." << std::endl;
	Image someImage;
	someImage.read("C:\\data\\peppers.jpg");
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Creating Novel Image" << std::endl;
	Image anotherImage;
	anotherImage.size(Geometry(32, 32));         // Specify the dimensionality
	Pixels anotherImageView(anotherImage);      // Get a view of the image
	PixelPacket aPixel;
	aPixel.red = ColorGray::scaleDoubleToQuantum(0.5);
	aPixel.green = ColorGray::scaleDoubleToQuantum(0.5);
	aPixel.blue = ColorGray::scaleDoubleToQuantum(0.5);
	*(anotherImageView.get(16, 16, 1, 1)) = aPixel;
	anotherImage.type(GrayscaleType);           // Specify the color type
	anotherImageView.sync();
	anotherImage.write("C:\\data\\testoutimage.png");
	std::cout << "    " << "Passed." << std::endl;

	/* Test CTVM Image Load */
	std::cout << std::endl;
	std::cout << "Testing CTVM Image Load." << std::endl;
	BoostDoubleMatrix ImageMatrix = LoadImage("C:\\data\\peppers.jpg");
	std::cout << "Image Data:" << std::endl;
	std::cout << ImageMatrix(0, 0) << " " << ImageMatrix(0, 1) << " " << ImageMatrix(0, 3) << std::endl;
	std::cout << ImageMatrix(1, 0) << " " << ImageMatrix(1, 1) << " " << ImageMatrix(1, 3) << std::endl;
	std::cout << ImageMatrix(2, 0) << " " << ImageMatrix(2, 1) << " " << ImageMatrix(2, 3) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Testing CTVM Image Write." << std::endl;
	WriteImage(ImageMatrix, "C:\\data\\test_peppers.jpg");
	std::cout << "    " << "Passed." << std::endl;

	/* Initialisation */
	BoostDoubleMatrix A(2, 4), W(4, 2), NU(4, 2);
	BoostDoubleVector U(4), U1(9), B(2), LAMBDA(2);

	A(0, 0) = 1; A(0, 1) = 0; A(0, 2) = 1; A(0, 3) = 0;
	A(1, 0) = 0; A(1, 1) = 1; A(1, 2) = 1; A(1, 3) = 1;

	W(0, 0) = -1; W(0, 1) = 1;
	W(1, 0) = 0; W(1, 1) = 1;
	W(2, 0) = -1; W(2, 1) = 0;
	W(3, 0) = 0; W(3, 1) = 1;

	NU(0, 0) = 2; NU(0, 1) = 1;
	NU(1, 0) = 1; NU(1, 1) = 0;
	NU(2, 0) = 0; NU(2, 1) = 2;
	NU(3, 0) = 1; NU(3, 1) = 3;

	U(0) = 1;
	U(1) = 2;
	U(2) = 0;
	U(3) = 1;

	U1(0) = 1;
	U1(1) = 2;
	U1(2) = 0;
	U1(3) = 1;
	U1(4) = 3;
	U1(5) = -2;
	U1(6) = 0;
	U1(7) = -1;
	U1(8) = 0;

	B(0) = 1;
	B(1) = 2;

	LAMBDA(0) = 2;
	LAMBDA(1) = 1;

	double beta = sqrt(2);
	double mu = 3;

	/* Test Gradient2DMatrix */
	std::cout << std::endl;
	std::cout << "Testing CTVM 2D Gradient for all i." << std::endl;
	BoostDoubleMatrix X = VectorToMatrix(U, 2, 2);
	BoostDoubleMatrix GradientMatrix = Gradient2DMatrix(U);
	BoostDoubleMatrix Di = Norm_Gradient2DMatrix(U1, 4);
	std::cout << "Original Matrix: " << X << std::endl;
	std::cout << "Gradients DiU (right gradient, down gradient): " << GradientMatrix << std::endl;
	std::cout << "Original Vector: " << U1 << std::endl;
	std::cout << " D(4) times U: " << prod(Di,U1) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	/*Test Lagrangian function*/
	std::cout << std::endl;
	double L = Lagrangian(A, U, B, W, NU, LAMBDA, beta, mu);

	std::cout << "Lagrangian: " << L << std::endl; // expected result L = 8.6213
	std::cout << "    " << "Passed." << std::endl;

	/*Test Shrinke function*/
	std::cout << std::endl;
	int ii = 1;
	BoostDoubleVector DiUk = Gradient2D(U, ii);
	BoostDoubleVector NUi (2);
	for (int jj = 0; jj < 2; ++jj) { NUi(jj) = NU(ii, jj); }
	BoostDoubleVector SHRIKE = Shrike(DiUk, NUi, beta);

	std::cout << "W(i,l+1): " << SHRIKE << std::endl; // expected result SHRIKE = ( -0.2988585, -0.42265)
	std::cout << "    " << "Passed." << std::endl;

return 0;
}<commit_msg>correct<commit_after>#include <iostream>
#include "ctvm.h"
#include "ctvm_util.h"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <Magick++.h>

int main(int argc, char **argv)
{
	/* Test CTVM.dylib Link */
	std::cout << std::endl;
	std::cout << "Testing libctvm Link." << std::endl;
	BoostDoubleMatrix DummySinogram(0, 0);
	BoostDoubleVector DummyAngles(0);
	// BoostDoubleMatrix DummyReconstruction = tval3_reconstruction(DummySinogram,DummyAngles);
	std::cout << "    " << "Passed." << std::endl;

	/* Test CTVM_util.dylib Link */
	std::cout << std::endl;
	std::cout << "Allocating tiny(3x3) random matrix..." << std::endl;
	BoostDoubleMatrix RandomMatrix = CreateRandomMatrix(3, 3);
	std::cout << "    " << RandomMatrix << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Rasterized Version..." << std::endl;
	std::cout << "    " << MatrixToVector(RandomMatrix) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Back to Matrix..." << std::endl;
	std::cout << "    " << VectorToMatrix(MatrixToVector(RandomMatrix), 3, 3) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Allocating large(1000x1000) random matrix..." << std::endl;
	BoostDoubleMatrix RandomMatrixLarge = CreateRandomMatrix(1000, 1000);
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Testing Normalization" << std::endl;
	BoostDoubleMatrix TestMatrix(3, 3);
	TestMatrix(0, 0) = 1; TestMatrix(0, 1) = 5; TestMatrix(0, 2) = 3;
	TestMatrix(1, 0) = 2; TestMatrix(1, 1) = 11; TestMatrix(1, 2) = 5;
	TestMatrix(2, 0) = 1; TestMatrix(2, 1) = 10; TestMatrix(2, 2) = 6;
	std::cout << "Original Matrix: " << TestMatrix << std::endl;
	std::cout << "Normalized: " << NormalizeMatrix(TestMatrix) << std::endl;

	/* Test ImageMagick */
	std::cout << std::endl;
	using namespace Magick;
	InitializeMagick("");

	std::cout << "Testing ImageMagick Link." << std::endl;
	Image someImage;
	someImage.read("C:\\data\\peppers.jpg");
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Creating Novel Image" << std::endl;
	Image anotherImage;
	anotherImage.size(Geometry(32, 32));         // Specify the dimensionality
	Pixels anotherImageView(anotherImage);      // Get a view of the image
	PixelPacket aPixel;
	aPixel.red = ColorGray::scaleDoubleToQuantum(0.5);
	aPixel.green = ColorGray::scaleDoubleToQuantum(0.5);
	aPixel.blue = ColorGray::scaleDoubleToQuantum(0.5);
	*(anotherImageView.get(16, 16, 1, 1)) = aPixel;
	anotherImage.type(GrayscaleType);           // Specify the color type
	anotherImageView.sync();
	anotherImage.write("C:\\data\\testoutimage.png");
	std::cout << "    " << "Passed." << std::endl;

	/* Test CTVM Image Load */
	std::cout << std::endl;
	std::cout << "Testing CTVM Image Load." << std::endl;
	BoostDoubleMatrix ImageMatrix = LoadImage("C:\\data\\peppers.jpg");
	std::cout << "Image Data:" << std::endl;
	std::cout << ImageMatrix(0, 0) << " " << ImageMatrix(0, 1) << " " << ImageMatrix(0, 3) << std::endl;
	std::cout << ImageMatrix(1, 0) << " " << ImageMatrix(1, 1) << " " << ImageMatrix(1, 3) << std::endl;
	std::cout << ImageMatrix(2, 0) << " " << ImageMatrix(2, 1) << " " << ImageMatrix(2, 3) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	std::cout << "Testing CTVM Image Write." << std::endl;
	WriteImage(ImageMatrix, "C:\\data\\test_peppers.jpg");
	std::cout << "    " << "Passed." << std::endl;

	/* Initialisation */
	BoostDoubleMatrix A(2, 4), W(4, 2), NU(4, 2);
	BoostDoubleVector U(4), U1(9), B(2), LAMBDA(2);

	A(0, 0) = 1; A(0, 1) = 0; A(0, 2) = 1; A(0, 3) = 0;
	A(1, 0) = 0; A(1, 1) = 1; A(1, 2) = 1; A(1, 3) = 1;

	W(0, 0) = -1; W(0, 1) = 1;
	W(1, 0) = 0; W(1, 1) = 1;
	W(2, 0) = -1; W(2, 1) = 0;
	W(3, 0) = 0; W(3, 1) = 1;

	NU(0, 0) = 2; NU(0, 1) = 1;
	NU(1, 0) = 1; NU(1, 1) = 0;
	NU(2, 0) = 0; NU(2, 1) = 2;
	NU(3, 0) = 1; NU(3, 1) = 3;

	U(0) = 1;
	U(1) = 2;
	U(2) = 0;
	U(3) = 1;

	U1(0) = 1;
	U1(1) = 2;
	U1(2) = 0;
	U1(3) = 1;
	U1(4) = 3;
	U1(5) = -2;
	U1(6) = 0;
	U1(7) = -1;
	U1(8) = 0;

	B(0) = 1;
	B(1) = 2;

	LAMBDA(0) = 2;
	LAMBDA(1) = 1;

	double beta = sqrt(2);
	double mu = 3;

	/* Test Gradient2DMatrix */
	std::cout << std::endl;
	std::cout << "Testing CTVM 2D Gradient for all i." << std::endl;
	BoostDoubleMatrix X = VectorToMatrix(U, 2, 2);
	BoostDoubleMatrix GradientMatrix = Gradient2DMatrix(U);
	BoostDoubleMatrix Di = Unit_Gradient2DMatrix(U1, 4);
	std::cout << "Original Matrix: " << X << std::endl;
	std::cout << "Gradients DiU (right gradient, down gradient): " << GradientMatrix << std::endl;
	std::cout << "Original Vector: " << U1 << std::endl;
	std::cout << " D(4) times U: " << prod(Di,U1) << std::endl;
	std::cout << "    " << "Passed." << std::endl;

	/*Test Lagrangian function*/
	std::cout << std::endl;
	double L = Lagrangian(A, U, B, W, NU, LAMBDA, beta, mu);

	std::cout << "Lagrangian: " << L << std::endl; // expected result L = 8.6213
	std::cout << "    " << "Passed." << std::endl;

	/*Test Shrinke function*/
	std::cout << std::endl;
	int ii = 1;
	BoostDoubleVector DiUk = Gradient2D(U, ii);
	BoostDoubleVector NUi (2);
	for (int jj = 0; jj < 2; ++jj) { NUi(jj) = NU(ii, jj); }
	BoostDoubleVector SHRIKE = Shrike(DiUk, NUi, beta);

	std::cout << "W(i,l+1): " << SHRIKE << std::endl; // expected result SHRIKE = ( -0.2988585, -0.42265)
	std::cout << "    " << "Passed." << std::endl;

return 0;
}<|endoftext|>


<commit_before>// This file is for a basic string library so I do not have to use <cstring>

int getStringLength(char *str)
{
    int result= 0;

    for(int index = 0; str[index]; index++)
    {
        ++result;
    }
    return result;
}

// Utliity function
void clearTempStringsToNull(char *str)
{
    for(int index = 0; str[index] ; index++)
    {
        str[index] = 0;
    }
}

//TODO: make another compreString that is case insensitive
bool compareString(char *fString, char *sString) // first/second String
{
    int index = 0;
    bool result = false;

    while(fString[index])
    {
        if(fString[index] != sString[index])
        { break;}

        index++;
    }
    if (!sString[index])
    {
        result = true;
    }

    return result;
}

//NOTE(Dustin): You will have to free this memory if you use this function
char* CopyString(char *strToCopy)
{
    char *result = (char*)calloc(getStringLength(strToCopy)+1, sizeof(char));

    for (int index = 0; strToCopy[index]; index++)
    {
        result[index] = strToCopy[index];
    }
    return result;
}

//NOTE(Dustin): Overloaded function, the calle defines were the copy gets placed
void CopyString(char *strToCopy, char *placeToPutCopiedString)
{
    for (int index = 0; strToCopy[index]; index++)
    {
        placeToPutCopiedString[index] = strToCopy[index];
    }
}

//NOTE(Dustin): Enduser needs to free the resultstring
char* CatString(char *originString, char *strToCat)
{
    int originLength = getStringLength(originString);
    int catStrLength = getStringLength(strToCat);
    int outstringLength = (originLength + catStrLength);
    int catStrIndex = 0;

    char *result = ((char*)calloc(outstringLength+1, sizeof(char)));

    for(int index = 0; index < outstringLength; index++)
    {
        if(index < originLength)
        {
            result[index] = originString[index];
        }
        else
        {
            result[index] = strToCat[catStrIndex];
            catStrIndex++;
        }
    }
    return result;
}

//Overloaded function to let calle tell where to put the result
void CatString(char *originString, char *strToCat, char *outputString)
{
    int originLength = getStringLength(originString);
    int catStrLength = getStringLength(strToCat);
    int outstringLength = (originLength + catStrLength);
    int catStrIndex = 0;

    for(int index = 0; index < outstringLength; index++)
    {
        if(index < originLength)
        {
            outputString[index] = originString[index];
        }
        else
        {
            outputString[index] =strToCat[catStrIndex];
            catStrLength++;
        }
    }
}

// if no outputstring then calle has to free | if you don't give me a valid savePlace you get nothing back about where you were in the string/array
char* SplitString(char *inputString, char strDelim, char *savePlace, char *outputString=NULL)
{
    bool isParsingStringToDelim = true;
    int index = 0;
    int resultIndex = 0;

    if(inputString)
    {
        while (isParsingStringToDelim)
        {
            //TODO: make this take multiple possible delim characters
            if(inputString[index] == strDelim)
            {
                clearTempStringsToNull(savePlace);
                isParsingStringToDelim = false;
                index++;

                if (savePlace)
                {
                    for(int localIndex = 0; inputString[index]; localIndex++)
                    {
                        savePlace[localIndex] = inputString[index];
                        index++;
                    }
                }
            }
            else
            {
                if (inputString[index])
                {
                    resultIndex++;
                    index++;
                }
                else
                {
                    break;
                }
            }
        }

        if(resultIndex)
        {
            if(!outputString)
            {
                char *result = ((char*)calloc(resultIndex+1, sizeof(char)));

                for(int localIndex = 0; localIndex < resultIndex; localIndex++)
                {
                    result[localIndex] = inputString[localIndex];
                }

                return result;
            }
            else
            {
                for(int localIndex = 0; localIndex < resultIndex; localIndex++)
                {
                    outputString[localIndex] = inputString[localIndex];
                }
                return outputString; // make sure if this is in a if that it doesnt fail all the time
            }
        }
    }

    return NULL;
}
<commit_msg>continued refining of spechtStringLub<commit_after>// This file is for a basic string library so I do not have to use <cstring>

int getStringLength(char *str)
{
    int result= 0;

    for(int index = 0; str[index]; index++)
    {
        ++result;
    }
    return result;
}

// Utliity function
void clearTempStringsToNull(char *str)
{
    for(int index = 0; str[index] ; index++)
    {
        str[index] = 0;
    }
}

//TODO: make another compreString that is case insensitive
bool compareString(char *fString, char *sString) // first/second String
{
    int index = 0;
    bool result = false;

    while(fString[index])
    {
        if(fString[index] != sString[index])
        { break;}

        index++;
    }
    if (!sString[index])
    {
        result = true;

    }
    return result;
}

//NOTE(dustin): if you don't pass a placetoputcopiedstring then you will have to free the result
char* CopyString(char *strToCopy, char *placeToPutCopiedString=NULL)
{
    if(!placeToPutCopiedString)
    {
        char *result = (char*)calloc(getStringLength(strToCopy)+1, sizeof(char));

        for (int index = 0; strToCopy[index]; index++)
        {
            result[index] = strToCopy[index];
        }
        return result;
    }
    else
    {
        for (int index = 0; strToCopy[index]; index++)
        {
            placeToPutCopiedString[index] = strToCopy[index];
        }
        return placeToPutCopiedString; // if you check for a return, this make it not fail everytime
    }
}

//NOTE(Dustin): Enduser needs to free the resultstring
char* CatString(char *originString, char *strToCat, char *outputString=NULL)
{
    int originLength = getStringLength(originString);
    int catStrLength = getStringLength(strToCat);
    int outstringLength = (originLength + catStrLength);
    int catStrIndex = 0;

    if(!outputString)
    {
        char *result = ((char*)calloc(outstringLength+1, sizeof(char)));

        for(int index = 0; index < outstringLength; index++)
        {
            if(index < originLength)
            {
                result[index] = originString[index];
            }
            else
            {
                result[index] = strToCat[catStrIndex];
                catStrIndex++;
            }
        }
        return result;
    }
    else
    {
        for(int index = 0; index < outstringLength; index++)
        {
            if(index < originLength)
            {
                outputString[index] = originString[index];
            }
            else
            {
                outputString[index] =strToCat[catStrIndex];
                catStrLength++;
            }
        }
        return outputString; // if you check for a return, this  makes it not just fail
    }
}

// if no outputstring then calle has to free | if you don't give me a valid savePlace you get nothing back about where you were in the string/array
char* SplitString(char *inputString, char strDelim, char *savePlace, char *outputString=NULL)
{
    bool isParsingStringToDelim = true;
    int index = 0;
    int resultIndex = 0;

    if(inputString)
    {
        while (isParsingStringToDelim)
        {
            //TODO: make this take multiple possible delim characters
            if(inputString[index] == strDelim)
            {
                clearTempStringsToNull(savePlace);
                isParsingStringToDelim = false;
                index++;

                if (savePlace)
                {
                    for(int localIndex = 0; inputString[index]; localIndex++)
                    {
                        savePlace[localIndex] = inputString[index];
                        index++;
                    }
                }
            }
            else
            {
                if (inputString[index])
                {
                    resultIndex++;
                    index++;
                }
                else
                {
                    break;
                }
            }
        }

        if(resultIndex)
        {
            if(!outputString)
            {
                char *result = ((char*)calloc(resultIndex+1, sizeof(char)));

                for(int localIndex = 0; localIndex < resultIndex; localIndex++)
                {
                    result[localIndex] = inputString[localIndex];
                }

                return result;
            }
            else
            {
                for(int localIndex = 0; localIndex < resultIndex; localIndex++)
                {
                    outputString[localIndex] = inputString[localIndex];
                }
                return outputString; // make sure if this is in a if that it doesnt fail all the time
            }
        }
    }

    return NULL;
}
<|endoftext|>


<commit_before>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>

#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>

using namespace std;

namespace bfs = boost::filesystem;

NS_IZENELIB_IR_BEGIN

namespace indexmanager
{

FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
        :field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
    skipInterval_ = pIndexer_->getSkipInterval();
    maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
    if (! pIndexer_->isRealTime())
    {
        std::string sorterName = field_+".tmp";
        bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
        sorterFullPath_= path.string();
        sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 130000000);
    }
    else
        alloc_ = new boost::scoped_alloc(recycle_);
}

FieldIndexer::~FieldIndexer()
{
    /*
        InMemoryPostingMap::iterator iter = postingMap_.begin()
        for(; iter !=postingMap_.end(); ++iter)
        {
            delete iter->second;
        }
    */
    if (alloc_) delete alloc_;
    pMemCache_ = NULL;
    if (sorter_) delete sorter_;
}

void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
    char* pData = data;
    memcpy(pData, &(termId), sizeof(termId));
    pData += sizeof(termId);
    memcpy(pData, &(docId), sizeof(docId));
    pData += sizeof(docId);
    memcpy(pData, &(offset), sizeof(offset));
    pData += sizeof(offset);
}

void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
    if (pIndexer_->isRealTime())
    {
        InMemoryPosting* curPosting;
        for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
        {
            InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
            if (postingIter == postingMap_.end())
            {
                //curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
                curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
                postingMap_[iter->termId_] = curPosting;
            }
            else
                curPosting = postingIter->second;
            curPosting->add(docid, iter->offset_);
        }
    }
    else
    {
        if (!sorter_)
            sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 130000000);

        char data[12];
        for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
        {
            convert(data,iter->termId_,docid,iter->offset_);
            sorter_->add_data(12, data);
        }
    }
}

void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
    InMemoryPosting* curPosting;

    for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
    {
        InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
        if (postingIter == postingMap_.end())
        {
            curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
            postingMap_[iter->first] = curPosting;
        }
        else
            curPosting = postingIter->second;

        ForwardIndexOffset::iterator	endit = iter->second->end();
        for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
            curPosting->add(docid, *it);
    }
}

void FieldIndexer::reset()
{
    InMemoryPosting* pPosting;
    for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
    {
        pPosting = iter->second;
        if (!pPosting->hasNoChunk())
        {
            pPosting->reset();		///clear posting data
        }
    }
    postingMap_.clear();
    termCount_ = 0;
}

void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
    pVocWriter->writeInt(tid);					///write term id
    pVocWriter->writeInt(termInfo.docFreq_);		///write df
    pVocWriter->writeInt(termInfo.ctf_);			///write ctf
    pVocWriter->writeInt(termInfo.lastDocID_);		///write last doc id
    pVocWriter->writeInt(termInfo.skipLevel_);		///write skip level
    pVocWriter->writeLong(termInfo.skipPointer_);	///write skip list offset offset
    pVocWriter->writeLong(termInfo.docPointer_);	///write document posting offset
    pVocWriter->writeInt(termInfo.docPostingLen_);	///write document posting length (without skiplist)
    pVocWriter->writeLong(termInfo.positionPointer_);	///write position posting offset
    pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}

fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
    vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();

    IndexOutput* pVocWriter = pWriterDesc->getVocOutput();

    termid_t tid;
    InMemoryPosting* pPosting;
    fileoffset_t vocOffset = pVocWriter->getFilePointer();
    TermInfo termInfo;

    if (pIndexer_->isRealTime())
    {
        izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
        for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
        {
            pPosting = iter->second;
            pPosting->setDirty(true);
            if (!pPosting->hasNoChunk())
            {
                tid = iter->first;
                pPosting->write(pWriterDesc, termInfo);		///write posting data
                writeTermInfo(pVocWriter,tid,termInfo);
                pPosting->reset();								///clear posting data
                termInfo.reset();
                termCount_++;
            }
            //delete pPosting;
            //pPosting = NULL;
        }

        postingMap_.clear();

        delete alloc_;
        alloc_ = new boost::scoped_alloc(recycle_);
    }
    else
    {
        sorter_->sort();
        FILE* f = fopen(sorterFullPath_.c_str(),"r");
        fseek(f, 0, SEEK_SET);
        uint64_t count;
        fread(&count, sizeof(uint64_t), 1, f);

        pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
        termid_t lastTerm = BAD_DOCID;
        try
        {
        for (uint64_t i = 0; i < count; ++i)
        {
            uint8_t len;
            fread(&len, sizeof(uint8_t), 1, f);
            uint32_t docId,offset;
            fread(&tid, sizeof(uint32_t), 1, f);
            fread(&docId, sizeof(uint32_t), 1, f);
            fread(&offset, sizeof(uint32_t), 1, f);

            if(tid != lastTerm && lastTerm != BAD_DOCID)
            {
                if (!pPosting->hasNoChunk())
                {
                    pPosting->write(pWriterDesc, termInfo); 	///write posting data
                    writeTermInfo(pVocWriter, lastTerm, termInfo);
                    pPosting->reset();								///clear posting data
                    pMemCache_->flushMem();
                    termInfo.reset();
                    termCount_++;
                }
            }
            pPosting->add(docId, offset);
            lastTerm = tid;
        }
        }catch(std::exception& e)
        {
        cout<<e.what()<<endl;
        }

        if (!pPosting->hasNoChunk())
        {
            pPosting->write(pWriterDesc, termInfo);	///write posting data
            writeTermInfo(pVocWriter, lastTerm, termInfo);
            pPosting->reset(); 							///clear posting data
            pMemCache_->flushMem();
            termInfo.reset();
            termCount_++;
        }

        fclose(f);
        sorter_->clear_files();
        delete sorter_;
        sorter_ = NULL;
        delete pPosting;
    }

    fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
    int64_t vocLength = vocDescOffset - vocOffset;
    ///begin write vocabulary descriptor
    pVocWriter->writeLong(vocLength);	///<VocLength(Int64)>
    pVocWriter->writeLong(termCount_);	///<TermCount(Int64)>
    ///end write vocabulary descriptor

    return vocDescOffset;
}

TermReader* FieldIndexer::termReader()
{
    izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
    return new InMemoryTermReader(getField(),this);
}

}

NS_IZENELIB_IR_END

<commit_msg>recover<commit_after>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>

#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>

using namespace std;

namespace bfs = boost::filesystem;

NS_IZENELIB_IR_BEGIN

namespace indexmanager
{

FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
        :field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
    skipInterval_ = pIndexer_->getSkipInterval();
    maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
    if (! pIndexer_->isRealTime())
    {
        std::string sorterName = field_+".tmp";
        bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
        sorterFullPath_= path.string();
        sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);
    }
    else
        alloc_ = new boost::scoped_alloc(recycle_);
}

FieldIndexer::~FieldIndexer()
{
    /*
        InMemoryPostingMap::iterator iter = postingMap_.begin()
        for(; iter !=postingMap_.end(); ++iter)
        {
            delete iter->second;
        }
    */
    if (alloc_) delete alloc_;
    pMemCache_ = NULL;
    if (sorter_) delete sorter_;
}

void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
    char* pData = data;
    memcpy(pData, &(termId), sizeof(termId));
    pData += sizeof(termId);
    memcpy(pData, &(docId), sizeof(docId));
    pData += sizeof(docId);
    memcpy(pData, &(offset), sizeof(offset));
    pData += sizeof(offset);
}

void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
    if (pIndexer_->isRealTime())
    {
        InMemoryPosting* curPosting;
        for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
        {
            InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
            if (postingIter == postingMap_.end())
            {
                //curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
                curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
                postingMap_[iter->termId_] = curPosting;
            }
            else
                curPosting = postingIter->second;
            curPosting->add(docid, iter->offset_);
        }
    }
    else
    {
        if (!sorter_)
            sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);

        char data[12];
        for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
        {
            convert(data,iter->termId_,docid,iter->offset_);
            sorter_->add_data(12, data);
        }
    }
}

void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
    InMemoryPosting* curPosting;

    for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
    {
        InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
        if (postingIter == postingMap_.end())
        {
            curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
            postingMap_[iter->first] = curPosting;
        }
        else
            curPosting = postingIter->second;

        ForwardIndexOffset::iterator	endit = iter->second->end();
        for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
            curPosting->add(docid, *it);
    }
}

void FieldIndexer::reset()
{
    InMemoryPosting* pPosting;
    for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
    {
        pPosting = iter->second;
        if (!pPosting->hasNoChunk())
        {
            pPosting->reset();		///clear posting data
        }
    }
    postingMap_.clear();
    termCount_ = 0;
}

void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
    pVocWriter->writeInt(tid);					///write term id
    pVocWriter->writeInt(termInfo.docFreq_);		///write df
    pVocWriter->writeInt(termInfo.ctf_);			///write ctf
    pVocWriter->writeInt(termInfo.lastDocID_);		///write last doc id
    pVocWriter->writeInt(termInfo.skipLevel_);		///write skip level
    pVocWriter->writeLong(termInfo.skipPointer_);	///write skip list offset offset
    pVocWriter->writeLong(termInfo.docPointer_);	///write document posting offset
    pVocWriter->writeInt(termInfo.docPostingLen_);	///write document posting length (without skiplist)
    pVocWriter->writeLong(termInfo.positionPointer_);	///write position posting offset
    pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}

fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
    vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();

    IndexOutput* pVocWriter = pWriterDesc->getVocOutput();

    termid_t tid;
    InMemoryPosting* pPosting;
    fileoffset_t vocOffset = pVocWriter->getFilePointer();
    TermInfo termInfo;

    if (pIndexer_->isRealTime())
    {
        izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
        for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
        {
            pPosting = iter->second;
            pPosting->setDirty(true);
            if (!pPosting->hasNoChunk())
            {
                tid = iter->first;
                pPosting->write(pWriterDesc, termInfo);		///write posting data
                writeTermInfo(pVocWriter,tid,termInfo);
                pPosting->reset();								///clear posting data
                termInfo.reset();
                termCount_++;
            }
            //delete pPosting;
            //pPosting = NULL;
        }

        postingMap_.clear();

        delete alloc_;
        alloc_ = new boost::scoped_alloc(recycle_);
    }
    else
    {
        sorter_->sort();
        FILE* f = fopen(sorterFullPath_.c_str(),"r");
        fseek(f, 0, SEEK_SET);
        uint64_t count;
        fread(&count, sizeof(uint64_t), 1, f);

        pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
        termid_t lastTerm = BAD_DOCID;
        try
        {
        for (uint64_t i = 0; i < count; ++i)
        {
            uint8_t len;
            fread(&len, sizeof(uint8_t), 1, f);
            uint32_t docId,offset;
            fread(&tid, sizeof(uint32_t), 1, f);
            fread(&docId, sizeof(uint32_t), 1, f);
            fread(&offset, sizeof(uint32_t), 1, f);

            if(tid != lastTerm && lastTerm != BAD_DOCID)
            {
                if (!pPosting->hasNoChunk())
                {
                    pPosting->write(pWriterDesc, termInfo); 	///write posting data
                    writeTermInfo(pVocWriter, lastTerm, termInfo);
                    pPosting->reset();								///clear posting data
                    pMemCache_->flushMem();
                    termInfo.reset();
                    termCount_++;
                }
            }
            pPosting->add(docId, offset);
            lastTerm = tid;
        }
        }catch(std::exception& e)
        {
        cout<<e.what()<<endl;
        }

        if (!pPosting->hasNoChunk())
        {
            pPosting->write(pWriterDesc, termInfo);	///write posting data
            writeTermInfo(pVocWriter, lastTerm, termInfo);
            pPosting->reset(); 							///clear posting data
            pMemCache_->flushMem();
            termInfo.reset();
            termCount_++;
        }

        fclose(f);
        sorter_->clear_files();
        delete sorter_;
        sorter_ = NULL;
        delete pPosting;
    }

    fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
    int64_t vocLength = vocDescOffset - vocOffset;
    ///begin write vocabulary descriptor
    pVocWriter->writeLong(vocLength);	///<VocLength(Int64)>
    pVocWriter->writeLong(termCount_);	///<TermCount(Int64)>
    ///end write vocabulary descriptor

    return vocDescOffset;
}

TermReader* FieldIndexer::termReader()
{
    izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
    return new InMemoryTermReader(getField(),this);
}

}

NS_IZENELIB_IR_END

<|endoftext|>


<commit_before>#include "Swampert.h"
#include "j1App.h"
#include "j1Pathfinding.h"
#include "j1Audio.h"

Swampert::Swampert()
{
}

Swampert::~Swampert()
{
}

bool Swampert::Awake(pugi::xml_node &conf)
{
	std::string temp = conf.attribute("dir").as_string("");
	if (temp == "up")
		direction = UP;
	else if (temp == "down")
		direction = DOWN;
	else if (temp == "left")
		direction = LEFT;
	else
		direction = RIGHT;
	hp = conf.attribute("hp").as_int(0);
	attack = conf.attribute("attack").as_int(0);
	speed = conf.attribute("speed").as_int(0);
	name = conf.attribute("name").as_string("");
	position.x = conf.attribute("pos_x").as_int(0);
	position.y = conf.attribute("pos_y").as_int(0);
	active = conf.attribute("active").as_bool(false);

	return true;
}

bool Swampert::Start()
{
	pokemon_player = true;
	state = IDLE;
	scale = App->win->GetScale();
	offset_x = 7;
	offset_y = 17;
	gamestate = TIMETOPLAY;
	timetoplay = SDL_GetTicks();
	movable = true;
	collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 15, 15 }, COLLIDER_PLAYER, this);
	timetoplay = SDL_GetTicks();
	reset_distance = false;
	reset_run = true;

	return true;
}

bool Swampert::Update()
{
	// STATE MACHINE ------------------
	if (gamestate == INGAME)
	{
		if (pokemon_player)
		{
			//pokemon controlled by player
			switch (state)
			{
			case IDLE:
			{
				Idle();
				break;
			}
			case WALKING:
			{
				Walking();
				break;
			}
			case ATTACKING:
			{
				Attack();
				break;
			}
			/*
			case SPECIALATTACK:
			{
				SpecialAttack();
				break;
			}
			*/
			default:
			{
				break;
			}

			}
		}
		else
		{
			//Pokemon IA
			switch (state)
			{
			case IDLE:
			{
				Idle_IA();
				break;
			}
			case WALKING:
			{
				Walking_IA();
				break;
			}
			case ATTACKING:
			{
				Attack_IA();
				break;
			}
			/*
			case SPECIALATTACK:
			{
				SpecialAttack();
				break;
			}
			*/
			default:
			{
				break;
			}

			}
		}

	}
	else if (gamestate == INMENU)
	{

	}
	else if (gamestate == TIMETOPLAY)
	{
		if (SDL_GetTicks() - timetoplay > 1000)
		{
			gamestate = INGAME;
		}
	}

	//Collision follow the player
	collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
	return true;
}

void Swampert::Draw()
{
	App->anim_manager->Drawing_Manager(state, direction, position, 7);
}

bool Swampert::CleanUp()
{
	return true;
}

void Swampert::OnCollision(Collider* c1, Collider* c2)
{
	if (c1 != nullptr && c2 != nullptr)
	{
		if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
		{

		}
	}
}

bool Swampert::Idle()
{
	//IDLE SCEPTYLE
	if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
	{
		state = WALKING;
		CheckOrientation();
	}

	else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
	{
		state = ATTACKING;
		current_animation = App->anim_manager->GetAnimation(state, direction, 7); //this number may need to be changed?
		current_animation->Reset();
	}

	else
	{
		state = IDLE;
	}
	return true;
}

bool Swampert::Walking()
{
	walking = false;
	Move();

	if (walking == false)
	{
		state = IDLE;
	}

	else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
	{
		state = ATTACKING;
		current_animation = App->anim_manager->GetAnimation(state, direction, 7); //This number may need to be changed?
		current_animation->Reset();
	}

	else
	{
		state = WALKING;
	}
	return false;
}

bool Swampert::Move()
{
	if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
	{
		direction = LEFT;
		//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT);
		int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
		if (temp == 0)
		{
			position.x -= speed;
		}

		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
	{
		direction = DOWN;
		//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
		int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
		if (temp == 0)
		{
			position.y += speed;
		}

		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
	{
		direction = RIGHT;
		//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
		int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
		if (temp == 0)
		{
			position.x += speed;
		}
		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
	{
		direction = UP;
		//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
		int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
		if (temp == 0)
		{
			position.y -= speed;
		}
		walking = true;
	}
	return walking;
}

bool Swampert::Attack()
{
	if (attacker)
	{
		if (current_animation->Finished())
		{
			App->collision->EraseCollider(collision_attack);
			attacker = false;
			current_animation->Reset();
			current_animation = nullptr;
			state = IDLE;
		}
	}
	else
	{
		attacker = true;
		if (direction == UP)
		{
			collision_attack = App->collision->AddCollider({ position.x, position.y, 8, 20 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == RIGHT)
		{
			collision_attack = App->collision->AddCollider({ position.x, position.y, 20, 8 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == DOWN)
		{
			collision_attack = App->collision->AddCollider({ position.x, position.y, 8, 20 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == LEFT)
		{
			collision_attack = App->collision->AddCollider({ position.x, position.y, 20, 8 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
	}
	return true;
}

bool Swampert::Idle_IA()
{
	if (movable)
	{
		if (reset_run)
		{
			timetorun = SDL_GetTicks();
			reset_run = false;
		}
		else
		{
			if (SDL_GetTicks() - timetorun > 200)
			{
				int direc_select = rand() % 4 + 1;
				if (direc_select == 1)
				{
					direction = UP;
				}
				else if (direc_select == 2)
				{
					direction = DOWN;
				}
				else if (direc_select == 3)
				{
					direction = LEFT;
				}
				else if (direc_select == 4)
				{
					direction = RIGHT;
				}
				state = WALKING;
				reset_distance = true;
			}
		}
	}
	return true;
}

bool Swampert::Walking_IA()
{
	walking = false;
	if (reset_distance)
	{
		distance = rand() % 60 + 20;
		dis_moved = 0;
		reset_distance = false;
	}
	Move_IA();

	if (dis_moved >= distance)
	{
		walking = false;
		reset_run = true;
	}

	if (walking == false)
	{
		state = IDLE;
	}

	else
	{
		state = WALKING;
	}
	return true;
}

bool Swampert::Move_IA()
{
	//App->pathfinding->CreatePath(position, target->Getposition());
	return true;
}

bool Swampert::Attack_IA()
{
	return true;
}

bool Swampert::CheckOrientation()
{
	return true;
}

void Swampert::OnInputCallback(INPUTEVENT, EVENTSTATE)
{
}<commit_msg>Swampert attack colliders modified<commit_after>#include "Swampert.h"
#include "j1App.h"
#include "j1Pathfinding.h"
#include "j1Audio.h"

Swampert::Swampert()
{
}

Swampert::~Swampert()
{
}

bool Swampert::Awake(pugi::xml_node &conf)
{
	std::string temp = conf.attribute("dir").as_string("");
	if (temp == "up")
		direction = UP;
	else if (temp == "down")
		direction = DOWN;
	else if (temp == "left")
		direction = LEFT;
	else
		direction = RIGHT;
	hp = conf.attribute("hp").as_int(0);
	attack = conf.attribute("attack").as_int(0);
	speed = conf.attribute("speed").as_int(0);
	name = conf.attribute("name").as_string("");
	position.x = conf.attribute("pos_x").as_int(0);
	position.y = conf.attribute("pos_y").as_int(0);
	active = conf.attribute("active").as_bool(false);

	return true;
}

bool Swampert::Start()
{
	pokemon_player = true;
	state = IDLE;
	scale = App->win->GetScale();
	offset_x = 7;
	offset_y = 17;
	gamestate = TIMETOPLAY;
	timetoplay = SDL_GetTicks();
	movable = true;
	collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 15, 15 }, COLLIDER_PLAYER, this);
	timetoplay = SDL_GetTicks();
	reset_distance = false;
	reset_run = true;

	return true;
}

bool Swampert::Update()
{
	// STATE MACHINE ------------------
	if (gamestate == INGAME)
	{
		if (pokemon_player)
		{
			//pokemon controlled by player
			switch (state)
			{
			case IDLE:
			{
				Idle();
				break;
			}
			case WALKING:
			{
				Walking();
				break;
			}
			case ATTACKING:
			{
				Attack();
				break;
			}
			/*
			case SPECIALATTACK:
			{
				SpecialAttack();
				break;
			}
			*/
			default:
			{
				break;
			}

			}
		}
		else
		{
			//Pokemon IA
			switch (state)
			{
			case IDLE:
			{
				Idle_IA();
				break;
			}
			case WALKING:
			{
				Walking_IA();
				break;
			}
			case ATTACKING:
			{
				Attack_IA();
				break;
			}
			/*
			case SPECIALATTACK:
			{
				SpecialAttack();
				break;
			}
			*/
			default:
			{
				break;
			}

			}
		}

	}
	else if (gamestate == INMENU)
	{

	}
	else if (gamestate == TIMETOPLAY)
	{
		if (SDL_GetTicks() - timetoplay > 1000)
		{
			gamestate = INGAME;
		}
	}

	//Collision follow the player
	collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
	return true;
}

void Swampert::Draw()
{
	App->anim_manager->Drawing_Manager(state, direction, position, 7);
}

bool Swampert::CleanUp()
{
	return true;
}

void Swampert::OnCollision(Collider* c1, Collider* c2)
{
	if (c1 != nullptr && c2 != nullptr)
	{
		if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
		{

		}
	}
}

bool Swampert::Idle()
{
	//IDLE SCEPTYLE
	if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
		App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
	{
		state = WALKING;
		CheckOrientation();
	}

	else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
	{
		state = ATTACKING;
		current_animation = App->anim_manager->GetAnimation(state, direction, 7); //this number may need to be changed?
		current_animation->Reset();
	}

	else
	{
		state = IDLE;
	}
	return true;
}

bool Swampert::Walking()
{
	walking = false;
	Move();

	if (walking == false)
	{
		state = IDLE;
	}

	else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
	{
		state = ATTACKING;
		current_animation = App->anim_manager->GetAnimation(state, direction, 7); //This number may need to be changed?
		current_animation->Reset();
	}

	else
	{
		state = WALKING;
	}
	return false;
}

bool Swampert::Move()
{
	if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
	{
		direction = LEFT;
		//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT);
		int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
		if (temp == 0)
		{
			position.x -= speed;
		}

		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
	{
		direction = DOWN;
		//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
		int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
		if (temp == 0)
		{
			position.y += speed;
		}

		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
	{
		direction = RIGHT;
		//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
		int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
		if (temp == 0)
		{
			position.x += speed;
		}
		walking = true;
	}

	if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
	{
		direction = UP;
		//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
		int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
		if (temp == 0)
		{
			position.y -= speed;
		}
		walking = true;
	}
	return walking;
}

bool Swampert::Attack()
{
	if (attacker)
	{
		if (current_animation->Finished())
		{
			App->collision->EraseCollider(collision_attack);
			attacker = false;
			current_animation->Reset();
			current_animation = nullptr;
			state = IDLE;
		}
	}
	else
	{
		attacker = true;
		if (direction == UP)
		{
			collision_attack = App->collision->AddCollider({ position.x - 11, position.y - 35, 22, 8 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == RIGHT)
		{
			collision_attack = App->collision->AddCollider({ position.x + 12, position.y - 26, 8, 22 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == DOWN)
		{
			collision_attack = App->collision->AddCollider({ position.x - 10, position.y - 4, 22, 8 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
		else if (direction == LEFT)
		{
			collision_attack = App->collision->AddCollider({ position.x - 20, position.y - 26, 8, 22 }, COLLIDER_PLAYER, this);
			App->audio->PlayFx(10);
		}
	}
	return true;
}

bool Swampert::Idle_IA()
{
	if (movable)
	{
		if (reset_run)
		{
			timetorun = SDL_GetTicks();
			reset_run = false;
		}
		else
		{
			if (SDL_GetTicks() - timetorun > 200)
			{
				int direc_select = rand() % 4 + 1;
				if (direc_select == 1)
				{
					direction = UP;
				}
				else if (direc_select == 2)
				{
					direction = DOWN;
				}
				else if (direc_select == 3)
				{
					direction = LEFT;
				}
				else if (direc_select == 4)
				{
					direction = RIGHT;
				}
				state = WALKING;
				reset_distance = true;
			}
		}
	}
	return true;
}

bool Swampert::Walking_IA()
{
	walking = false;
	if (reset_distance)
	{
		distance = rand() % 60 + 20;
		dis_moved = 0;
		reset_distance = false;
	}
	Move_IA();

	if (dis_moved >= distance)
	{
		walking = false;
		reset_run = true;
	}

	if (walking == false)
	{
		state = IDLE;
	}

	else
	{
		state = WALKING;
	}
	return true;
}

bool Swampert::Move_IA()
{
	//App->pathfinding->CreatePath(position, target->Getposition());
	return true;
}

bool Swampert::Attack_IA()
{
	return true;
}

bool Swampert::CheckOrientation()
{
	return true;
}

void Swampert::OnInputCallback(INPUTEVENT, EVENTSTATE)
{
}<|endoftext|>


<commit_before>// [WriteFile Name=StatisticalQuery, Category=Analysis]
// [Legal]
// Copyright 2017 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]

#include "StatisticalQuery.h"

#include "Map.h"
#include "MapQuickView.h"
#include "ArcGISVectorTiledLayer.h"
#include "FeatureLayer.h"
#include "ServiceFeatureTable.h"
#include "StatisticalQuery.h"
#include "StatisticsQueryParameters.h"
#include "StatisticDefinition.h"
#include "StatisticRecord.h"
#include "StatisticRecordIterator.h"
#include "Viewpoint.h"

#include <QUrl>

using namespace Esri::ArcGISRuntime;

StatisticalQuery::StatisticalQuery(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent)
{
}

void StatisticalQuery::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<StatisticalQuery>("Esri.Samples", 1, 0, "StatisticalQuerySample");
}

void StatisticalQuery::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");

  // Create a new Map with the world streets vector basemap
  m_map = new Map(Basemap::streetsVector(this), this);

  // Create feature table using the world cities URL
  m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0"), this);

  // Create a new feature layer to display features in the world cities table
  FeatureLayer* featureLayer = new FeatureLayer(m_featureTable, this);
  m_map->operationalLayers()->append(featureLayer);

  // Set map to map view
  m_mapView->setMap(m_map);

  connect(m_featureTable, &ServiceFeatureTable::errorOccurred, [this](Error e)
  {
    if (e.isEmpty())
      return;

    emit showStatistics(e.message());
  });

  // connect to queryStatisticsCompleted
  connect(m_featureTable, &ServiceFeatureTable::queryStatisticsCompleted, this, [this](QUuid, StatisticsQueryResult* rawResult)
  {
    if (!rawResult)
      return;

    // Delete rawResult when we leave local scope.
    QScopedPointer<StatisticsQueryResult> result(rawResult);

    // Iterate through the results
    QObject parent;
    QString resultText;
    StatisticRecordIterator iter = result->iterator();
    while (iter.hasNext())
    {
      StatisticRecord* record = iter.next(&parent);
      const QVariantMap& statsMap = record->statistics();
      for (const auto& it : statsMap.toStdMap())
      {
        resultText += QString("%1: %2\n").arg(it.first, it.second.toString());
      }
    }

    // Display the Results
    emit showStatistics(resultText);
  });
}

void StatisticalQuery::queryStatistics(bool extentOnly, bool bigCitiesOnly)
{
  // create the parameters
  StatisticsQueryParameters queryParameters;

  // Add the Statistic Definitions
  QList<StatisticDefinition> definitions
  {
    StatisticDefinition("POP", StatisticType::Average, ""),
    StatisticDefinition("POP", StatisticType::Minimum, ""),
    StatisticDefinition("POP", StatisticType::Maximum, ""),
    StatisticDefinition("POP", StatisticType::Sum, ""),
    StatisticDefinition("POP", StatisticType::StandardDeviation, ""),
    StatisticDefinition("POP", StatisticType::Variance, ""),
    StatisticDefinition("POP", StatisticType::Count, "CityCount")
  };
  queryParameters.setStatisticDefinitions(definitions);

  // If only using features in the current extent, set up the spatial filter for the statistics query parameters
  if (extentOnly)
  {
    // Set the statistics query parameters geometry with the envelope
    queryParameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());

    // Set the spatial relationship to Intersects (which is the default)
    queryParameters.setSpatialRelationship(SpatialRelationship::Intersects);
  }

  // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
  if (bigCitiesOnly)
    queryParameters.setWhereClause("POP_RANK = 1");

  // Execute the statistical query with these parameters
  m_featureTable->queryStatistics(queryParameters);
}
<commit_msg>Reverting back to QVariantMap iterator.<commit_after>// [WriteFile Name=StatisticalQuery, Category=Analysis]
// [Legal]
// Copyright 2017 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]

#include "StatisticalQuery.h"

#include "Map.h"
#include "MapQuickView.h"
#include "ArcGISVectorTiledLayer.h"
#include "FeatureLayer.h"
#include "ServiceFeatureTable.h"
#include "StatisticalQuery.h"
#include "StatisticsQueryParameters.h"
#include "StatisticDefinition.h"
#include "StatisticRecord.h"
#include "StatisticRecordIterator.h"
#include "Viewpoint.h"

#include <QUrl>

using namespace Esri::ArcGISRuntime;

StatisticalQuery::StatisticalQuery(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent)
{
}

void StatisticalQuery::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<StatisticalQuery>("Esri.Samples", 1, 0, "StatisticalQuerySample");
}

void StatisticalQuery::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");

  // Create a new Map with the world streets vector basemap
  m_map = new Map(Basemap::streetsVector(this), this);

  // Create feature table using the world cities URL
  m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0"), this);

  // Create a new feature layer to display features in the world cities table
  FeatureLayer* featureLayer = new FeatureLayer(m_featureTable, this);
  m_map->operationalLayers()->append(featureLayer);

  // Set map to map view
  m_mapView->setMap(m_map);

  connect(m_featureTable, &ServiceFeatureTable::errorOccurred, [this](Error e)
  {
    if (e.isEmpty())
      return;

    emit showStatistics(e.message());
  });

  // connect to queryStatisticsCompleted
  connect(m_featureTable, &ServiceFeatureTable::queryStatisticsCompleted, this, [this](QUuid, StatisticsQueryResult* rawResult)
  {
    if (!rawResult)
      return;

    // Delete rawResult when we leave local scope.
    QScopedPointer<StatisticsQueryResult> result(rawResult);

    // Iterate through the results
    QObject parent;
    QString resultText;
    StatisticRecordIterator iter = result->iterator();
    while (iter.hasNext())
    {
      StatisticRecord* record = iter.next(&parent);
      const QVariantMap& statsMap = record->statistics();
      for (auto it = statsMap.cbegin(); it != statsMap.cend(); ++it)
      {
        resultText += QString("%1: %2\n").arg(it.key(), it.value().toString());
      }
    }

    // Display the Results
    emit showStatistics(resultText);
  });
}

void StatisticalQuery::queryStatistics(bool extentOnly, bool bigCitiesOnly)
{
  // create the parameters
  StatisticsQueryParameters queryParameters;

  // Add the Statistic Definitions
  QList<StatisticDefinition> definitions
  {
    StatisticDefinition("POP", StatisticType::Average, ""),
    StatisticDefinition("POP", StatisticType::Minimum, ""),
    StatisticDefinition("POP", StatisticType::Maximum, ""),
    StatisticDefinition("POP", StatisticType::Sum, ""),
    StatisticDefinition("POP", StatisticType::StandardDeviation, ""),
    StatisticDefinition("POP", StatisticType::Variance, ""),
    StatisticDefinition("POP", StatisticType::Count, "CityCount")
  };
  queryParameters.setStatisticDefinitions(definitions);

  // If only using features in the current extent, set up the spatial filter for the statistics query parameters
  if (extentOnly)
  {
    // Set the statistics query parameters geometry with the envelope
    queryParameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());

    // Set the spatial relationship to Intersects (which is the default)
    queryParameters.setSpatialRelationship(SpatialRelationship::Intersects);
  }

  // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
  if (bigCitiesOnly)
    queryParameters.setWhereClause("POP_RANK = 1");

  // Execute the statistical query with these parameters
  m_featureTable->queryStatistics(queryParameters);
}
<|endoftext|>


<commit_before><commit_msg>Fix memory leak<commit_after><|endoftext|>


<commit_before>/*!
    \file barrier.cpp
    \brief Barrier synchronization primitive implementation
    \author Ivan Shynkarenka
    \date 16.03.2016
    \copyright MIT License
*/

#include "threads/barrier.h"

#include "errors/exceptions.h"

#include <cassert>

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "errors/fatal.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppCommon {

//! @cond INTERNALS

class Barrier::Impl
{
public:
    Impl(int threads) : _threads(threads)
    {
        assert((threads > 0) && "Barrier threads counter must be greater than zero!");

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_init(&_barrier, nullptr, threads);
        if (result != 0)
            throwex SystemException("Failed to initialize a synchronization barrier!", result);
#elif defined(_WIN32) || defined(_WIN64)
        if (!InitializeSynchronizationBarrier(&_barrier, threads, -1))
            throwex SystemException("Failed to initialize a synchronization barrier!");
#endif
    }

    ~Impl()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_destroy(&_barrier);
        if (result != 0)
            fatality(SystemException("Failed to destroy a synchronization barrier!", result));
#elif defined(_WIN32) || defined(_WIN64)
        DeleteSynchronizationBarrier(&_barrier);
#endif
    }

    int threads() const noexcept
    {
        return _threads;
    }

    bool Wait()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_wait(&_barrier);
        if ((result != PTHREAD_BARRIER_SERIAL_THREAD) && (result != 0))
            throwex SystemException("Failed to wait at a synchronization barrier!", result);
        return (result == PTHREAD_BARRIER_SERIAL_THREAD);
#elif defined(_WIN32) || defined(_WIN64)
        return (EnterSynchronizationBarrier(&_barrier, 0) == TRUE);
#endif
    }

private:
    int _threads;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    pthread_barrier_t _barrier;
#elif defined(_WIN32) || defined(_WIN64)
    SYNCHRONIZATION_BARRIER _barrier;
#endif
};

//! @endcond

Barrier::Barrier(int threads) : _pimpl(std::make_unique<Impl>(threads))
{
}

Barrier::Barrier(Barrier&& barrier) noexcept : _pimpl(std::move(barrier._pimpl))
{
}

Barrier::~Barrier()
{
}

Barrier& Barrier::operator=(Barrier&& barrier) noexcept
{
    _pimpl = std::move(barrier._pimpl);
    return *this;
}

int Barrier::threads() const noexcept
{
    return _pimpl->threads();
}

bool Barrier::Wait()
{
    return _pimpl->Wait();
}

} // namespace CppCommon
<commit_msg>Fix MinGW build<commit_after>/*!
    \file barrier.cpp
    \brief Barrier synchronization primitive implementation
    \author Ivan Shynkarenka
    \date 16.03.2016
    \copyright MIT License
*/

#include "threads/barrier.h"

#include "errors/exceptions.h"

#include <cassert>

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "errors/fatal.h"
#include <pthread.h>
#elif defined(__MINGW32__) || defined(__MINGW64__)
#include <condition_variable>
#include <mutex>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppCommon {

//! @cond INTERNALS

class Barrier::Impl
{
public:
    Impl(int threads) : _threads(threads)
    {
        assert((threads > 0) && "Barrier threads counter must be greater than zero!");

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_init(&_barrier, nullptr, threads);
        if (result != 0)
            throwex SystemException("Failed to initialize a synchronization barrier!", result);
#elif defined(__MINGW32__) || defined(__MINGW64__)
        _counter = threads;
        _generation = 0;
#elif defined(_WIN32) || defined(_WIN64)
        if (!InitializeSynchronizationBarrier(&_barrier, threads, -1))
            throwex SystemException("Failed to initialize a synchronization barrier!");
#endif
    }

    ~Impl()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_destroy(&_barrier);
        if (result != 0)
            fatality(SystemException("Failed to destroy a synchronization barrier!", result));
#elif defined(__MINGW32__) || defined(__MINGW64__)
        // Do nothing here...
#elif defined(_WIN32) || defined(_WIN64)
        DeleteSynchronizationBarrier(&_barrier);
#endif
    }

    int threads() const noexcept
    {
        return _threads;
    }

    bool Wait()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_barrier_wait(&_barrier);
        if ((result != PTHREAD_BARRIER_SERIAL_THREAD) && (result != 0))
            throwex SystemException("Failed to wait at a synchronization barrier!", result);
        return (result == PTHREAD_BARRIER_SERIAL_THREAD);
#elif defined(__MINGW32__) || defined(__MINGW64__)
        std::unique_lock<std::mutex> lock(_mutex);

        // Remember the current barrier generation
        int generation = _generation;

        // Decrease the count of waiting threads
        if (--_counter == 0)
        {
            // Increase the current barrier generation
            ++_generation;

            // Reset waiting threads counter
            _counter = _threads;

            // Notify all waiting threads
            _cond.notify_all();

            // Notify the last thread that reached the barrier
            return true;
        }

        // Wait for the next barrier generation
        _cond.wait(lock, [&, this]() { return generation != _generation; });

        // Notify each of remaining threads
        return false;
#elif defined(_WIN32) || defined(_WIN64)
        return (EnterSynchronizationBarrier(&_barrier, 0) == TRUE);
#endif
    }

private:
    int _threads;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    pthread_barrier_t _barrier;
#elif defined(__MINGW32__) || defined(__MINGW64__)
    std::mutex _mutex;
    std::condition_variable _cond;
    int _counter;
    int _generation;
#elif defined(_WIN32) || defined(_WIN64)
    SYNCHRONIZATION_BARRIER _barrier;
#endif
};

//! @endcond

Barrier::Barrier(int threads) : _pimpl(std::make_unique<Impl>(threads))
{
}

Barrier::Barrier(Barrier&& barrier) noexcept : _pimpl(std::move(barrier._pimpl))
{
}

Barrier::~Barrier()
{
}

Barrier& Barrier::operator=(Barrier&& barrier) noexcept
{
    _pimpl = std::move(barrier._pimpl);
    return *this;
}

int Barrier::threads() const noexcept
{
    return _pimpl->threads();
}

bool Barrier::Wait()
{
    return _pimpl->Wait();
}

} // namespace CppCommon
<|endoftext|>


<commit_before>#include "OverloadRunValidationAlgorithm.h"

#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/WorkStop.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Operation.h>

bool Scheduler::OverloadRunValidationAlgorithm::isValid(const Run * run) const
{
	if (run->getVehicle() == nullptr) return true; // Have no vehicle to check with
	const auto& stops = run->getWorkStops();
	const Capacity vehicle_capacity = run->getVehicle()->getCapacity();
	bool overflow = false;
	Capacity run_demand;
	for (auto stop_it = stops.begin(); stop_it != stops.end() && !overflow;	++stop_it) {
		run_demand += (*stop_it)->getOperation()->getDemand();
		overflow = (run_demand > vehicle_capacity);
	}
	return overflow;
}
<commit_msg>[#45] Bugfix in overload checker<commit_after>#include "OverloadRunValidationAlgorithm.h"

#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/WorkStop.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Operation.h>

bool Scheduler::OverloadRunValidationAlgorithm::isValid(const Run * run) const
{
	if (run->getVehicle() == nullptr) return true; // Have no vehicle to check with
	const auto& stops = run->getWorkStops();
	const Capacity vehicle_capacity = run->getVehicle()->getCapacity();
	bool overload = false;
	Capacity run_demand;
	for (auto stop_it = stops.begin(); stop_it != stops.end() && !overload;	++stop_it) {
		run_demand += (*stop_it)->getOperation()->getDemand();
		overload = (run_demand > vehicle_capacity);
	}
	return !overload;
}
<|endoftext|>


<commit_before>#include "vvvsourcegraph.hpp"
#include <memory>
using namespace clang;
using namespace std;

shared_ptr<SemanticVertex>
getSemanticVertexFromStmt(const Stmt* stmt, Graph& graph, const clang::ASTContext& context)
{
    SemanticVertex* ret = 0;
    if(stmt) switch(stmt->getStmtClass()){
                case Stmt::CompoundStmtClass: ret = new BlockCompound(graph, stmt, context);    break;
                case Stmt::IfStmtClass:       ret = new BlockIf(      graph, stmt, context);    break;
                case Stmt::SwitchStmtClass:   ret = new BlockSwitch(  graph, stmt, context);    break;
                case Stmt::CaseStmtClass:     ret = new BlockCase(    graph, stmt, context);    break;
                case Stmt::DefaultStmtClass:  ret = new BlockDefault( graph, stmt, context);    break;
                case Stmt::ForStmtClass:      ret = new BlockFor(     graph, stmt, context);    break;
                case Stmt::WhileStmtClass:    ret = new BlockWhile(   graph, stmt, context);    break;
                case Stmt::DoStmtClass:       ret = new BlockDoWhile( graph, stmt, context);    break;
                case Stmt::CallExprClass:     ret = new BlockCall(    graph, stmt, context);    break;
                case Stmt::ReturnStmtClass:   ret = new BlockReturn(  graph, stmt, context);    break;
                case Stmt::BreakStmtClass:    ret = new BlockBreak(  graph );                   break;
                case Stmt::ContinueStmtClass: ret = new BlockContinue( graph );                 break;
                default:                      ret = new BlockSimple(  graph, stmt, context);    break; }
    return shared_ptr<SemanticVertex>(ret);
}

void BlockIf::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto thenStmt = getSemanticVertexFromStmt( stmt->getThen(), graph, context );
    auto elseStmt = getSemanticVertexFromStmt( stmt->getElse(), graph, context );

    thenStmt->expand( vertex, end, onReturn, onBreak, onContinue);
    if( elseStmt )
        elseStmt->expand( vertex, end, onReturn, onBreak, onContinue);
    else {
        edge_t e = boost::add_edge( vertex, end, graph).first;
        graph[e].text = "false"; }
    auto outedges = boost::out_edges( vertex, graph );
    auto i = outedges.first;
    edge_t trueBranch =  *(i++);
    edge_t falseBranch = *i;
    graph[ trueBranch ].text = "true";
    graph[ falseBranch ].text = "false";

}

void BlockCall::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, decl2str( stmt, context ) );
    boost::add_edge( begin, vertex, graph );
    boost::add_edge( vertex, end, graph );
}

void BlockReturn::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, std::string("return ") + decl2str( stmt->getRetValue(), context )  );
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex, onReturn, graph);
}

void BlockSimple::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, decl2str( stmt, context ) );
    boost::add_edge( begin, vertex, graph );
    boost::add_edge( vertex, end, graph );
}

static std::vector<std::shared_ptr<SemanticVertex>>
groupChildren(const std::vector<const Stmt*>& stmts,
            Graph& graph, const ASTContext& context)
{
    using namespace std;
    using uptrSemVert = shared_ptr<SemanticVertex>;

    std::vector<uptrSemVert> ret;
    std::vector<uptrSemVert> oneBlock;

    auto addOneBlock = [&oneBlock, &ret, &graph, &context]() {
        if(oneBlock.size()) {
            ret.push_back( uptrSemVert(new BlockSimpleCompound(graph, oneBlock, context) ) );
            oneBlock.clear();} };

    for( auto& stmt : stmts ) {
        auto sv = getSemanticVertexFromStmt( stmt, graph, context);
        if (sv->getType() != SEMANTIC_BLOCK_TYPE::SIMPLE) {
            addOneBlock();
            ret.push_back( std::move(sv) );}
        else oneBlock.push_back( std::move(sv) ); }
    addOneBlock();

    return ret;
}

void BlockCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    auto children = getCompoundStmtChildren( stmt );

    const auto groupedChildren = groupChildren(children, graph, context);
    const auto numChildren = groupedChildren.size();

    switch(numChildren){
        case 0: boost::add_edge(begin,end,graph); break;
        case 1: groupedChildren[0]->expand(begin,end,onReturn, onBreak, onContinue); break;
        default:
                {
                    size_t i = numChildren-1;
                    groupedChildren[i]->expand(begin,end,onReturn,onBreak,onContinue);
                    boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
                    do
                    {
                        --i;
                        groupedChildren[i]->expand(begin,groupedChildren[i+1]->getVertex(),onReturn,onBreak,onContinue);
                        boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
                    }while(i!=0);
                    boost::add_edge( begin, groupedChildren[0]->getVertex(), graph);
                }
                break;};
    vertex = groupedChildren[0]->getVertex();
}

void BlockSimpleCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    std::string caption;
    for(const auto& stmt: stmts)
        caption += "\n" + stmt->toString();
    vertex = addProcessVertex( graph, caption );
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex,   end, graph);
}

void BlockFor::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex(graph, decl2str(stmt->getInc(),context) );
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex(graph, "");
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockDoWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, "" );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex( graph, decl2str( stmt->getCond(), context));
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockSwitch::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, decl2str(stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto children = getCompoundStmtChildren( stmt->getBody() );
    const auto groupedChildren = groupChildren(children, graph, context);
    const auto numChildren = groupedChildren.size();

    switch(numChildren){
        case 0: boost::add_edge(vertex,end,graph); break;
        case 1: groupedChildren[0]->expand(vertex,end,onReturn, end, onContinue); break;
        default: {  size_t i = numChildren-1;
                    if(groupedChildren[i]->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
                        groupedChildren[i]->expand(vertex,end,onReturn,end,onContinue);
                    do {
                        --i;
                        auto& currentChild  = groupedChildren[i];
                        auto& nextChild     = groupedChildren[i+1];
                        const auto localend = (nextChild->getType() == SEMANTIC_BLOCK_TYPE::BREAK) ? end :
                                                                                nextChild->getVertex();
                        if(currentChild->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
                            currentChild->expand(vertex, localend, onReturn, end, onContinue);  // TODO: connect children to each other, not to vertex
                    }while(i!=0);
                }
                break;};
}

static std::pair<vector<string>,const Stmt*> getConditions(const CaseStmt* stmt, const ASTContext& context)
{
    std::pair<vector<string>, const Stmt*> ret;

    auto currentStmt = stmt;
    for(;;){
        ret.first.push_back( decl2str(currentStmt->getLHS(), context) );
        auto subStmt = currentStmt->getSubStmt();
        if( subStmt->getStmtClass() == Stmt::CaseStmtClass )
            currentStmt = static_cast<const CaseStmt*>(subStmt);
        else {
            currentStmt = nullptr;
            ret.second  = subStmt;
            break;} }

    return ret;
}

static
string joinStringsWith( const vector<string>& v, const string& delimiter)
{
    string ret;
    const auto numStrings = v.size();
    const auto numStrings_1 = numStrings-1;
    for(size_t i = 0; i < numStrings; ++i) {
        ret += v[i];
        if( i!= numStrings_1) ret += delimiter; }

    return ret;
}

void BlockCase::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    auto condition = getConditions( stmt, context );

    auto statements = getSemanticVertexFromStmt( condition.second, graph, context);
    statements->expand( begin, end, onReturn, onBreak, onContinue );

    vertex = statements->getVertex();
    boost::remove_edge( begin, vertex, graph );
    auto beginvertex = boost::add_edge( begin, vertex, graph).first;
    graph[beginvertex].text = joinStringsWith( condition.first, ", " );

/*
    vertex = addConditionVertex( graph, "CASE");
    auto beginvertex = boost::add_edge( begin, vertex, graph).first;
    boost::add_edge( vertex, end, graph);
    graph[beginvertex].text = joinStringsWith( condition.first, ", " );
    */
}

void BlockDefault::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, "default: ");
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex, end, graph);
}

void BlockBreak::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    boost::add_edge( begin, onBreak, graph);
}

void BlockContinue::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    boost::add_edge( begin, onContinue, graph);
}

<commit_msg>fix case bug<commit_after>#include "vvvsourcegraph.hpp"
#include <memory>
using namespace clang;
using namespace std;

shared_ptr<SemanticVertex>
getSemanticVertexFromStmt(const Stmt* stmt, Graph& graph, const clang::ASTContext& context)
{
    SemanticVertex* ret = 0;
    if(stmt) switch(stmt->getStmtClass()){
                case Stmt::CompoundStmtClass: ret = new BlockCompound(graph, stmt, context);    break;
                case Stmt::IfStmtClass:       ret = new BlockIf(      graph, stmt, context);    break;
                case Stmt::SwitchStmtClass:   ret = new BlockSwitch(  graph, stmt, context);    break;
                case Stmt::CaseStmtClass:     ret = new BlockCase(    graph, stmt, context);    break;
                case Stmt::DefaultStmtClass:  ret = new BlockDefault( graph, stmt, context);    break;
                case Stmt::ForStmtClass:      ret = new BlockFor(     graph, stmt, context);    break;
                case Stmt::WhileStmtClass:    ret = new BlockWhile(   graph, stmt, context);    break;
                case Stmt::DoStmtClass:       ret = new BlockDoWhile( graph, stmt, context);    break;
                case Stmt::CallExprClass:     ret = new BlockCall(    graph, stmt, context);    break;
                case Stmt::ReturnStmtClass:   ret = new BlockReturn(  graph, stmt, context);    break;
                case Stmt::BreakStmtClass:    ret = new BlockBreak(  graph );                   break;
                case Stmt::ContinueStmtClass: ret = new BlockContinue( graph );                 break;
                default:                      ret = new BlockSimple(  graph, stmt, context);    break; }
    return shared_ptr<SemanticVertex>(ret);
}

void BlockIf::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto thenStmt = getSemanticVertexFromStmt( stmt->getThen(), graph, context );
    auto elseStmt = getSemanticVertexFromStmt( stmt->getElse(), graph, context );

    thenStmt->expand( vertex, end, onReturn, onBreak, onContinue);
    if( elseStmt )
        elseStmt->expand( vertex, end, onReturn, onBreak, onContinue);
    else {
        edge_t e = boost::add_edge( vertex, end, graph).first;
        graph[e].text = "false"; }
    auto outedges = boost::out_edges( vertex, graph );
    auto i = outedges.first;
    edge_t trueBranch =  *(i++);
    edge_t falseBranch = *i;
    graph[ trueBranch ].text = "true";
    graph[ falseBranch ].text = "false";

}

void BlockCall::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, decl2str( stmt, context ) );
    boost::add_edge( begin, vertex, graph );
    boost::add_edge( vertex, end, graph );
}

void BlockReturn::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, std::string("return ") + decl2str( stmt->getRetValue(), context )  );
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex, onReturn, graph);
}

void BlockSimple::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addProcessVertex( graph, decl2str( stmt, context ) );
    boost::add_edge( begin, vertex, graph );
    boost::add_edge( vertex, end, graph );
}

static std::vector<std::shared_ptr<SemanticVertex>>
groupChildren(const std::vector<const Stmt*>& stmts,
            Graph& graph, const ASTContext& context)
{
    using namespace std;
    using uptrSemVert = shared_ptr<SemanticVertex>;

    std::vector<uptrSemVert> ret;
    std::vector<uptrSemVert> oneBlock;

    auto addOneBlock = [&oneBlock, &ret, &graph, &context]() {
        if(oneBlock.size()) {
            ret.push_back( uptrSemVert(new BlockSimpleCompound(graph, oneBlock, context) ) );
            oneBlock.clear();} };

    for( auto& stmt : stmts ) {
        auto sv = getSemanticVertexFromStmt( stmt, graph, context);
        if (sv->getType() != SEMANTIC_BLOCK_TYPE::SIMPLE) {
            addOneBlock();
            ret.push_back( std::move(sv) );}
        else oneBlock.push_back( std::move(sv) ); }
    addOneBlock();

    return ret;
}

void BlockCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    auto children = getCompoundStmtChildren( stmt );

    const auto groupedChildren = groupChildren(children, graph, context);
    const auto numChildren = groupedChildren.size();

    switch(numChildren){
        case 0: boost::add_edge(begin,end,graph); break;
        case 1: groupedChildren[0]->expand(begin,end,onReturn, onBreak, onContinue); break;
        default:
                {
                    size_t i = numChildren-1;
                    groupedChildren[i]->expand(begin,end,onReturn,onBreak,onContinue);
                    boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
                    do
                    {
                        --i;
                        groupedChildren[i]->expand(begin,groupedChildren[i+1]->getVertex(),onReturn,onBreak,onContinue);
                        boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
                    }while(i!=0);
                    boost::add_edge( begin, groupedChildren[0]->getVertex(), graph);
                }
                break;};
    vertex = groupedChildren[0]->getVertex();
}

void BlockSimpleCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    std::string caption;
    for(const auto& stmt: stmts)
        caption += "\n" + stmt->toString();
    vertex = addProcessVertex( graph, caption );
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex,   end, graph);
}

void BlockFor::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex(graph, decl2str(stmt->getInc(),context) );
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex(graph, "");
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockDoWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addLoopOpenVertex( graph, "" );
    boost::add_edge( begin, vertex, graph);

    auto endLoopVertex = addLoopCloseVertex( graph, decl2str( stmt->getCond(), context));
    boost::add_edge( endLoopVertex, end, graph);

    auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
    body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}

void BlockSwitch::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, decl2str(stmt->getCond(), context) );
    boost::add_edge( begin, vertex, graph);

    auto children = getCompoundStmtChildren( stmt->getBody() );
    const auto groupedChildren = groupChildren(children, graph, context);
    const auto numChildren = groupedChildren.size();

    switch(numChildren){
        case 0: boost::add_edge(vertex,end,graph); break;
        case 1: groupedChildren[0]->expand(vertex,end,onReturn, end, onContinue); break;
        default: {  size_t i = numChildren-1;
                    if(groupedChildren[i]->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
                    {
                        groupedChildren[i]->expand(vertex,end,onReturn,end,onContinue);
                        boost::remove_edge(vertex,groupedChildren[i]->getVertex(), graph);
                    }
                    do {
                        --i;
                        auto& currentChild  = groupedChildren[i];
                        auto& nextChild     = groupedChildren[i+1];
                        const auto localend = (nextChild->getType() == SEMANTIC_BLOCK_TYPE::BREAK) ? end :
                                                                                nextChild->getVertex();
                        const auto currentChildType = currentChild->getType();
                        if(currentChildType != SEMANTIC_BLOCK_TYPE::BREAK){
                            currentChild->expand(vertex, localend, onReturn, end, onContinue);  // TODO: connect children to each other, not to vertex
                            if(     currentChildType != SEMANTIC_BLOCK_TYPE::CASE
                                &&  currentChildType != SEMANTIC_BLOCK_TYPE::DEFAULT)
                                boost::remove_edge(vertex, currentChild->getVertex(), graph); }
                    }while(i!=0);
                }
                break;};
}

static std::pair<vector<string>,const Stmt*> getConditions(const CaseStmt* stmt, const ASTContext& context)
{
    std::pair<vector<string>, const Stmt*> ret;

    auto currentStmt = stmt;
    for(;;){
        ret.first.push_back( decl2str(currentStmt->getLHS(), context) );
        auto subStmt = currentStmt->getSubStmt();
        if( subStmt->getStmtClass() == Stmt::CaseStmtClass )
            currentStmt = static_cast<const CaseStmt*>(subStmt);
        else {
            currentStmt = nullptr;
            ret.second  = subStmt;
            break;} }

    return ret;
}

static
string joinStringsWith( const vector<string>& v, const string& delimiter)
{
    string ret;
    const auto numStrings = v.size();
    const auto numStrings_1 = numStrings-1;
    for(size_t i = 0; i < numStrings; ++i) {
        ret += v[i];
        if( i!= numStrings_1) ret += delimiter; }

    return ret;
}

void BlockCase::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    auto condition = getConditions( stmt, context );

    auto statements = getSemanticVertexFromStmt( condition.second, graph, context);
    statements->expand( begin, end, onReturn, onBreak, onContinue );

    vertex = statements->getVertex();
    boost::remove_edge( begin, vertex, graph );
    auto beginvertex = boost::add_edge( begin, vertex, graph).first;
    graph[beginvertex].text = joinStringsWith( condition.first, ", " );

/*
    vertex = addConditionVertex( graph, "CASE");
    auto beginvertex = boost::add_edge( begin, vertex, graph).first;
    boost::add_edge( vertex, end, graph);
    graph[beginvertex].text = joinStringsWith( condition.first, ", " );
    */
}

void BlockDefault::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    vertex = addConditionVertex( graph, "default: ");
    boost::add_edge( begin, vertex, graph);
    boost::add_edge( vertex, end, graph);
}

void BlockBreak::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    boost::add_edge( begin, onBreak, graph);
}

void BlockContinue::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
    boost::add_edge( begin, onContinue, graph);
}

<|endoftext|>


<commit_before>#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

#include <libmesh/libmesh.h>

int main( int argc, char **argv)
{
  // Initialize the library.  This is necessary because the library
  // may depend on a number of other libraries (i.e. MPI  and Petsc)
  // that require initialization before use.
  libMesh::LibMeshInit init(argc, argv);
  CppUnit::TextUi::TestRunner runner;
  CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  runner.addTest( registry.makeTest() );
  runner.run();

  return 0;
}
<commit_msg>If we see unit test failure, don't ignore it!<commit_after>#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

#include <libmesh/libmesh.h>

int main( int argc, char **argv)
{
  // Initialize the library.  This is necessary because the library
  // may depend on a number of other libraries (i.e. MPI  and Petsc)
  // that require initialization before use.
  libMesh::LibMeshInit init(argc, argv);
  CppUnit::TextUi::TestRunner runner;
  CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  runner.addTest( registry.makeTest() );

  // If the tests all succeed, report success
  if (runner.run())
    return 0;

  // If any test fails report failure
  return 1;
}
<|endoftext|>