<commit_before>#include "PlayerUFO.h"

//---------------------------------------------------------------
//						CONSTRUCTORS & DESTRUCTOR
//---------------------------------------------------------------
PlayerUFO::PlayerUFO(void)
{
	PlayerModel* p = new PlayerModel;
	pModel = (Model*)p;
	pos = new GLfloat[3];
	pos[0] = 0.0f;
	pos[1] = 0.0f;
	pos[2] = 0.0f;
	box = new BoundingBox(pos[0],pos[1],pos[2],pos[0]+1.0f,pos[1]+0.5f,pos[2]+1.0f, true);
	ct = new CollisionTester;
	ct->staticBoxes.push_back(box);
        updateLights(pos[0], pos[1], pos[2]);
}

PlayerUFO::PlayerUFO(GLfloat x, GLfloat z)
{
	PlayerModel* p = new PlayerModel;
	pModel = (Model*)p;
	pos = new GLfloat[3];
	pos[0] = x;
	pos[1] = 0;
	pos[2] = z;
	box = new BoundingBox(pos[0],pos[1],pos[2],pos[0]+1.0f,pos[1]+0.5f,pos[2]+1.0f, true);
	ct = new CollisionTester;
	ct->staticBoxes.push_back(box);

        //LIGHTING
        updateLights(pos[0], pos[1], pos[2]);
}

PlayerUFO::~PlayerUFO(void)
{
	if (pModel != NULL) {
		delete pModel;
		pModel = NULL;
	}
}

//---------------------------------------------------------------
//						LIGHTS
//---------------------------------------------------------------
void PlayerUFO::updateLights(GLfloat xPos, GLfloat yPos, GLfloat zPos)
{
        spotLight = new SpotLight(0.3f, 0.9f, 0.1f, 0.0f);
        light = new LightPost(xPos+0.5f, yPos, zPos+0.5f, 0, -1, 0);
        glLightfv(GL_LIGHT7, GL_AMBIENT, spotLight->getAmbient()); //Setup ambient lighting
        glLightfv(GL_LIGHT7, GL_DIFFUSE, spotLight->getDiffuse()); // Setup diffuse lighting
        glLightfv(GL_LIGHT7, GL_SPECULAR, spotLight->getSpecular());
        glLightfv(GL_LIGHT7, GL_POSITION, light->getPositionArray()); // Setup the lighting
        glLightf(GL_LIGHT7, GL_SPOT_CUTOFF, 25.0f);
        glLightf(GL_LIGHT7, GL_SPOT_EXPONENT, 0);
        glLightfv(GL_LIGHT7, GL_SPOT_DIRECTION, light->getDirectionArray());
        glEnable(GL_LIGHT7);
}

//---------------------------------------------------------------
//						DRAW
//---------------------------------------------------------------
void PlayerUFO::draw(){
	incrementHeight(false);
	glPushMatrix();
                box->draw();
	glPopMatrix();
	glPushMatrix();
		glTranslatef(pos[0],pos[1],pos[2]);
		pModel->draw();
	glPopMatrix();
        updateLights(pos[0], pos[1], pos[2]);
}

