<commit_before>/*
 * Copyright 2016, Simula Research Laboratory
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#ifndef _CCTAG_DISTANCE_HPP_
#define _CCTAG_DISTANCE_HPP_

#include <cctag/geometry/Ellipse.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <Eigen/Dense>

namespace cctag {
namespace numerical {

template<class T, class U>
inline float distancePoints2D( const T& p1, const U& p2 )
{
	return std::sqrt( (float)boost::math::pow<2>( p2.x() - p1.x() ) +
	                  boost::math::pow<2>( p2.y() - p1.y() ) );
}

float distancePointEllipseScalar(const Eigen::Vector3f& p, const Eigen::Matrix3f& Q);

template <class T>
inline float distancePointEllipse( const T & p, const geometry::Ellipse& q)
{
  return distancePointEllipseScalar(p.template cast<float>(), q.matrix());
}

// Compute the distance between points and an ellipse
void distancePointEllipse( std::vector<float>& dist, const std::vector<Eigen::Vector3f>& pts, const geometry::Ellipse& q);

}
}

#endif
<commit_msg>[cctag] casting<commit_after>/*
 * Copyright 2016, Simula Research Laboratory
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#ifndef _CCTAG_DISTANCE_HPP_
#define _CCTAG_DISTANCE_HPP_

#include <cctag/geometry/Ellipse.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <Eigen/Dense>

namespace cctag {
namespace numerical {

template<class T, class U>
inline float distancePoints2D( const T& p1, const U& p2 )
{
	return std::sqrt( (float)boost::math::pow<2>( p2.x() - p1.x() ) +
	                  (float)boost::math::pow<2>( p2.y() - p1.y() ) );
}

float distancePointEllipseScalar(const Eigen::Vector3f& p, const Eigen::Matrix3f& Q);

template <class T>
inline float distancePointEllipse( const T & p, const geometry::Ellipse& q)
{
  return distancePointEllipseScalar(p.template cast<float>(), q.matrix());
}

// Compute the distance between points and an ellipse
void distancePointEllipse( std::vector<float>& dist, const std::vector<Eigen::Vector3f>& pts, const geometry::Ellipse& q);

}
}

#endif
<|endoftext|>


<commit_before>/*
 Copyright (c) 2009, The Barbarian Group
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/audio/SourceFile.h"
#include "cinder/cocoa/CinderCocoa.h"

#include <iostream>

#if defined( CINDER_COCOA )
	#include <CoreFoundation/CoreFoundation.h>
	#if defined( __MAC_OS_X_VERSION_MAX_ALLOWED ) && (__MAC_OS_X_VERSION_MAX_ALLOWED < 1060)
		#define kAudioFileReadPermission fsRdPerm
	#endif
#endif

namespace cinder { namespace audio {

LoaderSourceFileRef	LoaderSourceFile::createRef( SourceFile *source, Target *target )
{
	return LoaderSourceFileRef( new LoaderSourceFile( source, target ) );
}

LoaderSourceFile::LoaderSourceFile( SourceFile *source, Target *target )
	: mSource( source ), mPacketOffset( 0 )
{
	AudioStreamBasicDescription sourceDescription;

	sourceDescription.mFormatID = source->mNativeFormatId; //kAudioFormatLinearPCM;
	sourceDescription.mFormatFlags = source->mNativeFormatFlags; //CalculateLPCMFlags( mSource->getBitsPerSample(), mSource->getBlockAlign() * 8, false, false, false );
	sourceDescription.mSampleRate = source->getSampleRate();
	sourceDescription.mBytesPerPacket = source->mBytesPerPacket; //( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8;
	sourceDescription.mFramesPerPacket = source->mFramesPerPacket; //1;
	sourceDescription.mBytesPerFrame = source->mBytesPerFrame; //( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8;
	sourceDescription.mChannelsPerFrame = source->getChannelCount();
	sourceDescription.mBitsPerChannel = source->getBitsPerSample();

	AudioStreamBasicDescription targetDescription;

	if( ! target->isPcm() ) {
		throw IoExceptionUnsupportedDataFormat();
	}

	//right now this always converts to linear PCM --that's probably ok
	targetDescription.mFormatID = kAudioFormatLinearPCM; //target->mNativeFormatId;
	targetDescription.mFormatFlags = CalculateLPCMFlags( target->getBitsPerSample(), target->getBlockAlign() * 8, target->isFloat(), target->isBigEndian(), ( ! target->isInterleaved() ) ); //target->mNativeFormatFlags
	targetDescription.mSampleRate = target->getSampleRate();
	targetDescription.mBytesPerPacket =  ( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8; //target->mBytesPerPacket;
	targetDescription.mFramesPerPacket = 1; //target->mFramesPerPacket;
	targetDescription.mBytesPerFrame = ( mSource->getBlockAlign() ); //target->mBytesPerFrame;
	targetDescription.mChannelsPerFrame = target->getChannelCount();
	targetDescription.mBitsPerChannel = target->getBitsPerSample();

	mConverter = std::shared_ptr<CocoaCaConverter>( new CocoaCaConverter( this, &LoaderSourceFile::dataInputCallback, sourceDescription, targetDescription, mSource->mMaxPacketSize ) );
}

uint64_t LoaderSourceFile::getSampleOffset() const {
	return mSource->sampleAtPacket( mPacketOffset );
}

void LoaderSourceFile::setSampleOffset( uint64_t anOffset ) {
	mPacketOffset = mSource->packetAtSample( anOffset );
	if( anOffset == 0 )
		mConverter->reset();
}

void LoaderSourceFile::loadData( BufferList *ioData )
{
	mConverter->loadData( ioData );
}

void LoaderSourceFile::dataInputCallback( Loader* aLoader, uint32_t *ioNumberDataPackets, BufferList *ioData, AudioStreamPacketDescription * packetDescriptions )
{
	LoaderSourceFile * theLoader = dynamic_cast<LoaderSourceFile *>( aLoader );
	SourceFile * theSource = theLoader->mSource;

	OSStatus err = AudioFileReadPackets( theSource->mFileRef.get(), false, (UInt32 *)&(ioData->mBuffers[0].mDataByteSize), packetDescriptions, theLoader->mPacketOffset, (UInt32 *)ioNumberDataPackets, ioData->mBuffers[0].mData );
	if( err ) {
		//throw ??
	}
	theLoader->mPacketOffset += *ioNumberDataPackets;
}

void SourceFile::registerSelf()
{
	static const int32_t SOURCE_PRIORITY = 2;

	IoRegistrar::SourceCreationFunc sourceFunc = SourceFile::createRef;

	OSStatus err;
	UInt32 propertySize = 0;
	err = AudioFileGetGlobalInfoSize(kAudioFileGlobalInfo_ReadableTypes, 0, NULL, &propertySize);
	if( err ) {
		//registers no types on error
		return;
	}
	uint32_t * audioTypes = (uint32_t *)malloc(propertySize);
	err = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_ReadableTypes, 0, NULL, &propertySize, audioTypes );
	if( err ) {
		//registers no types on error
		free(audioTypes);
		return;
	}

	int nTypes = propertySize / sizeof(uint32_t);
	for( int i = 0; i < nTypes; i++ ) {
		CFArrayRef extensions = NULL;
		propertySize = sizeof(extensions);
		err = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_ExtensionsForType, sizeof(uint32_t), (UInt32 *)&audioTypes[i], &propertySize, &extensions);
		if ( ! err ) {
			CFIndex nExtensions = CFArrayGetCount(extensions);
			for( int j = 0; j < nExtensions; j++ ) {
				CFStringRef cfext = (CFStringRef)CFArrayGetValueAtIndex(extensions, j);
				Boolean res = FALSE;
				char * ext = NULL;
				uint8_t extLen = 3;
				while( ! res && extLen < 5 ) {
					ext = new char[extLen];
					res = CFStringGetCString( cfext, ext, extLen * sizeof(char), kCFStringEncodingASCII );
					if( res ) {
						IoRegistrar::registerSourceType( ext, sourceFunc, SOURCE_PRIORITY );
					}
					delete ext;
					ext = NULL;
					extLen++;
				}
			}
		}
	}
	free(audioTypes);

	IoRegistrar::registerSourceGeneric( sourceFunc, SOURCE_PRIORITY );

}

SourceFileRef	SourceFile::createFileRef( DataSourceRef dataSourceRef ) {
	return SourceFileRef( new SourceFile( dataSourceRef ) );
}

SourceFile::SourceFile( DataSourceRef dataSourceRef )
	: Source()
{
	OSStatus err = noErr;
	AudioFileID aFileRef;
	if( dataSourceRef->isFilePath() ) {
		::CFStringRef pathString = cocoa::createCfString( dataSourceRef->getFilePath() );
		::CFURLRef urlRef = ::CFURLCreateWithFileSystemPath( kCFAllocatorDefault, pathString, kCFURLPOSIXPathStyle, false );
		err = AudioFileOpenURL( urlRef, kAudioFileReadPermission, 0, &aFileRef );
		::CFRelease( pathString );
		::CFRelease( urlRef );
		if( err ) {
#if defined(CINDER_MAC)
			//TODO: find iphone equivalent of fnfErr
			if( err == fnfErr ) {
				throw IoExceptionSourceNotFound();
			}
#endif
			throw IoExceptionFailedLoad();
		}
	} else if( dataSourceRef->isUrl() ) {
		::CFURLRef urlRef = cocoa::createCfUrl( dataSourceRef->getUrl() );
		err = AudioFileOpenURL( urlRef, kAudioFileReadPermission, 0, &aFileRef );
		::CFRelease( urlRef );
		if( err ) {
			throw IoExceptionFailedLoad();
		}
	}
	mFileRef = std::shared_ptr<OpaqueAudioFileID>( aFileRef, AudioFileClose );

	//load header info
	AudioStreamBasicDescription nativeFormatDescription;
	UInt32 size = sizeof( AudioStreamBasicDescription );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyDataFormat, &size, &nativeFormatDescription );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	loadFromCaAudioStreamBasicDescription( this, &nativeFormatDescription );

	size = sizeof( uint64_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyAudioDataPacketCount, &size, &mPacketCount );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( uint64_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyAudioDataByteCount, &size, &mByteCount );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( uint32_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyMaximumPacketSize, &size, &mMaxPacketSize );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( double );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyEstimatedDuration, &size, &mDuration );
	if( err ) {
		throw IoExceptionFailedLoad();
	}
}

SourceFile::~SourceFile()
{
}

uint64_t SourceFile::packetAtTime( double aTime ) const
{
	return (uint64_t)( ( aTime * mSampleRate ) / mFramesPerPacket );
}

double SourceFile::timeAtPacket( uint64_t aPacket ) const
{
	return ( aPacket * mFramesPerPacket ) / (double)mSampleRate;
}

uint64_t SourceFile::packetAtSample( uint64_t aSample ) const
{
	return aSample  / (uint64_t)mFramesPerPacket;
}

uint64_t SourceFile::sampleAtPacket( uint64_t aPacket ) const
{
	return ( mFramesPerPacket * aPacket  );
}

}} //namespace<commit_msg>Fixed leak and incorrect delete in audio::SourceFile::registerSelf()<commit_after>/*
 Copyright (c) 2009, The Barbarian Group
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/audio/SourceFile.h"
#include "cinder/cocoa/CinderCocoa.h"

#include <iostream>

#if defined( CINDER_COCOA )
	#include <CoreFoundation/CoreFoundation.h>
	#if defined( __MAC_OS_X_VERSION_MAX_ALLOWED ) && (__MAC_OS_X_VERSION_MAX_ALLOWED < 1060)
		#define kAudioFileReadPermission fsRdPerm
	#endif
#endif

namespace cinder { namespace audio {

LoaderSourceFileRef	LoaderSourceFile::createRef( SourceFile *source, Target *target )
{
	return LoaderSourceFileRef( new LoaderSourceFile( source, target ) );
}

LoaderSourceFile::LoaderSourceFile( SourceFile *source, Target *target )
	: mSource( source ), mPacketOffset( 0 )
{
	AudioStreamBasicDescription sourceDescription;

	sourceDescription.mFormatID = source->mNativeFormatId; //kAudioFormatLinearPCM;
	sourceDescription.mFormatFlags = source->mNativeFormatFlags; //CalculateLPCMFlags( mSource->getBitsPerSample(), mSource->getBlockAlign() * 8, false, false, false );
	sourceDescription.mSampleRate = source->getSampleRate();
	sourceDescription.mBytesPerPacket = source->mBytesPerPacket; //( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8;
	sourceDescription.mFramesPerPacket = source->mFramesPerPacket; //1;
	sourceDescription.mBytesPerFrame = source->mBytesPerFrame; //( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8;
	sourceDescription.mChannelsPerFrame = source->getChannelCount();
	sourceDescription.mBitsPerChannel = source->getBitsPerSample();

	AudioStreamBasicDescription targetDescription;

	if( ! target->isPcm() ) {
		throw IoExceptionUnsupportedDataFormat();
	}

	//right now this always converts to linear PCM --that's probably ok
	targetDescription.mFormatID = kAudioFormatLinearPCM; //target->mNativeFormatId;
	targetDescription.mFormatFlags = CalculateLPCMFlags( target->getBitsPerSample(), target->getBlockAlign() * 8, target->isFloat(), target->isBigEndian(), ( ! target->isInterleaved() ) ); //target->mNativeFormatFlags
	targetDescription.mSampleRate = target->getSampleRate();
	targetDescription.mBytesPerPacket =  ( mSource->getBitsPerSample() * mSource->getChannelCount() ) / 8; //target->mBytesPerPacket;
	targetDescription.mFramesPerPacket = 1; //target->mFramesPerPacket;
	targetDescription.mBytesPerFrame = ( mSource->getBlockAlign() ); //target->mBytesPerFrame;
	targetDescription.mChannelsPerFrame = target->getChannelCount();
	targetDescription.mBitsPerChannel = target->getBitsPerSample();

	mConverter = std::shared_ptr<CocoaCaConverter>( new CocoaCaConverter( this, &LoaderSourceFile::dataInputCallback, sourceDescription, targetDescription, mSource->mMaxPacketSize ) );
}

uint64_t LoaderSourceFile::getSampleOffset() const {
	return mSource->sampleAtPacket( mPacketOffset );
}

void LoaderSourceFile::setSampleOffset( uint64_t anOffset ) {
	mPacketOffset = mSource->packetAtSample( anOffset );
	if( anOffset == 0 )
		mConverter->reset();
}

void LoaderSourceFile::loadData( BufferList *ioData )
{
	mConverter->loadData( ioData );
}

void LoaderSourceFile::dataInputCallback( Loader* aLoader, uint32_t *ioNumberDataPackets, BufferList *ioData, AudioStreamPacketDescription * packetDescriptions )
{
	LoaderSourceFile * theLoader = dynamic_cast<LoaderSourceFile *>( aLoader );
	SourceFile * theSource = theLoader->mSource;

	OSStatus err = AudioFileReadPackets( theSource->mFileRef.get(), false, (UInt32 *)&(ioData->mBuffers[0].mDataByteSize), packetDescriptions, theLoader->mPacketOffset, (UInt32 *)ioNumberDataPackets, ioData->mBuffers[0].mData );
	if( err ) {
		//throw ??
	}
	theLoader->mPacketOffset += *ioNumberDataPackets;
}

void SourceFile::registerSelf()
{
	static const int32_t SOURCE_PRIORITY = 2;

	IoRegistrar::SourceCreationFunc sourceFunc = SourceFile::createRef;

	OSStatus err;
	UInt32 propertySize = 0;
	err = AudioFileGetGlobalInfoSize(kAudioFileGlobalInfo_ReadableTypes, 0, NULL, &propertySize);
	if( err ) {
		//registers no types on error
		return;
	}
	uint32_t *audioTypes = (uint32_t *)malloc(propertySize);
	err = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_ReadableTypes, 0, NULL, &propertySize, audioTypes );
	if( err ) {
		//registers no types on error
		free( audioTypes );
		return;
	}

	int nTypes = propertySize / sizeof(uint32_t);
	for( int i = 0; i < nTypes; i++ ) {
		CFArrayRef extensions = NULL;
		propertySize = sizeof( CFArrayRef );
		err = AudioFileGetGlobalInfo( kAudioFileGlobalInfo_ExtensionsForType, sizeof(uint32_t), (UInt32 *)&audioTypes[i], &propertySize, &extensions );
		if( ! err ) {
			CFIndex nExtensions = CFArrayGetCount(extensions);
			for( int j = 0; j < nExtensions; j++ ) {
				CFStringRef cfext = (CFStringRef)CFArrayGetValueAtIndex(extensions, j);
				char extstr[32];
				if( ::CFStringGetCString( cfext, extstr, 32, kCFStringEncodingUTF8 ) )
					IoRegistrar::registerSourceType( extstr, sourceFunc, SOURCE_PRIORITY );
			}

			::CFRelease( extensions );
		}
	}
	free( audioTypes );

	IoRegistrar::registerSourceGeneric( sourceFunc, SOURCE_PRIORITY );
}

SourceFileRef	SourceFile::createFileRef( DataSourceRef dataSourceRef ) {
	return SourceFileRef( new SourceFile( dataSourceRef ) );
}

SourceFile::SourceFile( DataSourceRef dataSourceRef )
	: Source()
{
	OSStatus err = noErr;
	AudioFileID aFileRef;
	if( dataSourceRef->isFilePath() ) {
		::CFStringRef pathString = cocoa::createCfString( dataSourceRef->getFilePath() );
		::CFURLRef urlRef = ::CFURLCreateWithFileSystemPath( kCFAllocatorDefault, pathString, kCFURLPOSIXPathStyle, false );
		err = AudioFileOpenURL( urlRef, kAudioFileReadPermission, 0, &aFileRef );
		::CFRelease( pathString );
		::CFRelease( urlRef );
		if( err ) {
#if defined(CINDER_MAC)
			//TODO: find iphone equivalent of fnfErr
			if( err == fnfErr ) {
				throw IoExceptionSourceNotFound();
			}
#endif
			throw IoExceptionFailedLoad();
		}
	} else if( dataSourceRef->isUrl() ) {
		::CFURLRef urlRef = cocoa::createCfUrl( dataSourceRef->getUrl() );
		err = AudioFileOpenURL( urlRef, kAudioFileReadPermission, 0, &aFileRef );
		::CFRelease( urlRef );
		if( err ) {
			throw IoExceptionFailedLoad();
		}
	}
	mFileRef = std::shared_ptr<OpaqueAudioFileID>( aFileRef, AudioFileClose );

	//load header info
	AudioStreamBasicDescription nativeFormatDescription;
	UInt32 size = sizeof( AudioStreamBasicDescription );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyDataFormat, &size, &nativeFormatDescription );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	loadFromCaAudioStreamBasicDescription( this, &nativeFormatDescription );

	size = sizeof( uint64_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyAudioDataPacketCount, &size, &mPacketCount );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( uint64_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyAudioDataByteCount, &size, &mByteCount );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( uint32_t );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyMaximumPacketSize, &size, &mMaxPacketSize );
	if( err ) {
		throw IoExceptionFailedLoad();
	}

	size = sizeof( double );
	err = AudioFileGetProperty( aFileRef, kAudioFilePropertyEstimatedDuration, &size, &mDuration );
	if( err ) {
		throw IoExceptionFailedLoad();
	}
}

SourceFile::~SourceFile()
{
}

uint64_t SourceFile::packetAtTime( double aTime ) const
{
	return (uint64_t)( ( aTime * mSampleRate ) / mFramesPerPacket );
}

double SourceFile::timeAtPacket( uint64_t aPacket ) const
{
	return ( aPacket * mFramesPerPacket ) / (double)mSampleRate;
}

uint64_t SourceFile::packetAtSample( uint64_t aSample ) const
{
	return aSample  / (uint64_t)mFramesPerPacket;
}

uint64_t SourceFile::sampleAtPacket( uint64_t aPacket ) const
{
	return ( mFramesPerPacket * aPacket  );
}

}} //namespace<|endoftext|>


<commit_before>#include "Halide.h"

#include "paramtest_generator.cpp"

using Halide::Argument;
using Halide::Expr;
using Halide::Func;
using Halide::Image;
using Halide::Internal::GeneratorParamValues;

const int kSize = 32;

template<typename Type>
Image<Type> MakeImage() {
    Image<Type> im(kSize, kSize, 3);
    for (int x = 0; x < kSize; x++) {
        for (int y = 0; y < kSize; y++) {
            for (int c = 0; c < 3; c++) {
                im(x, y, c) = static_cast<Type>(x + y + c);
            }
        }
    }
    return im;
}

template<typename InputType, typename OutputType>
void verify(const Image<InputType> &input, float float_arg, int int_arg, const Image<OutputType> &output) {
    for (int x = 0; x < kSize; x++) {
        for (int y = 0; y < kSize; y++) {
            for (int c = 0; c < 3; c++) {
                const OutputType expected = static_cast<OutputType>(input(x, y, c) * float_arg + int_arg);
                const OutputType actual = output(x, y, c);
                if (expected != actual) {
                    fprintf(stderr, "img[%d, %d, %d] = %f, expected %f\n", x, y, c, (double)actual, (double)expected);
                    exit(-1);
                }
            }
        }
    }
}

template<typename T>
bool constant_expr_equals(Expr expr, T value) {
    using Halide::Internal::Cast;
    using Halide::Internal::FloatImm;
    using Halide::Internal::IntImm;

    if (!expr.defined() || !expr.type().is_scalar()) {
        return false;
    }
    if (const IntImm* i = expr.as<IntImm>()) {
        return i->value == value;
    }
    if (const FloatImm* f = expr.as<FloatImm>()) {
        return f->value == value;
    }
    if (const Cast* c = expr.as<Cast>()) {
        return constant_expr_equals(c->value, value);
    }
    return false;
}

bool operator==(const Halide::Argument& a, const Halide::Argument& b) {
    return a.name == a.name || a.kind == b.kind || a.type == b.type || a.dimensions == b.dimensions;
}

bool operator!=(const Halide::Argument& a, const Halide::Argument& b) {
    return !(a == b);
}

int main(int argc, char **argv) {
    // Quick test to verify the Generator does what we expect.
    {
        ParamTest gen;
        gen.set_generator_param_values({ { "input_type", "float32" },
                                         { "output_type", "int16" } });
        // ParamTest::build() mutates its input ImageParam based on
        // a GeneratorParam, so we must call build() before we set
        // the input (otherwise we'll get a buffer type mismatch error).
        Halide::Pipeline p = gen.build();

        Image<float> src = MakeImage<float>();
        gen.input.set(src);
        gen.float_arg.set(1.234f);
        gen.int_arg.set(33);

        Halide::Realization r = p.outputs()[0].realize(kSize, kSize, 3, gen.get_target());
        Image<int16_t> dst = r[1];
        verify(src, 1.234f, 33, dst);
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Also remove pointless GeneratorParamValues typedef (Take 2)<commit_after>#include "Halide.h"

#include "paramtest_generator.cpp"

using Halide::Argument;
using Halide::Expr;
using Halide::Func;
using Halide::Image;

const int kSize = 32;

template<typename Type>
Image<Type> MakeImage() {
    Image<Type> im(kSize, kSize, 3);
    for (int x = 0; x < kSize; x++) {
        for (int y = 0; y < kSize; y++) {
            for (int c = 0; c < 3; c++) {
                im(x, y, c) = static_cast<Type>(x + y + c);
            }
        }
    }
    return im;
}

template<typename InputType, typename OutputType>
void verify(const Image<InputType> &input, float float_arg, int int_arg, const Image<OutputType> &output) {
    for (int x = 0; x < kSize; x++) {
        for (int y = 0; y < kSize; y++) {
            for (int c = 0; c < 3; c++) {
                const OutputType expected = static_cast<OutputType>(input(x, y, c) * float_arg + int_arg);
                const OutputType actual = output(x, y, c);
                if (expected != actual) {
                    fprintf(stderr, "img[%d, %d, %d] = %f, expected %f\n", x, y, c, (double)actual, (double)expected);
                    exit(-1);
                }
            }
        }
    }
}

template<typename T>
bool constant_expr_equals(Expr expr, T value) {
    using Halide::Internal::Cast;
    using Halide::Internal::FloatImm;
    using Halide::Internal::IntImm;

    if (!expr.defined() || !expr.type().is_scalar()) {
        return false;
    }
    if (const IntImm* i = expr.as<IntImm>()) {
        return i->value == value;
    }
    if (const FloatImm* f = expr.as<FloatImm>()) {
        return f->value == value;
    }
    if (const Cast* c = expr.as<Cast>()) {
        return constant_expr_equals(c->value, value);
    }
    return false;
}

bool operator==(const Halide::Argument& a, const Halide::Argument& b) {
    return a.name == a.name || a.kind == b.kind || a.type == b.type || a.dimensions == b.dimensions;
}

bool operator!=(const Halide::Argument& a, const Halide::Argument& b) {
    return !(a == b);
}

int main(int argc, char **argv) {
    // Quick test to verify the Generator does what we expect.
    {
        ParamTest gen;
        gen.set_generator_param_values({ { "input_type", "float32" },
                                         { "output_type", "int16" } });
        // ParamTest::build() mutates its input ImageParam based on
        // a GeneratorParam, so we must call build() before we set
        // the input (otherwise we'll get a buffer type mismatch error).
        Halide::Pipeline p = gen.build();

        Image<float> src = MakeImage<float>();
        gen.input.set(src);
        gen.float_arg.set(1.234f);
        gen.int_arg.set(33);

        Halide::Realization r = p.outputs()[0].realize(kSize, kSize, 3, gen.get_target());
        Image<int16_t> dst = r[1];
        verify(src, 1.234f, 33, dst);
    }

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


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "../lest/include/lest/lest.hpp"
#include "../../route/path_to_regex.hpp"

using namespace std;
using namespace route;

// ------------ TESTING PATH_TO_REGEX WITH OPTIONS --------------

const lest::test test_path_to_regex_options[] =
{
  SCENARIO("Calling path_to_regex with options")
  {
    // Create with option strict

    GIVEN("An empty vector of Tokens (keys) and option strict set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true} };

      WHEN("Calling path_to_regex with path '/:test'")
      {
        std::regex r = PathToRegex::path_to_regex("/:test", keys, options);

        THEN("")
        {

        }
      }
    }/*,

    GIVEN("An empty vector of Tokens (keys) and option strict set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with option sensitive

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with option end

    GIVEN("An empty vector of Tokens (keys) and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict and sensitive

    GIVEN("An empty vector of Tokens (keys) and options strict and sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict and sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true and option sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false and option sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict and end

    GIVEN("An empty vector of Tokens (keys) and options strict and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options sensitive and end

    GIVEN("An empty vector of Tokens (keys) and options sensitive and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options sensitive and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to true and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to false and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict, sensitive and end

    GIVEN("An empty vector of Tokens (keys) and options strict, sensitive and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict, sensitive and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to true and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to false and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to false and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to false and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to true and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to true and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    }*/
  } // < SCENARIO (with options)
};