//---------------------------------------------------------------
//			TRANSLATE UFO (AND BOUNDING BOX)
//---------------------------------------------------------------
void PlayerUFO::incrementHeight(bool positive){
	if(positive){
		if(pos[1]+0.5f <= MAX_PLAYER_HEIGHT){
			pos[1] += 0.5f;
			box->lockBox(pos[0],pos[1],pos[2]);
		}
                if(pos[1]+0.3 > MAX_PLAYER_HEIGHT){
                    pos[1] = MAX_PLAYER_HEIGHT-0.3;
                   box->lockBox(pos[0],pos[1],pos[2]);
                }
	}
	else{
		if(pos[1]-0.02f >= MIN_PLAYER_HEIGHT&&
		!ufoCollisionTest(pos[0],pos[1]-0.02f,pos[2])){
			pos[1] -= 0.2f;
			box->lockBox(pos[0],pos[1],pos[2]);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

void PlayerUFO::incrementXPos(bool positive){
	if(positive){
		if(!ufoCollisionTest(pos[0]+0.05f,pos[1],pos[2])){
			pos[0] += 0.05f;
			box->moveBox(0.05f,0.0f,0.0f);
		}
	}
	else{
		if(!ufoCollisionTest(pos[0]-0.05f,pos[1],pos[2])){
			pos[0] -= 0.05f;
			box->moveBox(-0.05f,0.0f,0.0f);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

void PlayerUFO::incrementZPos(bool positive){
	if(positive){
		if(!ufoCollisionTest(pos[0],pos[1],pos[2]+0.05f)){
			pos[2] += 0.05f;
			box->moveBox(0.0f,0.0f,0.05f);
		}
	}
	else{
		if(!ufoCollisionTest(pos[0],pos[1],pos[2]-0.05f)){
			pos[2] -= 0.05f;
			box->moveBox(0.0f,0.0f,-0.05f);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

//---------------------------------------------------------------
//					COLLISION DETECTION
//---------------------------------------------------------------
bool PlayerUFO::ufoCollisionTest(GLfloat x, GLfloat y, GLfloat z){
		if(ct->collisionTest(x,y,z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x, y, z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y+box->size.y,	z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y+box->size.y,	z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y+box->size.y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y+box->size.y,	z+box->size.z,box->movingBoxId)){
			return true;
		}

		return false;
}<commit_msg>fixed a warning<commit_after>#include "PlayerUFO.h"

//---------------------------------------------------------------
//						CONSTRUCTORS & DESTRUCTOR
//---------------------------------------------------------------
PlayerUFO::PlayerUFO(void)
{
	PlayerModel* p = new PlayerModel;
	pModel = (Model*)p;
	pos = new GLfloat[3];
	pos[0] = 0.0f;
	pos[1] = 0.0f;
	pos[2] = 0.0f;
	box = new BoundingBox(pos[0],pos[1],pos[2],pos[0]+1.0f,pos[1]+0.5f,pos[2]+1.0f, true);
	ct = new CollisionTester;
	ct->staticBoxes.push_back(box);
        updateLights(pos[0], pos[1], pos[2]);
}

PlayerUFO::PlayerUFO(GLfloat x, GLfloat z)
{
	PlayerModel* p = new PlayerModel;
	pModel = (Model*)p;
	pos = new GLfloat[3];
	pos[0] = x;
	pos[1] = 0;
	pos[2] = z;
	box = new BoundingBox(pos[0],pos[1],pos[2],pos[0]+1.0f,pos[1]+0.5f,pos[2]+1.0f, true);
	ct = new CollisionTester;
	ct->staticBoxes.push_back(box);

        //LIGHTING
        updateLights(pos[0], pos[1], pos[2]);
}

PlayerUFO::~PlayerUFO(void)
{
	if (pModel != NULL) {
		delete pModel;
		pModel = NULL;
	}
}

//---------------------------------------------------------------
//						LIGHTS
//---------------------------------------------------------------
void PlayerUFO::updateLights(GLfloat xPos, GLfloat yPos, GLfloat zPos)
{
        spotLight = new SpotLight(0.3f, 0.9f, 0.1f, 0.0f);
        light = new LightPost(xPos+0.5f, yPos, zPos+0.5f, 0, -1, 0);
        glLightfv(GL_LIGHT7, GL_AMBIENT, spotLight->getAmbient()); //Setup ambient lighting
        glLightfv(GL_LIGHT7, GL_DIFFUSE, spotLight->getDiffuse()); // Setup diffuse lighting
        glLightfv(GL_LIGHT7, GL_SPECULAR, spotLight->getSpecular());
        glLightfv(GL_LIGHT7, GL_POSITION, light->getPositionArray()); // Setup the lighting
        glLightf(GL_LIGHT7, GL_SPOT_CUTOFF, 25.0f);
        glLightf(GL_LIGHT7, GL_SPOT_EXPONENT, 0);
        glLightfv(GL_LIGHT7, GL_SPOT_DIRECTION, light->getDirectionArray());
        glEnable(GL_LIGHT7);
}

//---------------------------------------------------------------
//						DRAW
//---------------------------------------------------------------
void PlayerUFO::draw(){
	incrementHeight(false);
	glPushMatrix();
                box->draw();
	glPopMatrix();
	glPushMatrix();
		glTranslatef(pos[0],pos[1],pos[2]);
		pModel->draw();
	glPopMatrix();
        updateLights(pos[0], pos[1], pos[2]);
}

//---------------------------------------------------------------
//			TRANSLATE UFO (AND BOUNDING BOX)
//---------------------------------------------------------------
void PlayerUFO::incrementHeight(bool positive){
	if(positive){

		if(pos[1]+0.5f <= MAX_PLAYER_HEIGHT){
			pos[1] += 0.5f;
			box->lockBox(pos[0],pos[1],pos[2]);
		}
                if(pos[1]+0.3 > MAX_PLAYER_HEIGHT){
                    pos[1] = MAX_PLAYER_HEIGHT-0.3f;
                   box->lockBox(pos[0],pos[1],pos[2]);
                }

	}
	else{
		if(pos[1]-0.02f >= MIN_PLAYER_HEIGHT&&
		!ufoCollisionTest(pos[0],pos[1]-0.02f,pos[2])){
			pos[1] -= 0.2f;
			box->lockBox(pos[0],pos[1],pos[2]);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

void PlayerUFO::incrementXPos(bool positive){
	if(positive){
		if(!ufoCollisionTest(pos[0]+0.05f,pos[1],pos[2])){
			pos[0] += 0.05f;
			box->moveBox(0.05f,0.0f,0.0f);
		}
	}
	else{
		if(!ufoCollisionTest(pos[0]-0.05f,pos[1],pos[2])){
			pos[0] -= 0.05f;
			box->moveBox(-0.05f,0.0f,0.0f);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

void PlayerUFO::incrementZPos(bool positive){
	if(positive){
		if(!ufoCollisionTest(pos[0],pos[1],pos[2]+0.05f)){
			pos[2] += 0.05f;
			box->moveBox(0.0f,0.0f,0.05f);
		}
	}
	else{
		if(!ufoCollisionTest(pos[0],pos[1],pos[2]-0.05f)){
			pos[2] -= 0.05f;
			box->moveBox(0.0f,0.0f,-0.05f);
		}
	}
        updateLights(pos[0], pos[1], pos[2]);
}

//---------------------------------------------------------------
//					COLLISION DETECTION
//---------------------------------------------------------------
bool PlayerUFO::ufoCollisionTest(GLfloat x, GLfloat y, GLfloat z){
		if(ct->collisionTest(x,y,z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x, y, z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y+box->size.y,	z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y+box->size.y,	z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x,	y+box->size.y,	z+box->size.z,box->movingBoxId)){
			return true;
		}
		if(ct->collisionTest(x+box->size.x,	y+box->size.y,	z+box->size.z,box->movingBoxId)){
			return true;
		}

		return false;
}<|endoftext|>


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

#include "danek/internal/UidIdentifierProcessor.h"
#include "danek/internal/Util.h"
#include "danek/internal/Compat.h"
#include "danek/ConfigurationException.h"
#include "danek/StringVector.h"
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <string.h>
#include <ctype.h>
#include <stdio.h>

namespace danek
{

    UidIdentifierProcessor::UidIdentifierProcessor() : m_count(0), m_uidToken("uid-")
    {
    }

    //----------------------------------------------------------------------
    // Spelling must be in one of the following forms:
    //      - "foo"                 -->  "foo"
    //      - "uid-<foo>"           -->  "uid-<digits>-<foo>"
    //      - "uid-<digits>-<foo>"  -->  "uid-<new-digits>-<foo>"
    // where "<foo>" does NOT start with a digit or "-"
    //----------------------------------------------------------------------

    std::string UidIdentifierProcessor::expand(const std::string& spelling)
    {
        // Common case optimizations
        if( spelling.find('.') == std::string::npos )
        {
            return expandOne(spelling);
        }

        if( spelling.find(m_uidToken) == std::string::npos )
        {
            return spelling;
        }

        // Let's break apart the scoped name, expand each local part
        // and then recombine the parts into an expanded scoped name.
        std::ostringstream result;
        const auto scopes = util::splitScopes(spelling);

        for( std::size_t i=0; i<scopes.size(); ++i )
        {
            result << expandOne(scopes[i]);

            if( i < scopes.size() - 1 )
            {
                result << '.';
            }
        }

        return result.str();
    }

    std::string UidIdentifierProcessor::expandOne(const std::string& spelling)
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        checkCondition(hasValidPrefix(spelling), spelling);

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return formatExpanded(std::string(digitsEnd, spelling.cend()));
        }

        checkCondition(hasValidPayload(digitsEnd, spelling.cend()), spelling);

        return formatExpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    std::string UidIdentifierProcessor::unexpand(const char* spelling, StringBuffer& buf) const
    {
        //--------
        // Common case optimizations
        //--------
        if (strchr(spelling, '.') == nullptr)
        {
            const auto result = unexpandOne(spelling);
            buf = result;
            return result;
        }
        if (strstr(spelling, "uid-") == nullptr)
        {
            return spelling;
        }

        //--------
        // Let's break apart the scoped name, unexpand each local part
        // and then recombine the parts into an unexpanded scoped name.
        //--------
        StringBuffer result;
        StringBuffer msg;

        StringVector vec{util::splitScopes(spelling)};
        const int len = vec.size();
        for (int i = 0; i < len; ++i)
        {
            std::string str;
            try
            {
                str = unexpandOne(vec[i]);
                buf = str;
            }
            catch (const ConfigurationException&)
            {
                msg << "'" << spelling << "' is not a legal identifier";
                throw ConfigurationException(msg.str());
            }
            result.append(str);
            if (i < len - 1)
            {
                result.append(".");
            }
        }
        buf = result.str();
        return buf.str().c_str();
    }

    std::string UidIdentifierProcessor::unexpandOne(const std::string& spelling) const
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return spelling;
        }

        return formatUnexpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    bool UidIdentifierProcessor::startsWithUidToken(const std::string& str) const
    {
        return std::equal(m_uidToken.cbegin(), m_uidToken.cend(), str.cbegin());
    }

    bool UidIdentifierProcessor::hasValidPrefix(const std::string& str) const
    {
        return ( str != m_uidToken ) && ( str.at(m_uidToken.size()) != '-' );
    }

    std::string UidIdentifierProcessor::formatExpanded(const std::string& suffix)
    {
        compat::checkAssertion(m_count < 1000 * 1000 * 1000);
        constexpr std::size_t numDigits = 9;

        std::ostringstream ss;
        ss << m_uidToken << std::setw(numDigits) << std::setfill('0') << (m_count++) << "-" << suffix;

        return ss.str();
    }

    std::string UidIdentifierProcessor::formatUnexpanded(const std::string& suffix) const
    {
        return m_uidToken + suffix;
    }

    void UidIdentifierProcessor::checkCondition(bool result, const std::string& input) const
    {
        if( result == false )
        {
            throw ConfigurationException{"'" + input + "' is not a legal identifier"};
        }
    }

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

#include "danek/internal/UidIdentifierProcessor.h"
#include "danek/internal/Util.h"
#include "danek/internal/Compat.h"
#include "danek/ConfigurationException.h"
#include "danek/StringVector.h"
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <cctype>
#include <string.h>
#include <ctype.h>
#include <stdio.h>

namespace danek
{

    UidIdentifierProcessor::UidIdentifierProcessor() : m_count(0), m_uidToken("uid-")
    {
    }

    //----------------------------------------------------------------------
    // Spelling must be in one of the following forms:
    //      - "foo"                 -->  "foo"
    //      - "uid-<foo>"           -->  "uid-<digits>-<foo>"
    //      - "uid-<digits>-<foo>"  -->  "uid-<new-digits>-<foo>"
    // where "<foo>" does NOT start with a digit or "-"
    //----------------------------------------------------------------------

    std::string UidIdentifierProcessor::expand(const std::string& spelling)
    {
        if( spelling.find('.') == std::string::npos )
        {
            return expandOne(spelling);
        }

        if( spelling.find(m_uidToken) == std::string::npos )
        {
            return spelling;
        }

        using OItr = std::ostream_iterator<std::string>;

        const auto scopes = util::splitScopes(spelling);
        const auto f = [this](auto s) { return expandOne(s); };
        std::ostringstream result;

        std::transform(scopes.cbegin(), std::prev(scopes.cend()), OItr{result, "."}, f);
        std::transform(std::prev(scopes.cend()), scopes.cend(), OItr{result}, f);

        return result.str();
    }

    std::string UidIdentifierProcessor::expandOne(const std::string& spelling)
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        checkCondition(hasValidPrefix(spelling), spelling);

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return formatExpanded(std::string(digitsEnd, spelling.cend()));
        }

        checkCondition(hasValidPayload(digitsEnd, spelling.cend()), spelling);

        return formatExpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    std::string UidIdentifierProcessor::unexpand(const char* spelling, StringBuffer& buf) const
    {
        //--------
        // Common case optimizations
        //--------
        if (strchr(spelling, '.') == nullptr)
        {
            const auto result = unexpandOne(spelling);
            buf = result;
            return result;
        }
        if (strstr(spelling, "uid-") == nullptr)
        {
            return spelling;
        }

        //--------
        // Let's break apart the scoped name, unexpand each local part
        // and then recombine the parts into an unexpanded scoped name.
        //--------
        StringBuffer result;
        StringBuffer msg;

        StringVector vec{util::splitScopes(spelling)};
        const int len = vec.size();
        for (int i = 0; i < len; ++i)
        {
            std::string str;
            try
            {
                str = unexpandOne(vec[i]);
                buf = str;
            }
            catch (const ConfigurationException&)
            {
                msg << "'" << spelling << "' is not a legal identifier";
                throw ConfigurationException(msg.str());
            }
            result.append(str);
            if (i < len - 1)
            {
                result.append(".");
            }
        }
        buf = result.str();
        return buf.str().c_str();
    }

    std::string UidIdentifierProcessor::unexpandOne(const std::string& spelling) const
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return spelling;
        }

        return formatUnexpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    bool UidIdentifierProcessor::startsWithUidToken(const std::string& str) const
    {
        return std::equal(m_uidToken.cbegin(), m_uidToken.cend(), str.cbegin());
    }

    bool UidIdentifierProcessor::hasValidPrefix(const std::string& str) const
    {
        return ( str != m_uidToken ) && ( str.at(m_uidToken.size()) != '-' );
    }

    std::string UidIdentifierProcessor::formatExpanded(const std::string& suffix)
    {
        compat::checkAssertion(m_count < 1000 * 1000 * 1000);
        constexpr std::size_t numDigits = 9;

        std::ostringstream ss;
        ss << m_uidToken << std::setw(numDigits) << std::setfill('0') << (m_count++) << "-" << suffix;

        return ss.str();
    }

    std::string UidIdentifierProcessor::formatUnexpanded(const std::string& suffix) const
    {
        return m_uidToken + suffix;
    }

    void UidIdentifierProcessor::checkCondition(bool result, const std::string& input) const
    {
        if( result == false )
        {
            throw ConfigurationException{"'" + input + "' is not a legal identifier"};
        }
    }

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {qb_RoadExtract.tif}
//    OUTPUTS: {qb_blue.tif qb_shiftscale.tif}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  First, we are going to use \doxygen{otb}{VectorImage} instead of the now
// traditionnal \doxygen{otb}{Image}. So we include the required header:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbVectorImage.h"
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
// We also include some other header which will be useful later. Note that we
// are still using the \doxygen{otb}{Image} in this example for some of the
// output.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "itkShiftScaleImageFilter.h"
#include "otbPerBandVectorImageFilter.h"

int main( int argc, char * argv[] )
{
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // We want to read a multispectral image so we declare the image type and the
  // reader. As we have done in the previous example we get the filename from
  // the command line.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef unsigned short int PixelType;
  typedef otb::VectorImage<PixelType, 2> VectorImageType;

  typedef otb::ImageFileReader<VectorImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();

  reader->SetFileName(argv[1]);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Sometime, you need to process only one spectral band of the image. To get
  // only one of the spectral band we use the
  // /doxygen{otb}{MultiToMonoChannelExtractROI}. The declaration is as usual:
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractChannelType;
  ExtractChannelType::Pointer extractChannel = ExtractChannelType::New();

  //  Software Guide : BeginLatex
  //
  //  We need to pass the parameters to the filter for the extraction. This
  // filter also allow to extract only a spatial subset of the image. However,
  // we will extract the whole channel in this case.
  //
  // To do that, we need to pass the desired region using the
  // \code{SetExtractionRegion()} (method such as \code{SetStartX},
  // \code{SetSizeX} are also available). We get the region from the reader with
  // the \code{GetLargestPossibleRegion()} method. Before doing that we need to
  // read the metadata from the file: this is done by calling the
  // \code{UpdateOutputInformation()} on the reader's output. The difference with the
  // \code{Update()} is that the pixel array is not allocated (yet !) and reduce
  // the memory usage.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  reader->UpdateOutputInformation();
  extractChannel->SetExtractionRegion(reader->GetOutput()->GetLargestPossibleRegion());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We chose the channel number to extract (starting from 1) and we plug the
  // pipeline.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  extractChannel->SetChannel(3);
  extractChannel->SetInput(reader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  To output this image, we need a writer. As the output of the
  // \doxygen{otb}{MultiToMonoChannelExtractROI} is a \doxygen{otb}{Image}, we
  // need to template the writer with this type.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType, 2> ImageType;
  typedef otb::StreamingImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetFileName(argv[2]);
  writer->SetInput(extractChannel->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // After this, we have a one band image that we can process with most OTB
  // filters.
  //
  // In some situation, you may want to apply the same process to all bands of
  // the image. You don't have to extract each band and process them separately.
  // There is several situations:
  //
  // \begin{itemize}
  // \item the filter (or the combination of filters) you want to use are doing
  // operations that are well defined for \doxygen{itk}{VariableLengthVector}
  // (which is the pixel type), then you don't have to do anything special.
  // \item if this is not working, you can look for the equivalent filter
  // specially designed for vector images.
  // \item some of the filter you need to use applies operations undefined for
  // \doxygen{itk}{VariableLengthVector}, then you can use the
  // \doxygen{otb}{PerBandVectorImageFilter} specially designed for this
  // purpose.
  // \end{itemize}
  //
  // Let's see how this filter is working. We chose to apply the
  // \doxygen{itk}{ShiftScaleImageFilter} to each of the spectral band. We start
  // by declaring the filter on a normal \doxygen{otb}{Image}. Note that we
  // don't need to specify any input for this filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ShiftScaleImageFilter<ImageType, ImageType> ShiftScaleType;
  ShiftScaleType::Pointer shiftScale = ShiftScaleType::New();
  shiftScale->SetScale(0.5);
  shiftScale->SetShift(10);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // We declare the \doxygen{otb}{PerBandVectorImageFilter} which has three
  // template: the input image type, the output image type and the filter type
  // to apply to each band.
  //
  // The filter is selected using the \code{SetFilter()} method and the input
  // by the usual \code{SetInput()} method.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PerBandVectorImageFilter
      <VectorImageType, VectorImageType, ShiftScaleType> VectorFilterType;
  VectorFilterType::Pointer vectorFilter = VectorFilterType::New();
  vectorFilter->SetFilter(shiftScale);

  vectorFilter->SetInput(reader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // Now, we just have to save the image using a writer templated over an
  // \doxygen{otb}{VectorImage}:
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::StreamingImageFileWriter<VectorImageType> VectorWriterType;
  VectorWriterType::Pointer writerVector = VectorWriterType::New();

  writerVector->SetFileName(argv[3]);
  writerVector->SetInput(vectorFilter->GetOutput());

  writerVector->Update();

  return 0;
}
// Software Guide : EndCodeSnippet

<commit_msg>Coma missing<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {qb_RoadExtract.tif}
//    OUTPUTS: {qb_blue.tif}, {qb_shiftscale.tif}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  First, we are going to use \doxygen{otb}{VectorImage} instead of the now
// traditionnal \doxygen{otb}{Image}. So we include the required header:
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbVectorImage.h"
// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
// We also include some other header which will be useful later. Note that we
// are still using the \doxygen{otb}{Image} in this example for some of the
// output.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "itkShiftScaleImageFilter.h"
#include "otbPerBandVectorImageFilter.h"

int main( int argc, char * argv[] )
{
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // We want to read a multispectral image so we declare the image type and the
  // reader. As we have done in the previous example we get the filename from
  // the command line.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef unsigned short int PixelType;
  typedef otb::VectorImage<PixelType, 2> VectorImageType;

  typedef otb::ImageFileReader<VectorImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();

  reader->SetFileName(argv[1]);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Sometime, you need to process only one spectral band of the image. To get
  // only one of the spectral band we use the
  // /doxygen{otb}{MultiToMonoChannelExtractROI}. The declaration is as usual:
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractChannelType;
  ExtractChannelType::Pointer extractChannel = ExtractChannelType::New();

  //  Software Guide : BeginLatex
  //
  //  We need to pass the parameters to the filter for the extraction. This
  // filter also allow to extract only a spatial subset of the image. However,
  // we will extract the whole channel in this case.
  //
  // To do that, we need to pass the desired region using the
  // \code{SetExtractionRegion()} (method such as \code{SetStartX},
  // \code{SetSizeX} are also available). We get the region from the reader with
  // the \code{GetLargestPossibleRegion()} method. Before doing that we need to
  // read the metadata from the file: this is done by calling the
  // \code{UpdateOutputInformation()} on the reader's output. The difference with the
  // \code{Update()} is that the pixel array is not allocated (yet !) and reduce
  // the memory usage.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  reader->UpdateOutputInformation();
  extractChannel->SetExtractionRegion(reader->GetOutput()->GetLargestPossibleRegion());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We chose the channel number to extract (starting from 1) and we plug the
  // pipeline.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  extractChannel->SetChannel(3);
  extractChannel->SetInput(reader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  To output this image, we need a writer. As the output of the
  // \doxygen{otb}{MultiToMonoChannelExtractROI} is a \doxygen{otb}{Image}, we
  // need to template the writer with this type.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::Image<PixelType, 2> ImageType;
  typedef otb::StreamingImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetFileName(argv[2]);
  writer->SetInput(extractChannel->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // After this, we have a one band image that we can process with most OTB
  // filters.
  //
  // In some situation, you may want to apply the same process to all bands of
  // the image. You don't have to extract each band and process them separately.
  // There is several situations:
  //
  // \begin{itemize}
  // \item the filter (or the combination of filters) you want to use are doing
  // operations that are well defined for \doxygen{itk}{VariableLengthVector}
  // (which is the pixel type), then you don't have to do anything special.
  // \item if this is not working, you can look for the equivalent filter
  // specially designed for vector images.
  // \item some of the filter you need to use applies operations undefined for
  // \doxygen{itk}{VariableLengthVector}, then you can use the
  // \doxygen{otb}{PerBandVectorImageFilter} specially designed for this
  // purpose.
  // \end{itemize}
  //
  // Let's see how this filter is working. We chose to apply the
  // \doxygen{itk}{ShiftScaleImageFilter} to each of the spectral band. We start
  // by declaring the filter on a normal \doxygen{otb}{Image}. Note that we
  // don't need to specify any input for this filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::ShiftScaleImageFilter<ImageType, ImageType> ShiftScaleType;
  ShiftScaleType::Pointer shiftScale = ShiftScaleType::New();
  shiftScale->SetScale(0.5);
  shiftScale->SetShift(10);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // We declare the \doxygen{otb}{PerBandVectorImageFilter} which has three
  // template: the input image type, the output image type and the filter type
  // to apply to each band.
  //
  // The filter is selected using the \code{SetFilter()} method and the input
  // by the usual \code{SetInput()} method.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PerBandVectorImageFilter
      <VectorImageType, VectorImageType, ShiftScaleType> VectorFilterType;
  VectorFilterType::Pointer vectorFilter = VectorFilterType::New();
  vectorFilter->SetFilter(shiftScale);

  vectorFilter->SetInput(reader->GetOutput());
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // Now, we just have to save the image using a writer templated over an
  // \doxygen{otb}{VectorImage}:
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::StreamingImageFileWriter<VectorImageType> VectorWriterType;
  VectorWriterType::Pointer writerVector = VectorWriterType::New();

  writerVector->SetFileName(argv[3]);
  writerVector->SetInput(vectorFilter->GetOutput());

  writerVector->Update();

  return 0;
}
// Software Guide : EndCodeSnippet

<|endoftext|>


<commit_before>#include <QtCore>
#include <QtGui>
#include <QFile>
#include <iostream>
#include <mainwindow.h>
using namespace std;

int len(char* str)
{
    int i=0;
    while(str[i])
        i++;
    return i;
}

int main(int argc, char *argv[])
{
    bool usegui=false;
    bool stripcomments=false;
    QString parameters;
    QStringList arguments;
    for(int i=1; i<argc; ++i)
    {
        if(argv[i][0]=='-')
            parameters+=QString::fromLocal8Bit(argv[i]+1);
        else
            arguments<<QString::fromLocal8Bit(argv[i]);
    }
    if (!parameters.isEmpty())
    {
        for(int i=0; i<parameters.length(); ++i)
        {
            if(parameters[i]=='g')
                usegui=true;
            else if (parameters[i]=='s')
                stripcomments=true;
            else
                goto usage;
        }
    }

    if(arguments.count()==1 && !usegui)
    {
        QFile f(arguments[0]);
        if (f.open(QIODevice::ReadOnly))
        {
            QString line;
            QStringList header;

            //build header
            while(!f.atEnd())
            {
                line = QString::fromUtf8(f.readLine());
                while (line.startsWith('#')){
                    line = QString::fromUtf8(f.readLine());
                }
                QStringList dataline=line.split(";");
                foreach(QString entry, dataline)
                {
                    QString name=entry.split(":").at(0);
                    if(!header.contains(name))
                        header<<name;
                }
            }

            f.seek(0);
            do{
                line = QString::fromUtf8(f.readLine());
                if(!stripcomments && line.startsWith('#'))
                    cout<<line.toLocal8Bit().data();
            }while (line.startsWith('#'));

            //output header
            foreach(QString name, header)
                cout<<name.toLocal8Bit().data()<<"\t";
            cout<<"\n";

            while(true)
            {
                QStringList dataline=line.split(";");
                QVector<QString> row;
                row.fill("0",header.count());
                foreach(QString entry, dataline)
                {
                    QString name=entry.split(":").at(0);
                    QString value=entry.split(":").at(1);
                    int id=header.indexOf(name);
                    row[id]=value.remove("\n");
                }
                foreach(QString cell, row)
                    cout<<cell.toLocal8Bit().data()<<"\t";
                cout<<"\n";
                if(f.atEnd())
                    break;
                else
                    line = QString::fromUtf8(f.readLine());
            }
        } else {
            cout<<"Could not open file ";
            cout<<(arguments.at(0).toLocal8Bit().data());
            cout<<":";
            cout<<f.errorString().toLocal8Bit().data();
        }
        return 0;
    } else if (arguments.count()==1 && usegui) {
        //show gui
        QApplication a(argc,argv);
        MainWindow w(arguments[0]);
        w.show();
        a.exec();
        return 0;
    }
    usage:
    cout<<"Usage: asec_parser [-gs] \"filename.red\"";
    return 1;
}
<commit_msg>bugfixes<commit_after>#include <QtCore>
#include <QtGui>
#include <QFile>
#include <iostream>
#include <mainwindow.h>
using namespace std;

int len(char* str)
{
    int i=0;
    while(str[i])
        i++;
    return i;
}

int main(int argc, char *argv[])
{
    bool usegui=false;
    bool stripcomments=false;
    QString parameters;
    QStringList arguments;
    for(int i=1; i<argc; ++i)
    {
        if(argv[i][0]=='-')
            parameters+=QString::fromLocal8Bit(argv[i]+1);
        else
            arguments<<QString::fromLocal8Bit(argv[i]);
    }
    if (!parameters.isEmpty())
    {
        for(int i=0; i<parameters.length(); ++i)
        {
            if(parameters[i]=='g')
                usegui=true;
            else if (parameters[i]=='s')
                stripcomments=true;
            else
                goto usage;
        }
    }

    if(arguments.count()==1 && !usegui)
    {
        QFile f(arguments[0]);
        if (f.open(QIODevice::ReadOnly))
        {
            QString line;
            QStringList header;

            //build header
            while(!f.atEnd())
            {
                line = QString::fromUtf8(f.readLine());
                while (line.startsWith('#')){
                    line = QString::fromUtf8(f.readLine());
                }
                if(!line.contains(":")) continue;
                QStringList dataline=line.split(";");
                foreach(QString entry, dataline)
                {
                    QString name=entry.split(":").at(0);
                    if(!header.contains(name))
                        header<<name;
                }
            }

            f.seek(0);
            do{
                line = QString::fromUtf8(f.readLine());
                if(!stripcomments && line.startsWith('#'))
                    cout<<line.toLocal8Bit().data();
            }while (line.startsWith('#'));

            //output header
            foreach(QString name, header)
                cout<<name.toLocal8Bit().data()<<"\t";
            cout<<"\n";

            while(true)
            {
                QStringList dataline=line.split(";");
                QVector<QString> row;
                if(!line.contains(":")) goto cont;
                row.fill("0",header.count());
                foreach(QString entry, dataline)
                {
                    QString name=entry.split(":").at(0);
                    QString value=entry.split(":").at(1);
                    int id=header.indexOf(name);
                    row[id]=value.remove("\n");
                }
                foreach(QString cell, row)
                    cout<<cell.toLocal8Bit().data()<<"\t";
                cout<<"\n";
                cont:
                if(f.atEnd())
                    break;
                else
                    line = QString::fromUtf8(f.readLine());
            }
        } else {
            cout<<"Could not open file ";
            cout<<(arguments.at(0).toLocal8Bit().data());
            cout<<":";
            cout<<f.errorString().toLocal8Bit().data();
        }
        return 0;
    } else if (arguments.count()==1 && usegui) {
        //show gui
        QApplication a(argc,argv);
        MainWindow w(arguments[0]);
        w.show();
        a.exec();
        return 0;
    }
    usage:
    cout<<"Usage: asec_parser [-gs] \"filename.red\"";
    return 1;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <math.h>
#include <Halide.h>
#include <iostream>
#include <limits>

using namespace Halide;

template <typename value_t>
bool relatively_equal(value_t a, value_t b) {
    if (a == b) {
        return true;
    } else if (!std::numeric_limits<value_t>::is_integer) {
        double da = (double)a, db = (double)b;
        double relative_error;

        // This test seems a bit high.
        if (fabs(db - da) < .0001)
          return true;

        if (fabs(da) > fabs(db))
            relative_error = fabs((db - da) / da);
        else
            relative_error = fabs((db - da) / db);

        if (relative_error < .0000005)
          return true;
        std::cerr << "relatively_equal failed for (" << a << ", " << b <<
          ") with relative error " << relative_error << std::endl;
    }
    return false;
}

// Using macros to expand name as both a C function and an Expr fragment.
// It may well be possible to do this without macros, but that is left
// for another day.

// Version for a one argument function.
#define fun_1(type, name, c_name)                                             \
    void test_##type##_##name(buffer_t *in_buf) {                             \
        Target target = get_jit_target_from_environment();                    \
        if ((target.features & Target::OpenCL) != 0 &&                        \
            (target.features & Target::CLDoubles) == 0 &&                     \
            type_of<type>() == type_of<double>()) {                           \
            return;                                                           \
        }                                                                     \
        Func test_##name("test_" #name);                                      \
        Var x("x");                                                           \
        ImageParam input(type_of<type>(), 1);                                 \
        test_##name(x) = name(input(x));                                      \
        Buffer in_buffer(type_of<type>(), in_buf);                            \
        input.set(in_buffer);                                                 \
        if (target.has_gpu_feature()) {                                       \
            test_##name.gpu_tile(x, 8, GPU_Default);                          \
        }                                                                     \
        Image<type> result = test_##name.realize(in_buf->extent[0], target);  \
        for (int i = 0; i < in_buf->extent[0]; i++) {                         \
          type c_result = c_name(reinterpret_cast<type *>(in_buf->host)[i]);  \
          assert(relatively_equal(c_result, result(i)) &&                     \
                 "Failure on function " #name);                               \
        }                                                                     \
    }

// Version for a one argument function
#define fun_2(type, name, c_name)                                                   \
    void test_##type##_##name(buffer_t *in_buf) {                                   \
        Target target = get_jit_target_from_environment();                          \
        if ((target.features & Target::OpenCL) != 0 &&                              \
            (target.features & Target::CLDoubles) == 0 &&                           \
            type_of<type>() == type_of<double>()) {                                 \
            return;                                                                 \
        }                                                                           \
        Func test_##name("test_" #name);                                            \
        Var x("x");                                                                 \
        ImageParam input(type_of<type>(), 2);                                       \
        test_##name(x) = name(input(0, x), input(1, x));                            \
        Buffer in_buffer(type_of<type>(), in_buf);                                  \
        input.set(in_buffer);                                                       \
        if (target.has_gpu_feature()) {                                             \
          test_##name.gpu_tile(x, 8, GPU_Default);                                  \
        }                                                                           \
        Image<type> result = test_##name.realize(in_buf->extent[1], target);        \
        for (int i = 0; i < in_buf->extent[1]; i++) {                               \
          type c_result = c_name(reinterpret_cast<type *>(in_buf->host)[i * 2],     \
                                 reinterpret_cast<type *>(in_buf->host)[i * 2 + 1]);\
          assert(relatively_equal(c_result, result(i)) &&                           \
                 "Failure on function " #name);                                     \
        }                                                                           \
    }

#define fun_1_all_types(name)    \
  fun_1(float, name, name)       \
  fun_1(double, name, name)

#define fun_2_all_types(name)    \
  fun_2(float, name, name)       \
  fun_2(double, name, name)

fun_1_all_types(sqrt)
fun_1_all_types(sin)
fun_1_all_types(cos)
fun_1_all_types(exp)
fun_1_all_types(log)
fun_1_all_types(floor)
fun_1_all_types(ceil)
fun_1_all_types(asin)
fun_1_all_types(acos)
fun_1_all_types(tan)
fun_1_all_types(atan)
fun_1_all_types(sinh)
fun_1_all_types(cosh)
fun_1_all_types(tanh)
#ifndef _MSC_VER
// These functions don't exist in msvc < 2012
fun_1_all_types(asinh)
fun_1_all_types(acosh)
fun_1_all_types(atanh)
fun_1_all_types(round)
#endif

fun_1(float, abs, fabsf)
fun_1(double, abs, fabs)

fun_2_all_types(pow)
fun_2_all_types(atan2)

template <typename T>
struct TestArgs {
    Image<T> data;

    TestArgs(int steps, T start, T end)
      : data(steps) {
        for (int i = 0; i < steps; i++) {
            data(i) = (T)((double)start + i * ((double)end - start) / steps);
        }
    }

    TestArgs(int steps,
             T start_x, T end_x,
             T start_y, T end_y)
      : data(2, steps) {
          for (int i = 0; i < steps; i++) {
            data(0, i) = (T)((double)start_x + i * ((double)end_x - start_x) / steps);
            data(1, i) = (T)((double)start_y + i * ((double)end_y - start_y) / steps);
          }
      }

    operator buffer_t *() { return data.raw_buffer(); }
};

// Note this test is more oriented toward making sure the paths
// through to math functions all work on a given target rather
// than usefully testing the accuracy of mathematical operations.
// As such little effort has been put into the domains tested,
// other than making sure they are valid for each function.

#define call_1(name, steps, start, end)                           \
    {                                                             \
    printf("Testing " #name "\n");                                \
    TestArgs<float> name##_float_args(steps, start, end);         \
    test_float_##name(name##_float_args);                         \
    TestArgs<double> name##_double_args(steps, start, end);       \
    test_double_##name(name##_double_args);                       \
    }

#define call_2(name, steps, start1, end1, start2, end2)                     \
    {                                                                       \
    printf("Testing " #name "\n");                                          \
    TestArgs<float> name##_float_args(steps, start1, end1, start2, end2);   \
    test_float_##name(name##_float_args);                                   \
    TestArgs<double> name##_double_args(steps, start1, end1, start2, end2); \
    test_double_##name(name##_double_args);                                 \
    }

int main(int argc, char **argv) {
    call_1(abs, 256, -1000, 1000);
    call_1(sqrt, 256, 0, 1000000)

    call_1(sin, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(cos, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(tan, 256, 5 * -3.1415, 5 * 3.1415)

    call_1(asin, 256, -1.0, 1.0)
    call_1(acos, 256, -1.0, 1.0)
    call_1(atan, 256, -256, 100)
    call_2(atan2, 256, -20, 20, -2, 2)

    call_1(sinh, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(cosh, 256, 0, 1)
    call_1(tanh, 256, 5 * -3.1415, 5 * 3.1415)

#ifndef _MSC_VER
    call_1(asinh, 256, -10.0, 10.0)
    call_1(acosh, 256, 1.0, 10)
    call_1(atanh, 256, -1.0, 1.0)
    call_1(round, 256, -15, 15)
#endif

    call_1(exp, 256, 0, 20)
    call_1(log, 256, 1, 1000000)
    call_1(floor, 256, -25, 25)
    call_1(ceil, 256, -25, 25)
    call_2(pow, 256, .1, 20, .1, 2)

    printf("Success!\n");
    return 0;
}
<commit_msg>Dodge testing atan2(0, 0)<commit_after>#include <stdio.h>
#include <math.h>
#include <Halide.h>
#include <iostream>
#include <limits>

using namespace Halide;

template <typename value_t>
bool relatively_equal(value_t a, value_t b) {
    if (a == b) {
        return true;
    } else if (!std::numeric_limits<value_t>::is_integer) {
        double da = (double)a, db = (double)b;
        double relative_error;

        // This test seems a bit high.
        if (fabs(db - da) < .0001)
          return true;

        if (fabs(da) > fabs(db))
            relative_error = fabs((db - da) / da);
        else
            relative_error = fabs((db - da) / db);

        if (relative_error < .0000005)
          return true;
        std::cerr << "relatively_equal failed for (" << a << ", " << b <<
          ") with relative error " << relative_error << std::endl;
    }
    return false;
}

// Using macros to expand name as both a C function and an Expr fragment.
// It may well be possible to do this without macros, but that is left
// for another day.

// Version for a one argument function.
#define fun_1(type, name, c_name)                                             \
    void test_##type##_##name(buffer_t *in_buf) {                             \
        Target target = get_jit_target_from_environment();                    \
        if ((target.features & Target::OpenCL) != 0 &&                        \
            (target.features & Target::CLDoubles) == 0 &&                     \
            type_of<type>() == type_of<double>()) {                           \
            return;                                                           \
        }                                                                     \
        Func test_##name("test_" #name);                                      \
        Var x("x");                                                           \
        ImageParam input(type_of<type>(), 1);                                 \
        test_##name(x) = name(input(x));                                      \
        Buffer in_buffer(type_of<type>(), in_buf);                            \
        input.set(in_buffer);                                                 \
        if (target.has_gpu_feature()) {                                       \
            test_##name.gpu_tile(x, 8, GPU_Default);                          \
        }                                                                     \
        Image<type> result = test_##name.realize(in_buf->extent[0], target);  \
        for (int i = 0; i < in_buf->extent[0]; i++) {                         \
          type c_result = c_name(reinterpret_cast<type *>(in_buf->host)[i]);  \
          assert(relatively_equal(c_result, result(i)) &&                     \
                 "Failure on function " #name);                               \
        }                                                                     \
    }

// Version for a one argument function
#define fun_2(type, name, c_name)                                                   \
    void test_##type##_##name(buffer_t *in_buf) {                                   \
        Target target = get_jit_target_from_environment();                          \
        if ((target.features & Target::OpenCL) != 0 &&                              \
            (target.features & Target::CLDoubles) == 0 &&                           \
            type_of<type>() == type_of<double>()) {                                 \
            return;                                                                 \
        }                                                                           \
        Func test_##name("test_" #name);                                            \
        Var x("x");                                                                 \
        ImageParam input(type_of<type>(), 2);                                       \
        test_##name(x) = name(input(0, x), input(1, x));                            \
        Buffer in_buffer(type_of<type>(), in_buf);                                  \
        input.set(in_buffer);                                                       \
        if (target.has_gpu_feature()) {                                             \
          test_##name.gpu_tile(x, 8, GPU_Default);                                  \
        }                                                                           \
        Image<type> result = test_##name.realize(in_buf->extent[1], target);        \
        for (int i = 0; i < in_buf->extent[1]; i++) {                               \
          type c_result = c_name(reinterpret_cast<type *>(in_buf->host)[i * 2],     \
                                 reinterpret_cast<type *>(in_buf->host)[i * 2 + 1]);\
          assert(relatively_equal(c_result, result(i)) &&                           \
                 "Failure on function " #name);                                     \
        }                                                                           \
    }

#define fun_1_all_types(name)    \
  fun_1(float, name, name)       \
  fun_1(double, name, name)

#define fun_2_all_types(name)    \
  fun_2(float, name, name)       \
  fun_2(double, name, name)

fun_1_all_types(sqrt)
fun_1_all_types(sin)
fun_1_all_types(cos)
fun_1_all_types(exp)
fun_1_all_types(log)
fun_1_all_types(floor)
fun_1_all_types(ceil)
fun_1_all_types(asin)
fun_1_all_types(acos)
fun_1_all_types(tan)
fun_1_all_types(atan)
fun_1_all_types(sinh)
fun_1_all_types(cosh)
fun_1_all_types(tanh)
#ifndef _MSC_VER
// These functions don't exist in msvc < 2012
fun_1_all_types(asinh)
fun_1_all_types(acosh)
fun_1_all_types(atanh)
fun_1_all_types(round)
#endif

fun_1(float, abs, fabsf)
fun_1(double, abs, fabs)

fun_2_all_types(pow)
fun_2_all_types(atan2)

template <typename T>
struct TestArgs {
    Image<T> data;

    TestArgs(int steps, T start, T end)
      : data(steps) {
        for (int i = 0; i < steps; i++) {
            data(i) = (T)((double)start + i * ((double)end - start) / steps);
        }
    }

    TestArgs(int steps,
             T start_x, T end_x,
             T start_y, T end_y)
      : data(2, steps) {
          for (int i = 0; i < steps; i++) {
            data(0, i) = (T)((double)start_x + i * ((double)end_x - start_x) / steps);
            data(1, i) = (T)((double)start_y + i * ((double)end_y - start_y) / steps);
          }
      }

    operator buffer_t *() { return data.raw_buffer(); }
};

// Note this test is more oriented toward making sure the paths
// through to math functions all work on a given target rather
// than usefully testing the accuracy of mathematical operations.
// As such little effort has been put into the domains tested,
// other than making sure they are valid for each function.

#define call_1(name, steps, start, end)                           \
    {                                                             \
    printf("Testing " #name "\n");                                \
    TestArgs<float> name##_float_args(steps, start, end);         \
    test_float_##name(name##_float_args);                         \
    TestArgs<double> name##_double_args(steps, start, end);       \
    test_double_##name(name##_double_args);                       \
    }

#define call_2(name, steps, start1, end1, start2, end2)                     \
    {                                                                       \
    printf("Testing " #name "\n");                                          \
    TestArgs<float> name##_float_args(steps, start1, end1, start2, end2);   \
    test_float_##name(name##_float_args);                                   \
    TestArgs<double> name##_double_args(steps, start1, end1, start2, end2); \
    test_double_##name(name##_double_args);                                 \
    }

int main(int argc, char **argv) {
    call_1(abs, 256, -1000, 1000);
    call_1(sqrt, 256, 0, 1000000)

    call_1(sin, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(cos, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(tan, 256, 5 * -3.1415, 5 * 3.1415)

    call_1(asin, 256, -1.0, 1.0)
    call_1(acos, 256, -1.0, 1.0)
    call_1(atan, 256, -256, 100)
    call_2(atan2, 256, -20, 20, -2, 2.001)

    call_1(sinh, 256, 5 * -3.1415, 5 * 3.1415)
    call_1(cosh, 256, 0, 1)
    call_1(tanh, 256, 5 * -3.1415, 5 * 3.1415)

#ifndef _MSC_VER
    call_1(asinh, 256, -10.0, 10.0)
    call_1(acosh, 256, 1.0, 10)
    call_1(atanh, 256, -1.0, 1.0)
    call_1(round, 256, -15, 15)
#endif

    call_1(exp, 256, 0, 20)
    call_1(log, 256, 1, 1000000)
    call_1(floor, 256, -25, 25)
    call_1(ceil, 256, -25, 25)
    call_2(pow, 256, .1, 20, .1, 2)

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
#include "../exceptions/context_index_out_of_range_exception.h"
#include "../result.h"
#include "query_executor_builder_visitor.h"

namespace You {
namespace Controller {
namespace Internal {

using You::NLP::TaskField;
using You::NLP::TaskPriority;
using You::NLP::QUERY;
using You::NLP::ADD_QUERY;
using You::NLP::SHOW_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::DELETE_QUERY;
using You::NLP::UNDO_QUERY;

QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(
	const Controller::Context& context)
	: context(context) {
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {
	class AddTaskQueryExecutor : public QueryExecutor {
	public:
		explicit AddTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~AddTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return ADD_RESULT {
				boost::get<Task>(response)
			};
		}
	};

	return std::unique_ptr<QueryExecutor>(
		new AddTaskQueryExecutor(
			QueryEngine::AddTask(
				query.description,
				query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,
				query.priority == TaskPriority::HIGH ?
					Task::Priority::HIGH : Task::Priority::NORMAL,
				Task::Dependencies()
			)
		)
	);
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) {
	class ShowTaskQueryExecutor : public QueryExecutor {
	public:
		explicit ShowTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~ShowTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return SHOW_RESULT {
				boost::get<TaskList>(response)
			};
		}
	};

	using You::QueryEngine::Filter;
	using You::QueryEngine::Comparator;
	Filter filter = Filter::anyTask();
	Comparator comparator(Comparator::notSorted());

	std::for_each(begin(query.predicates), end(query.predicates),
		[&filter](const SHOW_QUERY::FIELD_FILTER& field) {
			std::function<bool(const Task&)> currentFilter;
			switch (field.field) {
			case TaskField::DESCRIPTION:
				assert(boost::get<std::wstring>(&field.value));
				currentFilter = buildComparator(&Task::getDescription,
					field.predicate,
					boost::get<std::wstring>(field.value));
				break;
			case TaskField::DEADLINE:
				assert(boost::get<boost::posix_time::ptime>(&field.value));
				currentFilter = buildComparator(&Task::getDeadline,
					field.predicate,
					boost::get<boost::posix_time::ptime>(field.value));
				break;
			case TaskField::COMPLETE:
				assert(boost::get<bool>(&field.value));
				currentFilter = buildComparator(&Task::isCompleted,
					field.predicate,
					boost::get<bool>(field.value));
				break;
			case TaskField::PRIORITY:
				assert(boost::get<TaskPriority>(&field.value));
				currentFilter = buildComparator(&Task::getPriority,
					field.predicate,
					Controller::nlpToQueryEnginePriority(
						boost::get<TaskPriority>(field.value)));
				break;
			default:
				assert(false); abort();
			}

			filter = filter && Filter(currentFilter);
		});

	std::for_each(begin(query.order), end(query.order),
		[&comparator](const SHOW_QUERY::FIELD_ORDER& field) {
			Comparator comp(Comparator::notSorted());
			switch (field.field) {
			case TaskField::DESCRIPTION:
				comp = Comparator::byDescription();
				break;
			case TaskField::DEADLINE:
				comp = Comparator::byDeadline();
				break;
			case TaskField::PRIORITY:
				comp = Comparator::byPriority();
				break;
			case TaskField::COMPLETE:
			default:
				assert(false); abort();
			}

			if (field.order == SHOW_QUERY::Order::ASCENDING) {
				comp = comp.ascending();
			} else {
				comp = comp.descending();
			}

			comparator = comparator && comp;
		});

	return std::unique_ptr<QueryExecutor>(
		new ShowTaskQueryExecutor(
			QueryEngine::GetTask(filter, comparator)
		)
	);
}

template<typename TValue>
std::function<bool(const Task&)>
QueryExecutorBuilderVisitor::buildComparator(
	TValue(QueryEngine::Task::*selector)() const,
	SHOW_QUERY::Predicate predicate,
	const TValue& value) {
	switch (predicate) {
	case SHOW_QUERY::Predicate::EQ:
		return std::bind(std::equal_to<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::NOT_EQ:
		return std::bind(std::not_equal_to<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::LESS_THAN:
		return std::bind(std::less<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::LESS_THAN_EQ:
		return std::bind(std::less_equal<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::GREATER_THAN:
		return std::bind(std::greater<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::GREATER_THAN_EQ:
		return std::bind(std::greater_equal<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	default:
		assert(false); abort();
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {
	class EditTaskQueryExecutor : public QueryExecutor {
	public:
		explicit EditTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~EditTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return EDIT_RESULT {
				boost::get<Task>(response)
			};
		}
	};

	try {
		const Task& task = context.at(query.taskID);
		You::Utils::Option<Task::Priority> priority;
		if (query.priority) {
			if (query.priority.get() == TaskPriority::NORMAL) {
				priority = Task::Priority::NORMAL;
			} else {
				priority = Task::Priority::HIGH;
			}
		}
		return std::unique_ptr<QueryExecutor>(
			new EditTaskQueryExecutor(
				QueryEngine::UpdateTask(
					task.getID(),
					query.description,
					query.deadline,
					priority,
					boost::none,
					boost::none)));
	} catch (std::out_of_range& e) {
		throw ContextIndexOutOfRangeException(e);
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {
	class DeleteTaskQueryExecutor : public QueryExecutor {
	public:
		explicit DeleteTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~DeleteTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return DELETE_RESULT {
				boost::get<Task::ID>(response)
			};
		}
	};

	try {
		const Task& task = context.at(query.taskID);

		return std::unique_ptr<QueryExecutor>(
			new DeleteTaskQueryExecutor(
				QueryEngine::DeleteTask(
					task.getID())));
	} catch (std::out_of_range& e) {
		throw ContextIndexOutOfRangeException(e);
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const UNDO_QUERY& query) const {
	class UndoTaskQueryExecutor : public QueryExecutor {
	public:
		explicit UndoTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~UndoTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return UNDO_RESULT {
			};
		}
	};

	return std::unique_ptr<QueryExecutor>(
		new UndoTaskQueryExecutor(
			QueryEngine::Undo()));
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You
<commit_msg>Mark a task as complete when specified in the command.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
#include "../exceptions/context_index_out_of_range_exception.h"
#include "../result.h"
#include "query_executor_builder_visitor.h"

namespace You {
namespace Controller {
namespace Internal {

using You::NLP::TaskField;
using You::NLP::TaskPriority;
using You::NLP::QUERY;
using You::NLP::ADD_QUERY;
using You::NLP::SHOW_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::DELETE_QUERY;
using You::NLP::UNDO_QUERY;

QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor(
	const Controller::Context& context)
	: context(context) {
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) {
	class AddTaskQueryExecutor : public QueryExecutor {
	public:
		explicit AddTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~AddTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return ADD_RESULT {
				boost::get<Task>(response)
			};
		}
	};

	return std::unique_ptr<QueryExecutor>(
		new AddTaskQueryExecutor(
			QueryEngine::AddTask(
				query.description,
				query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE,
				query.priority == TaskPriority::HIGH ?
					Task::Priority::HIGH : Task::Priority::NORMAL,
				Task::Dependencies()
			)
		)
	);
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) {
	class ShowTaskQueryExecutor : public QueryExecutor {
	public:
		explicit ShowTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~ShowTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return SHOW_RESULT {
				boost::get<TaskList>(response)
			};
		}
	};

	using You::QueryEngine::Filter;
	using You::QueryEngine::Comparator;
	Filter filter = Filter::anyTask();
	Comparator comparator(Comparator::notSorted());

	std::for_each(begin(query.predicates), end(query.predicates),
		[&filter](const SHOW_QUERY::FIELD_FILTER& field) {
			std::function<bool(const Task&)> currentFilter;
			switch (field.field) {
			case TaskField::DESCRIPTION:
				assert(boost::get<std::wstring>(&field.value));
				currentFilter = buildComparator(&Task::getDescription,
					field.predicate,
					boost::get<std::wstring>(field.value));
				break;
			case TaskField::DEADLINE:
				assert(boost::get<boost::posix_time::ptime>(&field.value));
				currentFilter = buildComparator(&Task::getDeadline,
					field.predicate,
					boost::get<boost::posix_time::ptime>(field.value));
				break;
			case TaskField::COMPLETE:
				assert(boost::get<bool>(&field.value));
				currentFilter = buildComparator(&Task::isCompleted,
					field.predicate,
					boost::get<bool>(field.value));
				break;
			case TaskField::PRIORITY:
				assert(boost::get<TaskPriority>(&field.value));
				currentFilter = buildComparator(&Task::getPriority,
					field.predicate,
					Controller::nlpToQueryEnginePriority(
						boost::get<TaskPriority>(field.value)));
				break;
			default:
				assert(false); abort();
			}

			filter = filter && Filter(currentFilter);
		});

	std::for_each(begin(query.order), end(query.order),
		[&comparator](const SHOW_QUERY::FIELD_ORDER& field) {
			Comparator comp(Comparator::notSorted());
			switch (field.field) {
			case TaskField::DESCRIPTION:
				comp = Comparator::byDescription();
				break;
			case TaskField::DEADLINE:
				comp = Comparator::byDeadline();
				break;
			case TaskField::PRIORITY:
				comp = Comparator::byPriority();
				break;
			case TaskField::COMPLETE:
			default:
				assert(false); abort();
			}

			if (field.order == SHOW_QUERY::Order::ASCENDING) {
				comp = comp.ascending();
			} else {
				comp = comp.descending();
			}

			comparator = comparator && comp;
		});

	return std::unique_ptr<QueryExecutor>(
		new ShowTaskQueryExecutor(
			QueryEngine::GetTask(filter, comparator)
		)
	);
}

template<typename TValue>
std::function<bool(const Task&)>
QueryExecutorBuilderVisitor::buildComparator(
	TValue(QueryEngine::Task::*selector)() const,
	SHOW_QUERY::Predicate predicate,
	const TValue& value) {
	switch (predicate) {
	case SHOW_QUERY::Predicate::EQ:
		return std::bind(std::equal_to<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::NOT_EQ:
		return std::bind(std::not_equal_to<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::LESS_THAN:
		return std::bind(std::less<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::LESS_THAN_EQ:
		return std::bind(std::less_equal<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::GREATER_THAN:
		return std::bind(std::greater<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	case SHOW_QUERY::Predicate::GREATER_THAN_EQ:
		return std::bind(std::greater_equal<TValue>(),
			std::bind(selector, std::placeholders::_1),
			value);
	default:
		assert(false); abort();
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const {
	class EditTaskQueryExecutor : public QueryExecutor {
	public:
		explicit EditTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~EditTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return EDIT_RESULT {
				boost::get<Task>(response)
			};
		}
	};

	try {
		const Task& task = context.at(query.taskID);
		You::Utils::Option<Task::Priority> priority;
		if (query.priority) {
			if (query.priority.get() == TaskPriority::NORMAL) {
				priority = Task::Priority::NORMAL;
			} else {
				priority = Task::Priority::HIGH;
			}
		}
		return std::unique_ptr<QueryExecutor>(
			new EditTaskQueryExecutor(
				QueryEngine::UpdateTask(
					task.getID(),
					query.description,
					query.deadline,
					priority,
					boost::none,
					query.complete)));
	} catch (std::out_of_range& e) {
		throw ContextIndexOutOfRangeException(e);
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const {
	class DeleteTaskQueryExecutor : public QueryExecutor {
	public:
		explicit DeleteTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~DeleteTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return DELETE_RESULT {
				boost::get<Task::ID>(response)
			};
		}
	};

	try {
		const Task& task = context.at(query.taskID);

		return std::unique_ptr<QueryExecutor>(
			new DeleteTaskQueryExecutor(
				QueryEngine::DeleteTask(
					task.getID())));
	} catch (std::out_of_range& e) {
		throw ContextIndexOutOfRangeException(e);
	}
}

std::unique_ptr<QueryExecutor>
QueryExecutorBuilderVisitor::build(const UNDO_QUERY& query) const {
	class UndoTaskQueryExecutor : public QueryExecutor {
	public:
		explicit UndoTaskQueryExecutor(
			std::unique_ptr<QueryEngine::Query>&& query)
			: QueryExecutor(std::move(query)) {
		}

		virtual ~UndoTaskQueryExecutor() = default;

	protected:
		Result processResponse(
			const You::QueryEngine::Response& response) override {
			return UNDO_RESULT {
			};
		}
	};

	return std::unique_ptr<QueryExecutor>(
		new UndoTaskQueryExecutor(
			QueryEngine::Undo()));
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You
<|endoftext|>


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

#include "danek/internal/UidIdentifierProcessor.h"
#include "danek/internal/Util.h"
#include "danek/internal/Compat.h"
#include "danek/ConfigurationException.h"
#include "danek/StringVector.h"
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <string.h>
#include <ctype.h>
#include <stdio.h>

namespace danek
{

    UidIdentifierProcessor::UidIdentifierProcessor() : m_count(0), m_uidToken("uid-")
    {
    }

    //----------------------------------------------------------------------
    // Spelling must be in one of the following forms:
    //      - "foo"                 -->  "foo"
    //      - "uid-<foo>"           -->  "uid-<digits>-<foo>"
    //      - "uid-<digits>-<foo>"  -->  "uid-<new-digits>-<foo>"
    // where "<foo>" does NOT start with a digit or "-"
    //----------------------------------------------------------------------

    std::string UidIdentifierProcessor::expand(const std::string& spelling)
    {
        // Common case optimizations
        if( spelling.find('.') == std::string::npos )
        {
            return expandOne(spelling);
        }

        if( spelling.find(m_uidToken) == std::string::npos )
        {
            return spelling;
        }

        // Let's break apart the scoped name, expand each local part
        // and then recombine the parts into an expanded scoped name.
        StringBuffer msg;
        std::ostringstream result;
        const auto vec = util::splitScopes(spelling);

        for( std::size_t i=0; i<vec.size(); ++i )
        {
            try
            {
                const auto buf = expandOne(vec[i]);
                result << buf;

            }
            catch (const ConfigurationException&)
            {
                checkCondition(false, spelling);
            }

            if (i < vec.size() - 1)
            {
                result << '.';
            }
        }
        return result.str();
    }

    std::string UidIdentifierProcessor::expandOne(const std::string& spelling)
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        checkCondition(hasValidPrefix(spelling), spelling);

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return formatExpanded(std::string(digitsEnd, spelling.cend()));
        }

        checkCondition(hasValidPayload(digitsEnd, spelling.cend()), spelling);

        return formatExpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    std::string UidIdentifierProcessor::unexpand(const char* spelling, StringBuffer& buf) const
    {
        //--------
        // Common case optimizations
        //--------
        if (strchr(spelling, '.') == nullptr)
        {
            const auto result = unexpandOne(spelling);
            buf = result;
            return result;
        }
        if (strstr(spelling, "uid-") == nullptr)
        {
            return spelling;
        }

        //--------
        // Let's break apart the scoped name, unexpand each local part
        // and then recombine the parts into an unexpanded scoped name.
        //--------
        StringBuffer result;
        StringBuffer msg;

        StringVector vec{util::splitScopes(spelling)};
        const int len = vec.size();
        for (int i = 0; i < len; ++i)
        {
            std::string str;
            try
            {
                str = unexpandOne(vec[i]);
                buf = str;
            }
            catch (const ConfigurationException&)
            {
                msg << "'" << spelling << "' is not a legal identifier";
                throw ConfigurationException(msg.str());
            }
            result.append(str);
            if (i < len - 1)
            {
                result.append(".");
            }
        }
        buf = result.str();
        return buf.str().c_str();
    }

    std::string UidIdentifierProcessor::unexpandOne(const std::string& spelling) const
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return spelling;
        }

        return formatUnexpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    bool UidIdentifierProcessor::startsWithUidToken(const std::string& str) const
    {
        return std::equal(m_uidToken.cbegin(), m_uidToken.cend(), str.cbegin());
    }

    bool UidIdentifierProcessor::hasValidPrefix(const std::string& str) const
    {
        return ( str != m_uidToken ) && ( str.at(m_uidToken.size()) != '-' );
    }

    std::string UidIdentifierProcessor::formatExpanded(const std::string& suffix)
    {
        compat::checkAssertion(m_count < 1000 * 1000 * 1000);
        constexpr std::size_t numDigits = 9;

        std::ostringstream ss;
        ss << m_uidToken << std::setw(numDigits) << std::setfill('0') << (m_count++) << "-" << suffix;

        return ss.str();
    }

    std::string UidIdentifierProcessor::formatUnexpanded(const std::string& suffix) const
    {
        return m_uidToken + suffix;
    }

    void UidIdentifierProcessor::checkCondition(bool result, const std::string& input) const
    {
        if( result == false )
        {
            throw ConfigurationException{"'" + input + "' is not a legal identifier"};
        }
    }

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

#include "danek/internal/UidIdentifierProcessor.h"
#include "danek/internal/Util.h"
#include "danek/internal/Compat.h"
#include "danek/ConfigurationException.h"
#include "danek/StringVector.h"
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <string.h>
#include <ctype.h>
#include <stdio.h>

namespace danek
{

    UidIdentifierProcessor::UidIdentifierProcessor() : m_count(0), m_uidToken("uid-")
    {
    }

    //----------------------------------------------------------------------
    // Spelling must be in one of the following forms:
    //      - "foo"                 -->  "foo"
    //      - "uid-<foo>"           -->  "uid-<digits>-<foo>"
    //      - "uid-<digits>-<foo>"  -->  "uid-<new-digits>-<foo>"
    // where "<foo>" does NOT start with a digit or "-"
    //----------------------------------------------------------------------

    std::string UidIdentifierProcessor::expand(const std::string& spelling)
    {
        // Common case optimizations
        if( spelling.find('.') == std::string::npos )
        {
            return expandOne(spelling);
        }

        if( spelling.find(m_uidToken) == std::string::npos )
        {
            return spelling;
        }

        // Let's break apart the scoped name, expand each local part
        // and then recombine the parts into an expanded scoped name.
        std::ostringstream result;
        const auto vec = util::splitScopes(spelling);

        for( std::size_t i=0; i<vec.size(); ++i )
        {
            result << expandOne(vec[i]);

            if (i < vec.size() - 1)
            {
                result << '.';
            }
        }

        return result.str();
    }

    std::string UidIdentifierProcessor::expandOne(const std::string& spelling)
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        checkCondition(hasValidPrefix(spelling), spelling);

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return formatExpanded(std::string(digitsEnd, spelling.cend()));
        }

        checkCondition(hasValidPayload(digitsEnd, spelling.cend()), spelling);

        return formatExpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    std::string UidIdentifierProcessor::unexpand(const char* spelling, StringBuffer& buf) const
    {
        //--------
        // Common case optimizations
        //--------
        if (strchr(spelling, '.') == nullptr)
        {
            const auto result = unexpandOne(spelling);
            buf = result;
            return result;
        }
        if (strstr(spelling, "uid-") == nullptr)
        {
            return spelling;
        }

        //--------
        // Let's break apart the scoped name, unexpand each local part
        // and then recombine the parts into an unexpanded scoped name.
        //--------
        StringBuffer result;
        StringBuffer msg;

        StringVector vec{util::splitScopes(spelling)};
        const int len = vec.size();
        for (int i = 0; i < len; ++i)
        {
            std::string str;
            try
            {
                str = unexpandOne(vec[i]);
                buf = str;
            }
            catch (const ConfigurationException&)
            {
                msg << "'" << spelling << "' is not a legal identifier";
                throw ConfigurationException(msg.str());
            }
            result.append(str);
            if (i < len - 1)
            {
                result.append(".");
            }
        }
        buf = result.str();
        return buf.str().c_str();
    }

    std::string UidIdentifierProcessor::unexpandOne(const std::string& spelling) const
    {
        if( startsWithUidToken(spelling) == false )
        {
            return spelling;
        }

        const auto startPayload = std::next(spelling.cbegin(), m_uidToken.size());
        auto digitsEnd = std::find_if_not(startPayload, spelling.cend(), [](auto v) { return std::isdigit(v); });

        if( digitsEnd == startPayload )
        {
            return spelling;
        }

        return formatUnexpanded(std::string(std::next(digitsEnd), spelling.cend()));
    }

    bool UidIdentifierProcessor::startsWithUidToken(const std::string& str) const
    {
        return std::equal(m_uidToken.cbegin(), m_uidToken.cend(), str.cbegin());
    }

    bool UidIdentifierProcessor::hasValidPrefix(const std::string& str) const
    {
        return ( str != m_uidToken ) && ( str.at(m_uidToken.size()) != '-' );
    }

    std::string UidIdentifierProcessor::formatExpanded(const std::string& suffix)
    {
        compat::checkAssertion(m_count < 1000 * 1000 * 1000);
        constexpr std::size_t numDigits = 9;

        std::ostringstream ss;
        ss << m_uidToken << std::setw(numDigits) << std::setfill('0') << (m_count++) << "-" << suffix;

        return ss.str();
    }

    std::string UidIdentifierProcessor::formatUnexpanded(const std::string& suffix) const
    {
        return m_uidToken + suffix;
    }

    void UidIdentifierProcessor::checkCondition(bool result, const std::string& input) const
    {
        if( result == false )
        {
            throw ConfigurationException{"'" + input + "' is not a legal identifier"};
        }
    }

}
<|endoftext|>