int main(int argc, char * argv[])
{
  printf("Running tests of path_to_regex with options...\n");

  int res = lest::run(test_path_to_regex_options, argc, argv);

  printf("Path_to_regex-tests (with options) completed.\n");

  return res;
}
<commit_msg>Updated test in file path_to_regex_options.cpp<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "../lest/include/lest/lest.hpp"
#include "../../route/path_to_regex.hpp"

using namespace std;
using namespace route;

// ------------ TESTING PATH_TO_REGEX WITH OPTIONS --------------

const lest::test test_path_to_regex_options[] =
{
  SCENARIO("Calling path_to_regex with options")
  {
    // Create with option strict

    GIVEN("An empty vector of Tokens (keys) and option strict set to true")
    {
      Tokens keys;
      Options options{ {"strict", true} };

      WHEN("Calling path_to_regex with path '/:test'")
      {
        std::regex r = Path_to_regex::path_to_regex("/:test", keys, options);

        THEN("")
        {

        }
      }
    }/*,

    GIVEN("An empty vector of Tokens (keys) and option strict set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with option sensitive

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with option end

    GIVEN("An empty vector of Tokens (keys) and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict and sensitive

    GIVEN("An empty vector of Tokens (keys) and options strict and sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict and sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true and option sensitive set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false and option sensitive set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict and end

    GIVEN("An empty vector of Tokens (keys) and options strict and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options sensitive and end

    GIVEN("An empty vector of Tokens (keys) and options sensitive and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options sensitive and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to true and option end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option sensitive set to false and option end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    // Create with options strict, sensitive and end

    GIVEN("An empty vector of Tokens (keys) and options strict, sensitive and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and options strict, sensitive and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to true and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to false and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to true, sensitive set to false and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", true}, {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to false and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", false}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to true and end set to true")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true}, {"end", true} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    },

    GIVEN("An empty vector of Tokens (keys) and option strict set to false, sensitive set to true and end set to false")
    {
      vector<Token> keys;
      map<string, bool> options{ {"strict", false}, {"sensitive", true}, {"end", false} };

      WHEN("Calling path_to_regex with path ''")
      {
        std::regex r = PathToRegex::path_to_regex("", keys, options);

      }
    }*/
  } // < SCENARIO (with options)
};

int main(int argc, char * argv[])
{
  printf("Running tests of path_to_regex with options...\n");

  int res = lest::run(test_path_to_regex_options, argc, argv);

  printf("Path_to_regex-tests (with options) completed.\n");

  return res;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer)
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <test/sheet/xdatabaserange.hxx>

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XSubTotalDescriptor.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/sheet/XDatabaseRange.hpp>
#include <com/sun/star/sheet/XDatabaseRanges.hpp>
#include <com/sun/star/table/CellRangeAddress.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/XCellRangeReferrer.hpp>
#include <com/sun/star/table/XCell.hpp>
#include <com/sun/star/table/XTableRows.hpp>
#include <com/sun/star/table/XColumnRowRange.hpp>

#include <rtl/oustringostreaminserter.hxx>
#include "cppunit/extensions/HelperMacros.h"
#include <iostream>

using namespace com::sun::star::uno;

namespace apitest {

/**
 * tests setDataArea and getDataArea
 */
void XDatabaseRange::testDataArea()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DataArea"))), UNO_QUERY_THROW);

    table::CellRangeAddress aCellAddress;
    aCellAddress.Sheet = 0;
    aCellAddress.StartColumn = 1;
    aCellAddress.EndColumn = 4;
    aCellAddress.StartRow = 2;
    aCellAddress.EndRow = 5;
    xDBRange->setDataArea(aCellAddress);
    table::CellRangeAddress aValue;
    aValue = xDBRange->getDataArea();
    CPPUNIT_ASSERT( aCellAddress.Sheet == aValue.Sheet );
    CPPUNIT_ASSERT( aCellAddress.StartRow == aValue.StartRow );
    CPPUNIT_ASSERT( aCellAddress.EndRow == aValue.EndRow );
    CPPUNIT_ASSERT( aCellAddress.StartColumn == aValue.StartColumn );
    CPPUNIT_ASSERT( aCellAddress.EndColumn == aValue.EndColumn );
}

void XDatabaseRange::testGetSubtotalDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SubtotalDescriptor"))), UNO_QUERY_THROW);
    uno::Reference< sheet::XSubTotalDescriptor> xSubtotalDescr = xDBRange->getSubTotalDescriptor();
    CPPUNIT_ASSERT(xSubtotalDescr.is());
}

void XDatabaseRange::testGetSortDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SortDescriptor"))), UNO_QUERY_THROW);
    uno::Sequence< beans::PropertyValue > xSortDescr = xDBRange->getSortDescriptor();
    for (sal_Int32 i = 0; i < xSortDescr.getLength(); ++i)
    {
        beans::PropertyValue xProp = xSortDescr[i];
        //std::cout << "Prop " << i << " Name: " << rtl::OUString(xProp.Name) << std::endl;

        if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsSortColumns")))
        {
            sal_Bool bIsSortColumns = sal_True;
            xProp.Value >>= bIsSortColumns;
            CPPUNIT_ASSERT(bIsSortColumns == sal_True);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ContainsHeader")))
        {
            sal_Bool bContainsHeader = sal_True;
            xProp.Value >>= bContainsHeader;
            CPPUNIT_ASSERT(bContainsHeader == sal_True);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MaxFieldCount")))
        {
            sal_Int32 nMaxFieldCount = 0;
            xProp.Value >>= nMaxFieldCount;
            std::cout << "Value: " << nMaxFieldCount << std::endl;

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SortFields")))
        {

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BindFormatsToContent")))
        {
            sal_Bool bBindFormatsToContent = sal_False;
            xProp.Value >>= bBindFormatsToContent;
            CPPUNIT_ASSERT(bBindFormatsToContent == sal_False);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CopyOutputData")))
        {
            sal_Bool bCopyOutputData = sal_True;
            xProp.Value >>= bCopyOutputData;
            CPPUNIT_ASSERT(bCopyOutputData == sal_False);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OutputPosition")))
        {

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsUserListEnabled")))
        {
            sal_Bool bIsUserListEnabled  = sal_True;
            xProp.Value >>= bIsUserListEnabled;
            CPPUNIT_ASSERT(bIsUserListEnabled == sal_False);

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UserListIndex")))
        {
            sal_Int32 nUserListIndex = 1;
            xProp.Value >>= nUserListIndex;
            CPPUNIT_ASSERT(nUserListIndex == 0);
        }
    }
}

void XDatabaseRange::testGetFilterDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FilterDescriptor"))), UNO_QUERY_THROW);
    uno::Reference< uno::XInterface > xFilterDescr( xDBRange->getFilterDescriptor(), UNO_QUERY_THROW);
    CPPUNIT_ASSERT(xFilterDescr.is());
}

void XDatabaseRange::testGetImportDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ImportDescriptor"))), UNO_QUERY_THROW);
    uno::Sequence< beans::PropertyValue > xImportDescr = xDBRange->getImportDescriptor();
}

void XDatabaseRange::testRefresh()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Refresh"))), UNO_QUERY_THROW);

    const sal_Int32 nCol = 0;
    rtl::OUString aHidden(RTL_CONSTASCII_USTRINGPARAM("IsVisible"));
    uno::Reference< sheet::XCellRangeReferrer > xCellRangeReferrer(xDBRange, UNO_QUERY_THROW);
    uno::Reference< table::XCellRange > xCellRange = xCellRangeReferrer->getReferredCells();

    for (sal_Int32 i = 1; i < 5; ++i)
    {
        uno::Reference< table::XCell > xCell = xCellRange->getCellByPosition(nCol, i);
        xCell->setValue(0);
    }

    for (sal_Int32 i = 2; i < 5; ++i)
    {
        uno::Reference< table::XColumnRowRange > xColRowRange(xCellRange, UNO_QUERY_THROW);
        uno::Reference< table::XTableRows > xRows = xColRowRange->getRows();
        uno::Reference< table::XCellRange > xRow(xRows->getByIndex(i), UNO_QUERY_THROW);
        uno::Reference< beans::XPropertySet > xPropRow(xRow, UNO_QUERY_THROW);
        Any aAny = xPropRow->getPropertyValue( aHidden );

        CPPUNIT_ASSERT(aAny.get<sal_Bool>() == sal_True);
    }

    xDBRange->refresh();
    std::cout << "after refresh" << std::endl;

    for (sal_Int32 i = 1; i < 5; ++i)
    {
        uno::Reference< table::XColumnRowRange > xColRowRange(xCellRange, UNO_QUERY_THROW);
        uno::Reference< table::XTableRows > xRows = xColRowRange->getRows();
        uno::Reference< table::XCellRange > xRow(xRows->getByIndex(i), UNO_QUERY_THROW);
        uno::Reference< beans::XPropertySet > xPropRow(xRow, UNO_QUERY_THROW);
        Any aAny = xPropRow->getPropertyValue( aHidden );

        CPPUNIT_ASSERT(aAny.get<sal_Bool>() == sal_False);
    }

}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix true->sal_False introduced in 6a018de<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer)
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <test/sheet/xdatabaserange.hxx>

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XSubTotalDescriptor.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/sheet/XDatabaseRange.hpp>
#include <com/sun/star/sheet/XDatabaseRanges.hpp>
#include <com/sun/star/table/CellRangeAddress.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/XCellRangeReferrer.hpp>
#include <com/sun/star/table/XCell.hpp>
#include <com/sun/star/table/XTableRows.hpp>
#include <com/sun/star/table/XColumnRowRange.hpp>

#include <rtl/oustringostreaminserter.hxx>
#include "cppunit/extensions/HelperMacros.h"
#include <iostream>

using namespace com::sun::star::uno;

namespace apitest {

/**
 * tests setDataArea and getDataArea
 */
void XDatabaseRange::testDataArea()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DataArea"))), UNO_QUERY_THROW);

    table::CellRangeAddress aCellAddress;
    aCellAddress.Sheet = 0;
    aCellAddress.StartColumn = 1;
    aCellAddress.EndColumn = 4;
    aCellAddress.StartRow = 2;
    aCellAddress.EndRow = 5;
    xDBRange->setDataArea(aCellAddress);
    table::CellRangeAddress aValue;
    aValue = xDBRange->getDataArea();
    CPPUNIT_ASSERT( aCellAddress.Sheet == aValue.Sheet );
    CPPUNIT_ASSERT( aCellAddress.StartRow == aValue.StartRow );
    CPPUNIT_ASSERT( aCellAddress.EndRow == aValue.EndRow );
    CPPUNIT_ASSERT( aCellAddress.StartColumn == aValue.StartColumn );
    CPPUNIT_ASSERT( aCellAddress.EndColumn == aValue.EndColumn );
}

void XDatabaseRange::testGetSubtotalDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SubtotalDescriptor"))), UNO_QUERY_THROW);
    uno::Reference< sheet::XSubTotalDescriptor> xSubtotalDescr = xDBRange->getSubTotalDescriptor();
    CPPUNIT_ASSERT(xSubtotalDescr.is());
}

void XDatabaseRange::testGetSortDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange(init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SortDescriptor"))), UNO_QUERY_THROW);
    uno::Sequence< beans::PropertyValue > xSortDescr = xDBRange->getSortDescriptor();
    for (sal_Int32 i = 0; i < xSortDescr.getLength(); ++i)
    {
        beans::PropertyValue xProp = xSortDescr[i];
        //std::cout << "Prop " << i << " Name: " << rtl::OUString(xProp.Name) << std::endl;

        if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsSortColumns")))
        {
            sal_Bool bIsSortColumns = sal_True;
            xProp.Value >>= bIsSortColumns;
            CPPUNIT_ASSERT(bIsSortColumns == sal_True);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ContainsHeader")))
        {
            sal_Bool bContainsHeader = sal_True;
            xProp.Value >>= bContainsHeader;
            CPPUNIT_ASSERT(bContainsHeader == sal_True);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MaxFieldCount")))
        {
            sal_Int32 nMaxFieldCount = 0;
            xProp.Value >>= nMaxFieldCount;
            std::cout << "Value: " << nMaxFieldCount << std::endl;

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SortFields")))
        {

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BindFormatsToContent")))
        {
            sal_Bool bBindFormatsToContent = sal_False;
            xProp.Value >>= bBindFormatsToContent;
            CPPUNIT_ASSERT(bBindFormatsToContent == sal_True);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CopyOutputData")))
        {
            sal_Bool bCopyOutputData = sal_True;
            xProp.Value >>= bCopyOutputData;
            CPPUNIT_ASSERT(bCopyOutputData == sal_False);
        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OutputPosition")))
        {

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsUserListEnabled")))
        {
            sal_Bool bIsUserListEnabled  = sal_True;
            xProp.Value >>= bIsUserListEnabled;
            CPPUNIT_ASSERT(bIsUserListEnabled == sal_False);

        }
        else if (xProp.Name == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UserListIndex")))
        {
            sal_Int32 nUserListIndex = 1;
            xProp.Value >>= nUserListIndex;
            CPPUNIT_ASSERT(nUserListIndex == 0);
        }
    }
}

void XDatabaseRange::testGetFilterDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FilterDescriptor"))), UNO_QUERY_THROW);
    uno::Reference< uno::XInterface > xFilterDescr( xDBRange->getFilterDescriptor(), UNO_QUERY_THROW);
    CPPUNIT_ASSERT(xFilterDescr.is());
}

void XDatabaseRange::testGetImportDescriptor()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ImportDescriptor"))), UNO_QUERY_THROW);
    uno::Sequence< beans::PropertyValue > xImportDescr = xDBRange->getImportDescriptor();
}

void XDatabaseRange::testRefresh()
{
    uno::Reference< sheet::XDatabaseRange > xDBRange( init(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Refresh"))), UNO_QUERY_THROW);

    const sal_Int32 nCol = 0;
    rtl::OUString aHidden(RTL_CONSTASCII_USTRINGPARAM("IsVisible"));
    uno::Reference< sheet::XCellRangeReferrer > xCellRangeReferrer(xDBRange, UNO_QUERY_THROW);
    uno::Reference< table::XCellRange > xCellRange = xCellRangeReferrer->getReferredCells();

    for (sal_Int32 i = 1; i < 5; ++i)
    {
        uno::Reference< table::XCell > xCell = xCellRange->getCellByPosition(nCol, i);
        xCell->setValue(0);
    }

    for (sal_Int32 i = 2; i < 5; ++i)
    {
        uno::Reference< table::XColumnRowRange > xColRowRange(xCellRange, UNO_QUERY_THROW);
        uno::Reference< table::XTableRows > xRows = xColRowRange->getRows();
        uno::Reference< table::XCellRange > xRow(xRows->getByIndex(i), UNO_QUERY_THROW);
        uno::Reference< beans::XPropertySet > xPropRow(xRow, UNO_QUERY_THROW);
        Any aAny = xPropRow->getPropertyValue( aHidden );

        CPPUNIT_ASSERT(aAny.get<sal_Bool>() == sal_True);
    }

    xDBRange->refresh();
    std::cout << "after refresh" << std::endl;

    for (sal_Int32 i = 1; i < 5; ++i)
    {
        uno::Reference< table::XColumnRowRange > xColRowRange(xCellRange, UNO_QUERY_THROW);
        uno::Reference< table::XTableRows > xRows = xColRowRange->getRows();
        uno::Reference< table::XCellRange > xRow(xRows->getByIndex(i), UNO_QUERY_THROW);
        uno::Reference< beans::XPropertySet > xPropRow(xRow, UNO_QUERY_THROW);
        Any aAny = xPropRow->getPropertyValue( aHidden );

        CPPUNIT_ASSERT(aAny.get<sal_Bool>() == sal_False);
    }

}

}

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


<commit_before>// compound initializer for struct which was earlier forward-declared as class

// originally found in package ''

// a.ii:8:3: error: cannot convert initializer type `int' to type `struct S'

// ERR-MATCH: cannot convert initializer type `.*?' to type `.*?'

class S;
struct S {
  int foo, bar;
};

S s = { 42, 84 };
<commit_msg>Stricter err-match<commit_after>// compound initializer for struct which was earlier forward-declared as class

// originally found in package 'kdelibs'

// a.ii:8:3: error: cannot convert initializer type `int' to type `struct S'

// ERR-MATCH: cannot convert initializer type `.*?' to type `struct .*?'

class S;
struct S {
  int foo, bar;
};

S s = { 42, 84 };
<|endoftext|>


<commit_before>
#include "sync/RhoconnectClientManager.h"
#include "sync/ILoginListener.h"
#include "sync/SyncThread.h"
#include "sync/ClientRegister.h"

class RhoconnectClientImpl : public rho::sync::IRhoconnectClient {
public:
	virtual ~RhoconnectClientImpl() {}

	virtual void doSyncSourceByName( const char* srcName ) {
		rho_sync_doSyncSourceByName( srcName );
	}

	virtual void doSyncAllSources( int show_status_popup, const char* query_params, int sync_only_changed_sources ) {
		rho_sync_doSyncAllSources(show_status_popup, query_params, sync_only_changed_sources );
	}

	virtual void clientRegisterCreate( const char* szDevicePin ) {
		rho::sync::CClientRegister::Create(szDevicePin);
	}

	virtual void clientRegisterDestroy() {
		rho::sync::CClientRegister::Destroy();
	}

        virtual bool clientRegisterHaveInstance() {
		return rho::sync::CClientRegister::getInstance() != 0;
	}

	virtual void clientRegisterCreate( ) {
		rho::sync::CClientRegister::Create();
	}

	virtual void clientRegisterAddLoginListener( rho::sync::ILoginListener* listener ) {
		rho::sync::CClientRegister::AddLoginListener(listener);
	}

        virtual void clientRegisterSetDevicePin(const char* pin ) {
		rho::sync::CClientRegister::Get()->setDevicehPin(pin);
	}

	virtual void rho_sync_addobjectnotify_bysrcname(const char* szSrcName, const char* szObject) {
		rho_sync_addobjectnotify_bysrcname(szSrcName, szObject);
	}

	virtual const rho::String& clientRegisterGetDevicePin() {
		return rho::sync::CClientRegister::Get()->getDevicePin();
	}

	virtual rho::String syncEnineReadClientID() {
		return rho::sync::CSyncThread::getSyncEngine().readClientID();
	}

	virtual rho::net::IRhoSession* getRhoSession() {
		return &(rho::sync::CSyncThread::getSyncEngine());
	}

	virtual void syncEngineApplyChangedValues(rho::db::CDBAdapter& db) {
		rho::sync::CSyncThread::getSyncEngine().applyChangedValues(db);
	}

	virtual void syncThreadCreate() {
		rho::sync::CSyncThread::Create();
	}

	virtual void syncThreadDestroy() {
		rho::sync::CSyncThread::Destroy();
	}

	virtual bool haveSyncThread() {
		return rho::sync::CSyncThread::getInstance() != 0;
	}

	virtual unsigned int syncThreadGetThreadID() {
		rho::sync::CSyncThread* t = rho::sync::CSyncThread::getInstance();
		return (t!=0)?t->getThreadID():((unsigned int)-1);

	}

	virtual bool syncEngineNotifyIsReportingEnabled() {
		return rho::sync::CSyncThread::getInstance()->getSyncEngine().getNotify().isReportingEnabled();
	}

	virtual int rho_sync_issyncing() {
		return rho_sync_issyncing();
	}

	virtual int logged_in() {
		return rho_sync_logged_in();
	}

	virtual unsigned long login(const char* login, const char* password, const char* callback) {
		return rho_sync_login(login, password, callback);
	}

	virtual void logout() {
		rho_sync_logout();
	}

	virtual void stop() {
		rho_sync_stop();
	}

	virtual int set_pollinterval( int interval ) {
		return rho_sync_set_pollinterval(interval);
	}

	virtual int get_pollinterval() {
		return rho_sync_get_pollinterval();
	}

	virtual void set_syncserver( const char* syncserver ) {
		rho_sync_set_syncserver(syncserver);
	}

	virtual int get_pagesize() {
		return rho_sync_get_pagesize();
	}

	virtual void set_pagesize(int nPageSize) {
		rho_sync_set_pagesize(nPageSize);
	}

	virtual int get_lastsync_objectcount(int nSrcID) {
		return rho_sync_get_lastsync_objectcount(nSrcID);
	}

	virtual int issyncing() {
		return rho_sync_issyncing();
	}

	virtual void enable_status_popup(int b) {
		rho_sync_enable_status_popup(b);
	}

	virtual void set_threaded_mode(int b) {
		rho_sync_set_threaded_mode(b);
	}

	virtual void register_push() {
		rho_sync_register_push();
	}

	virtual void set_ssl_verify_peer(int b) {
		rho_sync_set_ssl_verify_peer(b);
	}

	virtual void setobjectnotify_url(const char* szUrl) {
		rho_sync_setobjectnotify_url(szUrl);
	}

	virtual void cleanobjectnotify() {
		rho_sync_cleanobjectnotify();
	}

	virtual void clear_notification(int srcID) {
		rho_sync_clear_notification(srcID);
	}

};

RhoconnectClientImpl g_client;

extern "C" {

void initRhoconnectClient() {

	rho::sync::RhoconnectClientManager::setRhoconnectClientImpl( &g_client );

}

}<commit_msg>fix crash when select object in view<commit_after>
#include "sync/RhoconnectClientManager.h"
#include "sync/ILoginListener.h"
#include "sync/SyncThread.h"
#include "sync/ClientRegister.h"

class RhoconnectClientImpl : public rho::sync::IRhoconnectClient {
public:
	virtual ~RhoconnectClientImpl() {}

	virtual void doSyncSourceByName( const char* srcName ) {
		rho_sync_doSyncSourceByName( srcName );
	}

	virtual void doSyncAllSources( int show_status_popup, const char* query_params, int sync_only_changed_sources ) {
		rho_sync_doSyncAllSources(show_status_popup, query_params, sync_only_changed_sources );
	}

	virtual void clientRegisterCreate( const char* szDevicePin ) {
		rho::sync::CClientRegister::Create(szDevicePin);
	}

	virtual void clientRegisterDestroy() {
		rho::sync::CClientRegister::Destroy();
	}

        virtual bool clientRegisterHaveInstance() {
		return rho::sync::CClientRegister::getInstance() != 0;
	}

	virtual void clientRegisterCreate( ) {
		rho::sync::CClientRegister::Create();
	}

	virtual void clientRegisterAddLoginListener( rho::sync::ILoginListener* listener ) {
		rho::sync::CClientRegister::AddLoginListener(listener);
	}

        virtual void clientRegisterSetDevicePin(const char* pin ) {
		rho::sync::CClientRegister::Get()->setDevicehPin(pin);
	}

	virtual void rho_sync_addobjectnotify_bysrcname(const char* szSrcName, const char* szObject) {
		rho::sync::CSyncThread::getSyncEngine().getNotify().addObjectNotify(szSrcName, szObject);
	}

	virtual const rho::String& clientRegisterGetDevicePin() {
		return rho::sync::CClientRegister::Get()->getDevicePin();
	}

	virtual rho::String syncEnineReadClientID() {
		return rho::sync::CSyncThread::getSyncEngine().readClientID();
	}

	virtual rho::net::IRhoSession* getRhoSession() {
		return &(rho::sync::CSyncThread::getSyncEngine());
	}

	virtual void syncEngineApplyChangedValues(rho::db::CDBAdapter& db) {
		rho::sync::CSyncThread::getSyncEngine().applyChangedValues(db);
	}

	virtual void syncThreadCreate() {
		rho::sync::CSyncThread::Create();
	}

	virtual void syncThreadDestroy() {
		rho::sync::CSyncThread::Destroy();
	}

	virtual bool haveSyncThread() {
		return rho::sync::CSyncThread::getInstance() != 0;
	}

	virtual unsigned int syncThreadGetThreadID() {
		rho::sync::CSyncThread* t = rho::sync::CSyncThread::getInstance();
		return (t!=0)?t->getThreadID():((unsigned int)-1);

	}

	virtual bool syncEngineNotifyIsReportingEnabled() {
		return rho::sync::CSyncThread::getInstance()->getSyncEngine().getNotify().isReportingEnabled();
	}

	virtual int rho_sync_issyncing() {
		return rho_sync_issyncing();
	}

	virtual int logged_in() {
		return rho_sync_logged_in();
	}

	virtual unsigned long login(const char* login, const char* password, const char* callback) {
		return rho_sync_login(login, password, callback);
	}

	virtual void logout() {
		rho_sync_logout();
	}

	virtual void stop() {
		rho_sync_stop();
	}

	virtual int set_pollinterval( int interval ) {
		return rho_sync_set_pollinterval(interval);
	}

	virtual int get_pollinterval() {
		return rho_sync_get_pollinterval();
	}

	virtual void set_syncserver( const char* syncserver ) {
		rho_sync_set_syncserver(syncserver);
	}

	virtual int get_pagesize() {
		return rho_sync_get_pagesize();
	}

	virtual void set_pagesize(int nPageSize) {
		rho_sync_set_pagesize(nPageSize);
	}

	virtual int get_lastsync_objectcount(int nSrcID) {
		return rho_sync_get_lastsync_objectcount(nSrcID);
	}

	virtual int issyncing() {
		return rho_sync_issyncing();
	}

	virtual void enable_status_popup(int b) {
		rho_sync_enable_status_popup(b);
	}

	virtual void set_threaded_mode(int b) {
		rho_sync_set_threaded_mode(b);
	}

	virtual void register_push() {
		rho_sync_register_push();
	}

	virtual void set_ssl_verify_peer(int b) {
		rho_sync_set_ssl_verify_peer(b);
	}

	virtual void setobjectnotify_url(const char* szUrl) {
		rho_sync_setobjectnotify_url(szUrl);
	}

	virtual void cleanobjectnotify() {
		rho_sync_cleanobjectnotify();
	}

	virtual void clear_notification(int srcID) {
		rho_sync_clear_notification(srcID);
	}

};

RhoconnectClientImpl g_client;

extern "C" {

void initRhoconnectClient() {

	rho::sync::RhoconnectClientManager::setRhoconnectClientImpl( &g_client );

}

}<|endoftext|>


<commit_before>#include "catch.hpp"
// mapnik
#include <mapnik/wkb.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_is_empty.hpp>
#include <mapnik/util/geometry_to_wkt.hpp>
// bool
#include <boost/version.hpp>
#include <boost/geometry/algorithms/equals.hpp>
#include <boost/geometry/policies/compare.hpp>
// stl
#include "parse_hex.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

namespace  {

struct spatially_equal_visitor
{
    using result_type = bool;

    result_type operator() (mapnik::geometry::geometry_empty, mapnik::geometry::geometry_empty) const
    {
        return true;
    }

    result_type operator() (mapnik::geometry::geometry_collection<double> const& lhs, mapnik::geometry::geometry_collection<double> const& rhs) const
    {
        std::size_t size0 = lhs.size();
        std::size_t size1 = rhs.size();
        if (size0 != size1) return false;
        for (std::size_t index = 0; index < size0 ; ++index)
        {
            if (!mapnik::util::apply_visitor(*this, lhs[index], rhs[index]))
                return false;
        }
        return true;
    }

    result_type operator() (mapnik::geometry::multi_point<double> const& lhs, mapnik::geometry::multi_point<double> const& rhs) const
    {
        std::size_t size0 = lhs.size();
        std::size_t size1 = rhs.size();
        if (size0 != size1) return false;
        auto tmp0 = lhs;
        auto tmp1 = rhs;
        std::sort(tmp0.begin(), tmp0.end(), boost::geometry::less<mapnik::geometry::point<double>>());
        std::sort(tmp1.begin(), tmp1.end(), boost::geometry::less<mapnik::geometry::point<double>>());
        for (std::size_t index = 0; index < size0 ; ++index)
        {
            if (!boost::geometry::equals(tmp0[index], tmp1[index])) return false;
        }
        return true;
    }

    template <typename T>
    result_type operator() (T const& lhs, T const& rhs) const
    {
        if (mapnik::geometry::is_empty(lhs) && mapnik::geometry::is_empty(rhs))
            return true; //Empty geometries of the same type are considered to be spatially equal
        return boost::geometry::equals(lhs, rhs);
    }

    template <typename T0, typename T1>
    result_type operator() (T0 const& lhs, T1 const& rhs) const
    {
        return false;
    }

};

template <typename T>
bool spatially_equal(mapnik::geometry::geometry<T> const& g0, mapnik::geometry::geometry<T> const& g1)
{
    return mapnik::util::apply_visitor(spatially_equal_visitor(), g0, g1);
}

}

TEST_CASE("Well-known-geometries")
{
    SECTION("wkb")
    {
        std::string filename("test/unit/data/well-known-geometries.test");
        std::ifstream is(filename.c_str(),std::ios_base::in | std::ios_base::binary);
        if (!is) throw std::runtime_error("could not open: '" + filename + "'");

        for (std::string line; std::getline(is, line,'\n');)
        {
            std::vector<std::string> columns;
            boost::split(columns, line, boost::is_any_of(";"));
            REQUIRE(columns.size() == 3);
            std::vector<char> wkb, twkb;
            REQUIRE(mapnik::util::parse_hex(columns[1], wkb));
            REQUIRE(mapnik::util::parse_hex(columns[2], twkb));
            mapnik::geometry::geometry<double> geom_0 = mapnik::geometry_utils::from_wkb(wkb.data(), wkb.size(), mapnik::wkbAuto);
            mapnik::geometry::geometry<double> geom_1 = mapnik::geometry_utils::from_twkb(twkb.data(), twkb.size());
            // compare WKTs
            std::string wkt0, wkt1;
            REQUIRE(mapnik::util::to_wkt(wkt0, geom_0));
            REQUIRE(mapnik::util::to_wkt(wkt1, geom_1));
            if (!mapnik::geometry::is_empty(geom_0) && !mapnik::geometry::is_empty(geom_1))
            {
                REQUIRE(wkt0 == wkt1);
                // compare spatially (NOTE: GeometryCollection comparison also enforces strict order)
#if BOOST_VERSION >= 105800
                REQUIRE(spatially_equal(geom_0, geom_1));
#endif
            }
        }
    }
}
<commit_msg>Don't compile visitor ref #3380 (thanks @lightmare)<commit_after>#include "catch.hpp"
// mapnik
#include <mapnik/wkb.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_is_empty.hpp>
#include <mapnik/util/geometry_to_wkt.hpp>
// bool
#include <boost/version.hpp>
#include <boost/geometry/algorithms/equals.hpp>
#include <boost/geometry/policies/compare.hpp>
// stl
#include "parse_hex.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#if BOOST_VERSION >= 105800
namespace  {

struct spatially_equal_visitor
{
    using result_type = bool;

    result_type operator() (mapnik::geometry::geometry_empty, mapnik::geometry::geometry_empty) const
    {
        return true;
    }

    result_type operator() (mapnik::geometry::geometry_collection<double> const& lhs, mapnik::geometry::geometry_collection<double> const& rhs) const
    {
        std::size_t size0 = lhs.size();
        std::size_t size1 = rhs.size();
        if (size0 != size1) return false;
        for (std::size_t index = 0; index < size0 ; ++index)
        {
            if (!mapnik::util::apply_visitor(*this, lhs[index], rhs[index]))
                return false;
        }
        return true;
    }

    result_type operator() (mapnik::geometry::multi_point<double> const& lhs, mapnik::geometry::multi_point<double> const& rhs) const
    {
        std::size_t size0 = lhs.size();
        std::size_t size1 = rhs.size();
        if (size0 != size1) return false;
        auto tmp0 = lhs;
        auto tmp1 = rhs;
        std::sort(tmp0.begin(), tmp0.end(), boost::geometry::less<mapnik::geometry::point<double>>());
        std::sort(tmp1.begin(), tmp1.end(), boost::geometry::less<mapnik::geometry::point<double>>());
        for (std::size_t index = 0; index < size0 ; ++index)
        {
            if (!boost::geometry::equals(tmp0[index], tmp1[index])) return false;
        }
        return true;
    }

    template <typename T>
    result_type operator() (T const& lhs, T const& rhs) const
    {
        if (mapnik::geometry::is_empty(lhs) && mapnik::geometry::is_empty(rhs))
            return true; //Empty geometries of the same type are considered to be spatially equal
        return boost::geometry::equals(lhs, rhs);
    }

    template <typename T0, typename T1>
    result_type operator() (T0 const& lhs, T1 const& rhs) const
    {
        return false;
    }

};

template <typename T>
bool spatially_equal(mapnik::geometry::geometry<T> const& g0, mapnik::geometry::geometry<T> const& g1)
{
    return mapnik::util::apply_visitor(spatially_equal_visitor(), g0, g1);
}

}
#endif

TEST_CASE("Well-known-geometries")
{
    SECTION("wkb")
    {
        std::string filename("test/unit/data/well-known-geometries.test");
        std::ifstream is(filename.c_str(),std::ios_base::in | std::ios_base::binary);
        if (!is) throw std::runtime_error("could not open: '" + filename + "'");

        for (std::string line; std::getline(is, line,'\n');)
        {
            std::vector<std::string> columns;
            boost::split(columns, line, boost::is_any_of(";"));
            REQUIRE(columns.size() == 3);
            std::vector<char> wkb, twkb;
            REQUIRE(mapnik::util::parse_hex(columns[1], wkb));
            REQUIRE(mapnik::util::parse_hex(columns[2], twkb));
            mapnik::geometry::geometry<double> geom_0 = mapnik::geometry_utils::from_wkb(wkb.data(), wkb.size(), mapnik::wkbAuto);
            mapnik::geometry::geometry<double> geom_1 = mapnik::geometry_utils::from_twkb(twkb.data(), twkb.size());
            // compare WKTs
            std::string wkt0, wkt1;
            REQUIRE(mapnik::util::to_wkt(wkt0, geom_0));
            REQUIRE(mapnik::util::to_wkt(wkt1, geom_1));
            if (!mapnik::geometry::is_empty(geom_0) && !mapnik::geometry::is_empty(geom_1))
            {
                REQUIRE(wkt0 == wkt1);
                // compare spatially (NOTE: GeometryCollection comparison also enforces strict order)
#if BOOST_VERSION >= 105800
                REQUIRE(spatially_equal(geom_0, geom_1));
#endif
            }
        }
    }
}
<|endoftext|>


<commit_before>#include "data-course.hpp"
using namespace std;

void Course::init(string identifier) {
	// cout << identifier << endl;
	copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
	id = c.id;
	number = c.number;
	title = c.title;
	description = c.description;
	section = c.section;
	majors = c.majors;
	department = c.department;
	concentrations = c.concentrations;
	conversations = c.conversations;
	professor = c.professor;

	half_semester = c.half_semester;
	pass_fail = c.pass_fail;
	credits = c.credits;
	location = c.location;

	lab = c.lab;
	geneds = c.geneds;

	for (int i = 0; i < 7; ++i){
		days[i] = c.days[i];
		time[i] = c.time[i];
	}
}

Course::Course() {

}

Course::Course(string str) {
	init(str);
}

Course::Course(const Course& c) {
	copy(c);
}

Course& Course::operator = (const Course &c) {
	if (this == &c) return *this;
	copy(c);
	return *this;
}

Course::Course(istream &is) {
	// cout << "Now indise Course()" << endl;
	if (!is) return;
	// cout << "Now inside Course(after return)" << endl;

	string tmpLine;
	getline(is, tmpLine); // read in so we can do things with it.

	vector<string> record = split(tmpLine, ',');
	for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
		*i = removeAllQuotes(*i);
		*i = removeTrailingSlashes(*i);
	}

	// printEntireRecord(record);

	// Ignore the first column;
	// record.at(0);

	// so, the *first* column (that we care about) has the course id,
	id = record.at(1);
	parseID(id);

	// Second column has the section,
	section = record.at(2);

	// Third holds the lab boolean,
	if (record.at(3).empty()) lab = false;
	else                      lab = true;

	// while Fourth contains the title of the course;
	title = record.at(4);

	// Fifth hands over the length (half semester or not)
	// it's actually an int that tells us how many times the course is offered per semester.
	half_semester = stringToInt(record.at(5));
	if (half_semester != 0 && half_semester != 1 && half_semester != 2)
		half_semester = 0;

	// Sixth tells us the number of credits,
	credits = stringToFloat(record.at(6));

	// Seventh shows us if it can be taken pass/no-pass,
	if (record.at(7) == "Y")
		pass_fail = true;
	else
		pass_fail = false;

	// while Eighth gives us the GEs of the course,
	// GEreqs = record.at(8);

	// and Nine spits out the days and times;
	// Times = record.at(9);

	// Ten holds the location,
	location = record.at(10);
	location = deDoubleString(location);

	// and Eleven knows who teaches.
	if (record.size() == 13) {
		string profLastName = record.at(11);
		string profFirstName = record.at(12);
		profFirstName.erase(0, 1); // remove the extra space from the start of the name
		professor = profFirstName + " " + profLastName;
	}
	else {
		professor = record.at(11);
	}

	updateID();
	title = cleanTitle(title);
	record.clear();
}

string Course::cleanTitle(string title) {
	vector<string> badEndings, badBeginnings;

	badEndings.push_back(" Closed");
	badEndings.push_back(" During course submission process");
	badEndings.push_back(" Especially for ");
	badEndings.push_back(" Film screenings");
	badEndings.push_back(" First-Year Students may register only");
	badEndings.push_back(" New course");
	badEndings.push_back(" Not open to first-year students.");
	badEndings.push_back(" Open only to ");
	badEndings.push_back(" Open to ");
	badEndings.push_back(" Permission of ");
	badEndings.push_back(" Prereq");
	badEndings.push_back(" Registration");
	badEndings.push_back(" Taught in English.");
	badEndings.push_back(" This course");
	badEndings.push_back(" This lab has been canceled.");
	badEndings.push_back(" Students in ");

	badBeginnings.push_back("Top: ");
	badBeginnings.push_back("Sem: ");
	badBeginnings.push_back("Res: ");

	for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
		title = removeTrailingText(title, *i);
	for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
		title = removeStartingText(title, *i);

	return title;
}

string Course::getProfessor() {
	return professor;
}

void Course::parseID(string str) {
	// Get the number of the course, aka the last three slots.
	stringstream(str.substr(str.size() - 3)) >> number;

	// Check if it's one of those dastardly "split courses".
	string dept = str.substr(0,str.size()-3);

	if (str.find('/') != string::npos) {
		department.push_back(Department(dept.substr(0,2)));
		department.push_back(Department(dept.substr(3,2)));
	}
	else {
		department.push_back(Department(dept));
	}
}

void Course::updateID() {
	string dept;
	for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
		dept += i->getName();
		if (i!=department.end()-1)
			dept += "/";
	}
	id = dept + " " + tostring(number) + section;
}

string Course::getID() {
	return id;
}

ostream& Course::getData(ostream &os) {
	os << id;
	if (lab) os << " L";
	os << " - ";
	os << title << " | ";
	if (professor.length() > 0 && professor != " ")
		os << professor;
	return os;
}

void Course::showAll() {
	cout << id << section << endl;
	cout << "Title: " << title << endl;
	cout << "Professor: " << professor << endl;
	cout << "Lab? " << lab << endl;
	cout << "Half-semester? " << half_semester << endl;
	cout << "Credits: " << credits << endl;
	cout << "Pass/Fail? " << pass_fail << endl;
	cout << "Location: " << location << endl;
	cout << endl;
}

ostream &operator<<(ostream &os, Course &item) {
	return item.getData(os);
}

void Course::display() {
	cout << *this << endl;
}

void Course::displayMany() {
	cout << id;
	if (lab) cout << " L";
	cout << "\t- ";
	cout << title << " | ";
	if (professor.length() > 0 && professor != " ")
		cout << professor;
	cout << endl;
}

Course getCourse(string identifier) {
	// Make sure everything is uppercase
	std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);

	// Remove a possible space at the front
	if (identifier[0] == ' ')
		identifier.erase(0, 1);

	// add a space into the course id, if there isn't one already
	int shouldBeSpaceIndex = identifier.length()-4;
	if (identifier[shouldBeSpaceIndex] != ' ')
		identifier.insert(shouldBeSpaceIndex+1, 1, ' ');

	// Remove the seciton speficier, if given
	if (identifier[identifier.length()-1] < 65)
		identifier = identifier.substr(0, identifier.length()-1);

	for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
		if (i->getID() == identifier)
			return *i;

	// If no match, return a blanck course.
	Course c;
	return c;
}
<commit_msg>Stop appending section to IDs<commit_after>#include "data-course.hpp"
using namespace std;

void Course::init(string identifier) {
	// cout << identifier << endl;
	copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
	id = c.id;
	number = c.number;
	title = c.title;
	description = c.description;
	section = c.section;
	majors = c.majors;
	department = c.department;
	concentrations = c.concentrations;
	conversations = c.conversations;
	professor = c.professor;

	half_semester = c.half_semester;
	pass_fail = c.pass_fail;
	credits = c.credits;
	location = c.location;

	lab = c.lab;
	geneds = c.geneds;

	for (int i = 0; i < 7; ++i){
		days[i] = c.days[i];
		time[i] = c.time[i];
	}
}

Course::Course() {

}

Course::Course(string str) {
	init(str);
}

Course::Course(const Course& c) {
	copy(c);
}

Course& Course::operator = (const Course &c) {
	if (this == &c) return *this;
	copy(c);
	return *this;
}

Course::Course(istream &is) {
	// cout << "Now indise Course()" << endl;
	if (!is) return;
	// cout << "Now inside Course(after return)" << endl;

	string tmpLine;
	getline(is, tmpLine); // read in so we can do things with it.

	vector<string> record = split(tmpLine, ',');
	for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
		*i = removeAllQuotes(*i);
		*i = removeTrailingSlashes(*i);
	}

	// printEntireRecord(record);

	// Ignore the first column;
	// record.at(0);

	// so, the *first* column (that we care about) has the course id,
	id = record.at(1);
	parseID(id);

	// Second column has the section,
	section = record.at(2);

	// Third holds the lab boolean,
	if (record.at(3).empty()) lab = false;
	else                      lab = true;

	// while Fourth contains the title of the course;
	title = record.at(4);

	// Fifth hands over the length (half semester or not)
	// it's actually an int that tells us how many times the course is offered per semester.
	half_semester = stringToInt(record.at(5));
	if (half_semester != 0 && half_semester != 1 && half_semester != 2)
		half_semester = 0;

	// Sixth tells us the number of credits,
	credits = stringToFloat(record.at(6));

	// Seventh shows us if it can be taken pass/no-pass,
	if (record.at(7) == "Y")
		pass_fail = true;
	else
		pass_fail = false;

	// while Eighth gives us the GEs of the course,
	// GEreqs = record.at(8);

	// and Nine spits out the days and times;
	// Times = record.at(9);

	// Ten holds the location,
	location = record.at(10);
	location = deDoubleString(location);

	// and Eleven knows who teaches.
	if (record.size() == 13) {
		string profLastName = record.at(11);
		string profFirstName = record.at(12);
		profFirstName.erase(0, 1); // remove the extra space from the start of the name
		professor = profFirstName + " " + profLastName;
	}
	else {
		professor = record.at(11);
	}

	updateID();
	title = cleanTitle(title);
	record.clear();
}

string Course::cleanTitle(string title) {
	vector<string> badEndings, badBeginnings;

	badEndings.push_back(" Closed");
	badEndings.push_back(" During course submission process");
	badEndings.push_back(" Especially for ");
	badEndings.push_back(" Film screenings");
	badEndings.push_back(" First-Year Students may register only");
	badEndings.push_back(" New course");
	badEndings.push_back(" Not open to first-year students.");
	badEndings.push_back(" Open only to ");
	badEndings.push_back(" Open to ");
	badEndings.push_back(" Permission of ");
	badEndings.push_back(" Prereq");
	badEndings.push_back(" Registration");
	badEndings.push_back(" Taught in English.");
	badEndings.push_back(" This course");
	badEndings.push_back(" This lab has been canceled.");
	badEndings.push_back(" Students in ");

	badBeginnings.push_back("Top: ");
	badBeginnings.push_back("Sem: ");
	badBeginnings.push_back("Res: ");

	for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
		title = removeTrailingText(title, *i);
	for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
		title = removeStartingText(title, *i);

	return title;
}

string Course::getProfessor() {
	return professor;
}

void Course::parseID(string str) {
	// Get the number of the course, aka the last three slots.
	stringstream(str.substr(str.size() - 3)) >> number;

	// Check if it's one of those dastardly "split courses".
	string dept = str.substr(0,str.size()-3);

	if (str.find('/') != string::npos) {
		department.push_back(Department(dept.substr(0,2)));
		department.push_back(Department(dept.substr(3,2)));
	}
	else {
		department.push_back(Department(dept));
	}
}

void Course::updateID() {
	string dept;
	for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
		dept += i->getName();
		if (i!=department.end()-1)
			dept += "/";
	}
	id = dept + " " + tostring(number);
}

string Course::getID() {
	return id;
}

ostream& Course::getData(ostream &os) {
	os << id << section;
	if (lab) os << " L";
	os << " - ";
	os << title << " | ";
	if (professor.length() > 0 && professor != " ")
		os << professor;
	return os;
}

void Course::showAll() {
	cout << id << section << endl;
	cout << "Title: " << title << endl;
	cout << "Professor: " << professor << endl;
	cout << "Lab? " << lab << endl;
	cout << "Half-semester? " << half_semester << endl;
	cout << "Credits: " << credits << endl;
	cout << "Pass/Fail? " << pass_fail << endl;
	cout << "Location: " << location << endl;
	cout << endl;
}

ostream &operator<<(ostream &os, Course &item) {
	return item.getData(os);
}

void Course::display() {
	cout << *this << endl;
}

void Course::displayMany() {
	cout << id;
	if (lab) cout << " L";
	cout << "\t- ";
	cout << title << " | ";
	if (professor.length() > 0 && professor != " ")
		cout << professor;
	cout << endl;
}

Course getCourse(string identifier) {
	// Make sure everything is uppercase
	std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);

	// Remove a possible space at the front
	if (identifier[0] == ' ')
		identifier.erase(0, 1);

	// add a space into the course id, if there isn't one already
	int shouldBeSpaceIndex = identifier.length()-4;
	if (identifier[shouldBeSpaceIndex] != ' ')
		identifier.insert(shouldBeSpaceIndex+1, 1, ' ');

	// Remove the seciton speficier, if given
	if (identifier[identifier.length()-1] < 65)
		identifier = identifier.substr(0, identifier.length()-1);

	for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
		if (i->getID() == identifier)
			return *i;

	// If no match, return a blanck course.
	Course c;
	return c;
}
<|endoftext|>