text:
/*
 Copyright (c) 2012, The Cinder Project, All rights reserved.
 Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 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/app/App.h"
#include "cinder/app/Renderer.h"
#include "cinder/Camera.h"
#include "cinder/Utilities.h"
#include "cinder/Timeline.h"
#include "cinder/Thread.h"

#if defined( CINDER_COCOA )
	#if defined( CINDER_MAC )
		#import "cinder/app/CinderView.h"
		#import <Cocoa/Cocoa.h>
	#endif
	#include "cinder/cocoa/CinderCocoa.h"
#elif defined( CINDER_WINRT )
	#include "cinder/app/AppImplWinRT.h"
	#include <thread>
	#include <filesystem>
#elif defined( CINDER_MSW )
	#include "cinder/msw/OutputDebugStringStream.h"
	#include "cinder/app/AppImplMsw.h"
#endif

#if !defined ( CINDER_WINRT )
#define BOOST_REGEX_NO_LIB
#include <boost/asio.hpp>
#endif

using namespace std;

namespace cinder { namespace app {

#if defined( CINDER_COCOA )
	void*	App::sAutoReleasePool = 0;
#endif

// Static instance of App, effectively a singleton
App*	App::sInstance;
static std::thread::id	sPrimaryThreadId = std::this_thread::get_id();

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::Settings
App::Settings::Settings()
{
	mShouldQuit = false;
	mPowerManagement = false;
	mFrameRateEnabled = true;
	mFrameRate = 60.0f;
#if defined( CINDER_COCOA_TOUCH )
	mEnableHighDensityDisplay = true;
	mEnableMultiTouch = true;
#else
	mEnableHighDensityDisplay = false;
	mEnableMultiTouch = false;
#endif
}

void App::Settings::disableFrameRate()
{
	mFrameRateEnabled = false;
}

void App::Settings::setFrameRate( float aFrameRate )
{
	mFrameRate = aFrameRate;
}

void App::Settings::enablePowerManagement( bool aPowerManagement )
{
	mPowerManagement = aPowerManagement;
}

void App::Settings::prepareWindow( const Window::Format &format )
{
	mWindowFormats.push_back( format );
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App::App
App::App()
	: mFrameCount( 0 ), mAverageFps( 0 ), mFpsSampleInterval( 1 ), mTimer( true ), mTimeline( Timeline::create() )
{
	mFpsLastSampleFrame = 0;
	mFpsLastSampleTime = 0;
	mAssetDirectoriesInitialized = false;

#if !defined( CINDER_WINRT )
	mIo = shared_ptr<boost::asio::io_service>( new boost::asio::io_service() );
	mIoWork = shared_ptr<boost::asio::io_service::work>( new boost::asio::io_service::work( *mIo ) );
#endif

	// due to an issue with boost::filesystem's static initialization on Windows,
	// it's necessary to create a fs::path here in case of secondary threads doing the same thing simultaneously
#if (defined( CINDER_MSW ) || defined ( CINDER_WINRT ))
	fs::path dummyPath( "dummy" );
#endif
}

App::~App()
{
#if !defined( CINDER_WINRT )
	mIo->stop();
#endif
}

void App::privateSetup__()
{
	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	setup();
}

void App::privateUpdate__()
{
	mFrameCount++;

#if !defined( CINDER_WINRT )
	// service boost::asio::io_service
	mIo->poll();
#endif

	mSignalUpdate();

	update();

	mTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );

	double now = mTimer.getSeconds();
	if( now > mFpsLastSampleTime + mFpsSampleInterval ) {
		//calculate average Fps over sample interval
		uint32_t framesPassed = mFrameCount - mFpsLastSampleFrame;
		mAverageFps = (float)(framesPassed / (now - mFpsLastSampleTime));

		mFpsLastSampleTime = now;
		mFpsLastSampleFrame = mFrameCount;
	}
}

void App::emitShutdown()
{
	mSignalShutdown();
	shutdown();
}

#if ! defined( CINDER_WINRT )
void App::emitWillResignActive()
{
	mSignalWillResignActive();
}

void App::emitDidBecomeActive()
{
	mSignalDidBecomeActive();
}
#endif

DataSourceRef App::loadResource( const string &macPath, int mswID, const string &mswType )
{
#if defined( CINDER_COCOA )
	return loadResource( macPath );
#elif defined( CINDER_WINRT )
	return DataSourceBuffer::create( AppImplWinRT::loadResource( mswID, mswType ), macPath );
#else
	return DataSourceBuffer::create( AppImplMsw::loadResource( mswID, mswType ), macPath );
#endif
}

#if defined( CINDER_COCOA )
DataSourceRef App::loadResource( const string &macPath )
{
	fs::path resourcePath = App::get()->getResourcePath( macPath );
	if( resourcePath.empty() )
		throw ResourceLoadExc( macPath );
	else
		return DataSourcePath::create( resourcePath );
}
#elif defined( CINDER_MSW )

DataSourceRef App::loadResource( int mswID, const string &mswType )
{
	return DataSourceBuffer::create( AppImplMsw::loadResource( mswID, mswType ) );
}

#endif

void App::prepareAssetLoading()
{
	if( ! mAssetDirectoriesInitialized ) {
		fs::path appPath = getAppPath();

		// if this is Mac OS or iOS, search inside the bundle's resources, and then the bundle's root
#if defined( CINDER_COCOA )
		if( fs::exists( getResourcePath() / "assets" ) && fs::is_directory( getResourcePath() / "assets" ) ) {
			mAssetDirectories.push_back( getResourcePath() / "assets" );
			mAssetDirectoriesInitialized = true;
			return;
		}
		else {
			fs::path appAssetPath = getAppPath() / "assets/";
 #if TARGET_IPHONE_SIMULATOR // for some reason is_directory fails under the simulator
			if( fs::exists( appAssetPath ) /*&& fs::is_directory( appAssetPath )*/ ) {
 #else
			if( fs::exists( appAssetPath ) && fs::is_directory( appAssetPath ) ) {
 #endif
				mAssetDirectories.push_back( appAssetPath );
				mAssetDirectoriesInitialized = true;
				return;
			}
		}
#endif

#if defined( CINDER_WINRT )
		mAssetDirectories.push_back( appPath );
		fs::path curPath = appPath;
		fs::path curAssetPath = curPath / fs::path( "Assets" );
		mAssetDirectories.push_back( curAssetPath );
#else
		// first search the local directory, then its parent, up to 5 levels up
		int parentCt = 0;
		for( fs::path curPath = appPath;
			curPath.has_parent_path() || ( curPath == appPath ); //check at least the app path, even if it has no parent directory
			curPath = curPath.parent_path(), ++parentCt )
		{
			if( parentCt >= 5 )
				break;

			const fs::path curAssetPath = curPath / "assets";
			if( fs::exists( curAssetPath ) && fs::is_directory( curAssetPath ) ) {
				mAssetDirectories.push_back( curAssetPath );
				break;
			}
		}
#endif

		mAssetDirectoriesInitialized = true;
	}
}

// locate the asset at 'relativePath'
fs::path App::findAssetPath( const fs::path &relativePath )
{
	prepareAssetLoading();
	for( vector<fs::path>::const_iterator assetDirIt = mAssetDirectories.begin(); assetDirIt != mAssetDirectories.end(); ++assetDirIt ) {
		if( fs::exists( *assetDirIt / relativePath ) )
			return ( *assetDirIt / relativePath );
	}

	// empty implies failure
	return fs::path();
}

DataSourceRef App::loadAsset( const fs::path &relativePath )
{
	fs::path assetPath = findAssetPath( relativePath );
	if( ! assetPath.empty() )
		return DataSourcePath::create( assetPath.string() );
	else
		throw AssetLoadExc( relativePath );
}

fs::path App::getAssetPath( const fs::path &relativePath )
{
	return findAssetPath( relativePath );
}

void App::addAssetDirectory( const fs::path &dirPath )
{

	mAssetDirectories.push_back( dirPath );
}

#if defined( CINDER_COCOA )
NSBundle* App::getBundle() const
{
	return [NSBundle mainBundle];
}

fs::path App::getResourcePath( const fs::path &rsrcRelativePath )
{
	fs::path path = rsrcRelativePath.parent_path();
	fs::path fileName = rsrcRelativePath.filename();

	if( fileName.empty() )
		return string();

	NSString *pathNS = 0;
	if( ( ! path.empty() ) && ( path != rsrcRelativePath ) )
		pathNS = [NSString stringWithUTF8String:path.c_str()];

	NSString *resultPath = [App::get()->getBundle() pathForResource:[NSString stringWithUTF8String:fileName.c_str()] ofType:nil inDirectory:pathNS];
	if( ! resultPath )
		return string();

	return fs::path([resultPath cStringUsingEncoding:NSUTF8StringEncoding]);
}

fs::path App::getResourcePath()
{
	NSString *resultPath = [App::get()->getBundle() resourcePath];

	return fs::path([resultPath cStringUsingEncoding:NSUTF8StringEncoding]);
}

#endif

#if defined CINDER_WINRT

void App::getOpenFilePath( const fs::path &initialPath, std::vector<std::string> extensions, std::function<void (fs::path)> f)
{
	AppImplWinRT::getOpenFilePath( initialPath, extensions, f );
}
#else
fs::path App::getOpenFilePath( const fs::path &initialPath, vector<string> extensions )
{
#if defined( CINDER_MAC )
	bool wasFullScreen = isFullScreen();
	setFullScreen( false );

	NSOpenPanel *cinderOpen = [NSOpenPanel openPanel];
	[cinderOpen setCanChooseFiles:YES];
	[cinderOpen setCanChooseDirectories:NO];
	[cinderOpen setAllowsMultipleSelection:NO];

	if( ! extensions.empty() ) {
		NSMutableArray *typesArray = [NSMutableArray arrayWithCapacity:extensions.size()];
		for( vector<string>::const_iterator extIt = extensions.begin(); extIt != extensions.end(); ++extIt )
			[typesArray addObject:[NSString stringWithUTF8String:extIt->c_str()]];
		[cinderOpen setAllowedFileTypes:typesArray];
	}

	if( ! initialPath.empty() )
		[cinderOpen setDirectoryURL:[NSURL fileURLWithPath:[[NSString stringWithUTF8String:initialPath.c_str()] stringByExpandingTildeInPath]]];

	NSInteger resultCode = [cinderOpen runModal];

	setFullScreen( wasFullScreen );
	restoreWindowContext();

	if( resultCode == NSFileHandlingPanelOKButton ) {
		NSString *result = [[[cinderOpen URLs] objectAtIndex:0] path];
		return fs::path( [result UTF8String] );
	}
	else
		return fs::path();
#elif defined( CINDER_MSW )
	return AppImplMsw::getOpenFilePath( initialPath, extensions );
#else
	return fs::path();
#endif
}
#endif

#if defined CINDER_WINRT

void App::getFolderPath( const fs::path &initialPath,  std::vector<std::string> extensions, std::function<void (fs::path)> f)
{
	AppImplWinRT::getFolderPath( initialPath, extensions, f );
}
#else
fs::path App::getFolderPath( const fs::path &initialPath )
{
#if defined( CINDER_MAC )
	bool wasFullScreen = isFullScreen();
	setFullScreen(false);

	NSOpenPanel *cinderOpen = [NSOpenPanel openPanel];
	[cinderOpen setCanChooseFiles:NO];
	[cinderOpen setCanChooseDirectories:YES];
	[cinderOpen setAllowsMultipleSelection:NO];

	if( ! initialPath.empty() )
		[cinderOpen setDirectoryURL:[NSURL fileURLWithPath:[[NSString stringWithUTF8String:initialPath.c_str()] stringByExpandingTildeInPath]]];

	NSInteger resultCode = [cinderOpen runModal];

	setFullScreen(wasFullScreen);
	restoreWindowContext();

	if( resultCode == NSFileHandlingPanelOKButton ) {
		NSString *result = [[[cinderOpen URLs] objectAtIndex:0] path];
		return fs::path([result UTF8String]);
	}
	else
		return fs::path();
#elif defined( CINDER_MSW )
	return AppImplMsw::getFolderPath( initialPath );
#else
	return fs::path();
#endif
}
#endif

#if defined ( CINDER_WINRT )

void App::getSaveFilePath( const fs::path &initialPath, std::vector<std::string> extensions, std::function<void (fs::path)> f)
{
	AppImplWinRT::getSaveFilePath( initialPath, extensions, f );
}
#else
fs::path App::getSaveFilePath( const fs::path &initialPath, vector<string> extensions )
{
#if defined( CINDER_MAC )
	bool wasFullScreen = isFullScreen();
	setFullScreen( false );

	NSSavePanel *cinderSave = [NSSavePanel savePanel];

	NSMutableArray *typesArray = nil;
	if( ! extensions.empty() ) {
		typesArray = [NSMutableArray arrayWithCapacity:extensions.size()];
		for( vector<string>::const_iterator extIt = extensions.begin(); extIt != extensions.end(); ++extIt )
			[typesArray addObject:[NSString stringWithUTF8String:extIt->c_str()]];
		[cinderSave setAllowedFileTypes:typesArray];
	}

	if( ! initialPath.empty() ) {
		NSString *directory, *file = nil;
		directory = [[NSString stringWithUTF8String:initialPath.c_str()] stringByExpandingTildeInPath];
		BOOL isDir;
		if( [[NSFileManager defaultManager] fileExistsAtPath:directory isDirectory:&isDir] ) {
			if( ! isDir ) { // a file exists at this path, so directory is its parent
				file = [directory lastPathComponent];
				directory = [directory stringByDeletingLastPathComponent];
			}
		}
		else {
			file = [directory lastPathComponent];
			directory = [directory stringByDeletingLastPathComponent];
		}

		[cinderSave setDirectoryURL:[NSURL fileURLWithPath:directory]];
		if( file )
			[cinderSave setNameFieldStringValue:file];
	}

	NSInteger resultCode = [cinderSave runModal];

	setFullScreen( wasFullScreen );
	restoreWindowContext();

	if( resultCode == NSFileHandlingPanelOKButton ) {
		return fs::path( [[[cinderSave URL] path] UTF8String] );
	}
	else
		return fs::path();
#elif defined( CINDER_MSW )
	return AppImplMsw::getSaveFilePath( initialPath, extensions );
#else
	return fs::path();
#endif
}
#endif

std::ostream& App::console()
{
#if defined( CINDER_COCOA )
	return std::cout;
#else
	if( ! mOutputStream )
		mOutputStream = shared_ptr<cinder::msw::dostream>( new cinder::msw::dostream );
	return *mOutputStream;
#endif
}

bool App::isPrimaryThread()
{
	return std::this_thread::get_id() == sPrimaryThreadId;
}

#if !defined( CINDER_WINRT )
void App::dispatchAsync( const std::function<void()> &fn )
{
	io_service().post( fn );
}
#else
void App::dispatchAsync( const std::function<void()> &fn )
{
	std::async(fn);
}

#endif

Surface	App::copyWindowSurface()
{
	return getWindow()->getRenderer()->copyWindowSurface( getWindow()->toPixels( getWindow()->getBounds() ) );
}

Surface	App::copyWindowSurface( const Area &area )
{
	Area clippedArea = area.getClipBy( getWindowBounds() );
	return getWindow()->getRenderer()->copyWindowSurface( clippedArea );
}

void App::restoreWindowContext()
{
#if defined( CINDER_MAC )
	getWindow()->getRenderer()->makeCurrentContext();
#endif
}

RendererRef App::findSharedRenderer( RendererRef searchRenderer ) const
{
	if( ! searchRenderer )
		return RendererRef();

	for( size_t winIdx = 0; winIdx < getNumWindows(); ++winIdx ) {
		RendererRef thisRenderer = getWindowIndex( winIdx )->getRenderer();
		if( thisRenderer && (typeid( *thisRenderer ) == typeid(*searchRenderer)) )
			return getWindowIndex( winIdx )->getRenderer();
	}

	return RendererRef(); // didn't find one
}

// These are called by application instantiation macros
void App::prepareLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

void App::executeLaunch( App *app, RendererRef defaultRenderer, const char *title, int argc, char * const argv[] )
{
	sInstance = app;
	app->mDefaultRenderer = defaultRenderer;
	app->launch( title, argc, argv );
}

void App::cleanupLaunch()
{
#if defined( CINDER_COCOA )
    sAutoReleasePool = [[NSAutoreleasePool alloc] init];
#endif
}

Vec2i App::getMousePos()
{
#if defined( CINDER_MAC )
	NSPoint loc = [NSEvent mouseLocation];
	return Vec2i( loc.x, cinder::Display::getMainDisplay()->getHeight() - loc.y );
#elif defined( CINDER_MSW )
	POINT point;
	::GetCursorPos( &point );
	return Vec2i( point.x, point.y );
#else
	return Vec2i( -1, -1 );
#endif
}

#if defined( CINDER_COCOA )
ResourceLoadExc::ResourceLoadExc( const string &macPath )
{
	sprintf( mMessage, "Failed to load resource: %s", macPath.c_str() );
}

#elif defined( CINDER_MSW )

ResourceLoadExc::ResourceLoadExc( int mswID, const string &mswType )
{
	sprintf( mMessage, "Failed to load resource: #%d type: %s", mswID, mswType.c_str() );
}

ResourceLoadExc::ResourceLoadExc( const string &macPath, int mswID, const string &mswType )
{
	sprintf( mMessage, "Failed to load resource: #%d type: %s Mac path: %s", mswID, mswType.c_str(), macPath.c_str() );
}
#endif // defined( CINDER_MSW )

AssetLoadExc::AssetLoadExc( const fs::path &relativePath )
{
#if defined( CINDER_WINRT )
	strncpy_s( mMessage, relativePath.string().c_str(), sizeof(mMessage) );
#else
	strncpy( mMessage, relativePath.string().c_str(), sizeof(mMessage) );
#endif
}

} } // namespace cinder::app

max_stars_repo_name: timmb/HarmonicMotion

max_issues_repo_name: timmb/HarmonicMotion

max_forks_repo_name: timmb/HarmonicMotion


text:
#pragma once

/**
 * @file
 * @brief path functions
 */

#include <boost/config.hpp>

#include <xul/std/strings.hpp>
#include <xul/std/tstring.hpp>
#include <xul/data/tchar.hpp>

#if defined(XUL_RUN_TEST)
#include <xul/util/test_case.hpp>
#endif

#include <boost/noncopyable.hpp>

#include <utility>
#include <string>
#include <sstream>
#include <locale>
#include <assert.h>

namespace xul {

const char XUL_PATH_BACKSLASH = '\\';
const char XUL_PATH_SLASH = '/';

template <typename StringT>
class windows_path_traits
{
public:
    typedef StringT string_type;
    typedef typename StringT::value_type char_type;
    typedef typename StringT::traits_type char_traits_type;

    static char_type colon()
    {
        return char_traits_type::to_char_type(':');
    }

    static char_type slash()
    {
        return char_traits_type::to_char_type(XUL_PATH_SLASH);
    }

    static char_type backslash()
    {
        return char_traits_type::to_char_type(XUL_PATH_BACKSLASH);
    }

    static char_type separator()
    {
        return backslash();
    }
    static char_type extension_separator()
    {
        return char_traits_type::to_char_type('.');
    }

    static bool is_separator(char_type ch)
    {
        return slash() == ch || backslash() == ch;
    }

    static bool is_absolute(const string_type& path)
    {
        if ( path.empty() )
            return false;
        if ( is_separator( path[0] ) )
        {
            return true;
        }
        if ( path.size() < 2 )
            return false;
        if ( ( colon() == path[1] ) && isalpha(path[0]) )
        {
            if ( path.size() < 3 )
                return false;
            return is_separator( path[2] );
        }
        return false;
    }
};

template <typename StringT>
class posix_path_traits
{
public:
    typedef StringT string_type;
    typedef typename StringT::value_type char_type;
    typedef typename StringT::traits_type char_traits_type;

    static char_type slash()
    {
        return char_traits_type::to_char_type(XUL_PATH_SLASH);
    }

    static char_type separator()
    {
        return slash();
    }
    static char_type extension_separator()
    {
        return char_traits_type::to_char_type('.');
    }

    static bool is_separator(char_type ch)
    {
        return slash() == ch;
    }

    static bool is_absolute(const string_type& path)
    {
        return ( false == path.empty() ) && is_separator( path[0] );
    }
};

template <typename TraitsT>
class basic_paths
{
public:
    typedef TraitsT traits_type;
    typedef typename TraitsT::string_type string_type;
    typedef typename TraitsT::char_type char_type;
    typedef typename TraitsT::char_traits_type char_traits_type;

    typedef std::pair<string_type, string_type> string_pair_type;

    static string_type combine(const string_type& dir, const string_type& filename)
    {
        return join(dir, filename);
    }
    static string_type join(const string_type& dir, const string_type& filename)
    {
        if (dir.empty())
            return filename;
        string_type newDir = add_trailing_separator(dir);
        return newDir + filename;
    }

    static string_type join(const std::vector<string_type>& parts)
    {
        std::basic_ostringstream<typename traits_type::char_type> oss;
        bool lastPartHasTrailingSep = true;
        for (size_t index = 0; index < parts.size(); ++index)
        {
            if (false == lastPartHasTrailingSep)
            {
                oss << traits_type::separator();
            }
            oss << parts[index];
            lastPartHasTrailingSep = has_trailing_separator(parts[index]);
        }
        return oss.str();
    }

    static string_pair_type split_filename(const string_type& path)
    {
        if (path.empty())
        {
            return std::make_pair( string_type(), string_type() );
        }
        assert( path.size() >= 1 );
        int pos = path.size() - 1;
        for ( ;; )
        {
            if ( traits_type::is_separator( path[pos] ) )
            {
                if (0 == pos)
                {
                    return std::make_pair(path.substr(0, pos + 1), path.substr(pos + 1));
                }
                return std::make_pair(path.substr(0, pos), path.substr(pos + 1));
            }
            if ( pos <= 0 )
            {
                break;
            }
            --pos;
        }
        return std::make_pair( string_type(), path );
    }

    static string_pair_type split_extension(const string_type& path)
    {
        if (path.empty())
        {
            return string_pair_type( string_type(), string_type() );
        }
        assert( path.size() >= 1 );
        int pos = path.size() - 1;
        for ( ;; )
        {
            if ( traits_type::extension_separator() == path[pos] )
            {
                return strings::split_at( path, pos );
            }
            if ( traits_type::is_separator( path[pos] ) )
            {
                break;
            }
            if ( 0 == pos )
            {
                break;
            }
            --pos;
        }
        return std::make_pair( path, string_type() );
    }

    static void split(const string_type& path, std::vector<string_type>& parts, bool ignore_empty = false)
    {
        parts.clear();
        int startPos = 0;
        for (size_t pos = 0; pos < path.size(); ++pos)
        {
            if ( traits_type::is_separator( path[pos] ) )
            {
                std::string part;
                if (0 == startPos)
                {
                    part = path.substr(startPos, pos + 1 - startPos);
                }
                else
                {
                    part = path.substr(startPos, pos - startPos);
                }
                if (!ignore_empty || !part.empty())
                    parts.push_back(part);
                startPos = pos + 1;
            }
        }
        parts.push_back(path.substr(startPos));
    }

    static string_type get_directory(const string_type& path)
    {
        return remove_trailing_separator( split_filename(path).first );
    }

    static string_type remove_filename(const string_type& path)
    {
        return split_filename(path).first;
    }

    static string_type get_filename(const string_type& path)
    {
        return split_filename(path).second;
    }

    static string_type remove_extension(const string_type& path)
    {
        return split_extension(path).first;
    }

    static string_type get_extension(const string_type& path)
    {
        string_pair_type res = split_extension(path);
        return res.second;
    }

    static string_type get_basename(const string_type& path)
    {
        return remove_extension(get_filename(path));
    }

    static bool has_extension(const string_type& path)
    {
        return false == get_extension(path).empty();
    }

    static string_type replace_directory(const string_type& path, const string_type& newDir)
    {
        string_type filename = get_filename(path);
        return join(newDir, filename);
    }

    static string_type replace_filename(const string_type& path, const string_type& newFilename)
    {
        string_type dir = get_directory(path);
        return join(dir, newFilename);
    }

    static string_type replace_extension(const string_type& path, const string_type& newExt)
    {
        string_type pathWithoutExt = remove_extension(path);
        return pathWithoutExt + newExt;
    }

    static string_type replace_basename(const string_type& path, const string_type& newBasename)
    {
        string_pair_type dirs = split_filename(path);
        string_pair_type exts = split_extension(dirs.second);
        return join(dirs.first, newBasename + traits_type::extension_separator() + exts.second);
    }

    static bool is_absolute(const string_type& path)
    {
        return traits_type::is_absolute( path );
    }

    static bool has_trailing_separator(const string_type& path)
    {
        if (path.empty())
            return false;
        return traits_type::is_separator( path[path.size() - 1] );
    }

    static string_type add_trailing_separator(const string_type& path)
    {
        if (has_trailing_separator(path))
            return path;
        string_type res = path + traits_type::separator();
        assert( has_trailing_separator( res ) );
        return res;
    }

    static string_type remove_trailing_separator(const string_type& path)
    {
        if ( false == has_trailing_separator(path) )
            return path;
        if ( path.size() == 1 )
            return path;
        assert ( false == path.empty() );
        string_type res = path.substr(0, path.size() - 1);
        assert( false == has_trailing_separator( res ) );
        return res;
    }

};

typedef basic_paths<windows_path_traits<std::string> > windows_paths;
typedef basic_paths<windows_path_traits<std::wstring> > windows_wpaths;
typedef basic_paths<posix_path_traits<std::string> > posix_paths;
typedef basic_paths<posix_path_traits<std::wstring> > posix_wpaths;
typedef posix_paths url_paths;
typedef posix_wpaths url_wpaths;

#if defined(BOOST_WINDOWS)
typedef windows_path_traits<std::string> default_path_traits;
typedef windows_path_traits<std::wstring> default_wpath_traits;
#else
typedef posix_path_traits<std::string> default_path_traits;
typedef posix_path_traits<std::wstring> default_wpath_traits;
#endif

typedef basic_paths<default_path_traits> paths;
typedef basic_paths<default_wpath_traits> wpaths;

#ifdef XUL_RUN_TEST

class paths_test_case : public xul::test_case
{
public:
    static std::pair<std::string, std::string> make_string_pair(const std::string& x, const std::string& y)
    {
        return std::make_pair(x, y);
    }
    virtual void do_run()
    {
        assert(paths::split_filename("") == make_string_pair("", ""));
        assert(paths::split_filename("/") == make_string_pair("/", ""));
        assert(paths::split_filename("abc/c.txt") == make_string_pair("abc", "c.txt"));
        assert(paths::split_filename("abc/") == make_string_pair("abc", ""));
        assert(paths::split_extension("abc/c.txt") == make_string_pair("abc/c", ".txt"));
        assert(paths::get_basename("abc/cde.txt") == "cde");
        assert(paths::get_directory("abc/cde.txt") == "abc");
        assert(paths::get_filename("abc/cde.txt") == "cde.txt");
        assert(windows_paths::get_directory("abc\\cde.txt") == "abc");
        assert(windows_paths::get_basename("abc\\cde.txt\\") == "");
        assert(windows_paths::get_directory("abc\\cde.txt\\") == "abc\\cde.txt");
        assert(windows_paths::get_filename("abc\\cde.txt\\") == "");
        assert(paths::replace_extension("abc.txt", "") == "abc");
    }
};

#endif

}

ext: hpp

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul


text:
/*
==============================================================================
KratosStructuralApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).

Copyright 2007
Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
janosch.stascheit@rub.de
nagel@sd.rub.de
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
- Ruhr-University Bochum, Institute for Structural Mechanics, Germany

Permission is hereby granted, free  of charge, to any person obtaining
a  copy  of this  software  and  associated  documentation files  (the
"Software"), to  deal in  the Software without  restriction, including
without limitation  the rights to  use, copy, modify,  merge, publish,
distribute,  sublicense and/or  sell copies  of the  Software,  and to
permit persons to whom the Software  is furnished to do so, subject to
the following condition:

Distribution of this code for  any  commercial purpose  is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.

The  above  copyright  notice  and  this permission  notice  shall  be
included in all copies or substantial portions of the Software.

THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT  SHALL THE AUTHORS OR COPYRIGHT HOLDERS  BE LIABLE FOR ANY
CLAIM, DAMAGES OR  OTHER LIABILITY, WHETHER IN AN  ACTION OF CONTRACT,
TORT  OR OTHERWISE, ARISING  FROM, OUT  OF OR  IN CONNECTION  WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

//
//   Project Name:        Kratos
//   Last Modified by:    $Author: hurga $
//   Date:                $Date: 2009-02-02 14:03:23 $
//   Revision:            $Revision: 1.5 $
//
//

#if !defined(KRATOS_ADD_CONSTITUTIVE_LAWS_TO_PYTHON_H_INCLUDED )
#define  KRATOS_ADD_CONSTITUTIVE_LAWS_TO_PYTHON_H_INCLUDED

// System includes
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

// External includes
#include "boost/smart_ptr.hpp"

// Project includes
#include "custom_python/add_constitutive_laws_to_python.h"
#include "includes/define.h"
#include "includes/constitutive_law.h"
#include "constitutive_laws/viscoplastic_3d.h"
#include "constitutive_laws/clay_and_sand_model.h"
#include "constitutive_laws/casm.h"
#include "constitutive_laws/modified_barcelona_basic_model.h"
#include "constitutive_laws/freezing_soil_elastoplastic_model.h"
//#include "constitutive_laws/freezing_soil_elastoviscoplastic_model.h"
#include "includes/node.h"
#include "includes/variables.h"
#include "includes/mesh.h"
#include "includes/element.h"
#include "includes/condition.h"
#include "includes/properties.h"
#include "python/add_mesh_to_python.h"
#include "python/pointer_vector_set_python_interface.h"
#include "python/variable_indexing_python.h"

namespace Kratos
{

    namespace Python
    {

        using namespace boost::python;

        typedef ConstitutiveLaw ConstitutiveLawBaseType;
        typedef Mesh<Node<3>, Properties, Element, Condition> MeshType;
        typedef Properties::Pointer PropertiesPointer;

        typedef std::vector<ConstitutiveLaw::Pointer> MaterialsContainer;
        typedef ConstitutiveLaw::Pointer  ConstitutiveLawPointer;

        void  AddConstitutiveLawsToPython()
        {
            class_< Viscoplastic3D, bases< ConstitutiveLawBaseType >, boost::noncopyable >
            ( "Viscoplastic3D",
              init<>() )
            ;
            class_< ClayAndSandModel, bases< ConstitutiveLawBaseType >, boost::noncopyable >
            ( "ClayAndSandModel",
              init<>() )
            ;
            class_< CASM, bases< ConstitutiveLawBaseType >, boost::noncopyable >
            ( "CASM",
              init<>() )
            ;
            class_< ModifiedBarcelonaBasicModel, bases< ConstitutiveLawBaseType >, boost::noncopyable >
            ( "ModifiedBarcelonaBasicModel",
              init<>() )
            ;
            class_< FreezingSoilElastoplasticModel, bases< ConstitutiveLawBaseType >, boost::noncopyable >
            ( "FreezingSoilElastoplasticModel",
              init<>() )
            ;
 //           class_< FreezingSoilElastoviscoplasticModel, bases< ConstitutiveLawBaseType >, boost::noncopyable >
   //         ( "FreezingSoilElastoviscoplasticModel",
     //         init<>() )
       //     ;
        }
    }  // namespace Python.
}  // namespace Kratos.
#endif // KRATOS_ADD_CONSTITUTIVE_LAWS_TO_PYTHON_H_INCLUDED defined

ext: cpp


text:
//              Copyright Toru Niina 2018.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE or copy at
//          https://www.boost.org/LICENSE_1_0.txt)
#ifndef TOML_GET_HPP
#define TOML_GET_HPP
#include <toml/type_traits.hpp>
#include <toml/value.hpp>
#include <boost/format.hpp>
#include <boost/type_index.hpp>

namespace toml
{

struct bad_get : public std::exception
{
    bad_get(const std::string& mes): message_(mes){}
    ~bad_get() BOOST_NOEXCEPT_OR_NOTHROW {}
    const char * what() const BOOST_NOEXCEPT_OR_NOTHROW
    {return message_.c_str();}

  private:
    std::string message_;
};

// non-conversion. conversion for datetime is provided in a different way
// to support conversion like date -> datetime (0:00), time -> datetime(today, local)
template<typename T>
inline typename boost::enable_if<is_toml_type<T>, T>::type&
get(value& v)
{
    try
    {
        return v.template get<T>();
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

template<typename T>
inline typename boost::enable_if<is_toml_type<T>, T>::type const&
get(value const& v)
{
    try
    {
        return v.template get<T>();
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// toml::string -> string, returning lvalue.
template<typename T>
typename boost::enable_if<boost::is_same<T, std::string>, T>::type&
get(value& v)
{
    try
    {
        return v.get<string>().str;
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}
template<typename T>
typename boost::enable_if<boost::is_same<T, std::string>, T>::type const&
get(value const& v)
{
    try
    {
        return v.get<string>().str;
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// toml::value itself. nothing needed!
template<typename T>
typename boost::enable_if<boost::is_same<T, value>, T>::type&
get(value& v)
{
    return v;
}
template<typename T>
typename boost::enable_if<boost::is_same<T, value>, T>::type const&
get(value const& v)
{
    return v;
}

// ---------------------------------------------------------------------------
// conversions. return a prvalue

// integral types but not exactly toml::integer...
template<typename T>
typename boost::enable_if<boost::mpl::and_<
        boost::mpl::not_<is_toml_type<T> >,
        boost::is_integral<T>
    >, T>::type
get(const toml::value& v)
{
    try
    {
        return static_cast<T>(v.get<integer>());
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// floating types but not exactly toml::floating...
template<typename T>
typename boost::enable_if<boost::mpl::and_<
        boost::mpl::not_<is_toml_type<T> >,
        boost::is_floating_point<T>
    >, T>::type
get(const toml::value& v)
{
    try
    {
        return static_cast<T>(v.get<floating>());
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// string_view
template<typename T>
typename boost::enable_if<is_string_view_like<T>, T>::type
get(const toml::value& v)
{
    try
    {
        return T(v.get<string>().str);
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// std::tm from date, time, local_datetime, offset_datetime
template<typename T>
typename boost::enable_if<boost::is_same<T, std::tm>, T>::type
get(const value& v)
{
    try
    {
        switch(v.which())
        {
            case value::date_tag:
            {
                return boost::gregorian::to_tm(v.get<toml::date>());
            }
            case value::time_tag:
            {
                return boost::posix_time::to_tm(v.get<toml::time>());
            }
            case value::local_datetime_tag:
            {
                return boost::posix_time::to_tm(v.get<toml::local_datetime>());
            }
            case value::offset_datetime_tag:
            {
                return boost::local_time::to_tm(v.get<toml::offset_datetime>());
            }
            default:
            {
                throw bad_get((boost::format("toml::get: type of toml value is "
                    "`toml::%1%`, but type `%2%` is specified.") % v.which() %
                    boost::typeindex::type_id<T>().pretty_name()).str());
            }
        }
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<T>().pretty_name()).str());
    }
}

// array_like
template<typename Array>
typename boost::enable_if<is_array_like<Array>, Array>::type
get(const toml::value& v)
{
    typedef typename Array::value_type value_type;
    try
    {
        toml::array const& ar = v.get<toml::array>();

        Array retval(ar.size());
        typename Array::iterator out(retval.begin());
        for(toml::array::const_iterator i(ar.begin()), e(ar.end()); i!=e; ++i)
        {
            *(out++) = get<value_type>(*i);
        }
        return retval;
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Array>().pretty_name()).str());
    }

}

// (boost|std)::array
template<typename Array>
typename boost::enable_if<is_fixed_size_array<Array>, Array>::type
get(const toml::value& v)
{
    typedef typename Array::value_type value_type;
    try
    {
        toml::array const& ar = v.get<toml::array>();
        Array retval;
        if(ar.size() != retval.size())
        {
            throw std::out_of_range((boost::format("toml::get<%1%>: specified "
                "size differs from its actual size (%2% != %3%).") %
                boost::typeindex::type_id<Array>().pretty_name() %
                retval.size() % ar.size()).str());
        }

        typename Array::iterator out(retval.begin());
        for(toml::array::const_iterator i(ar.begin()), e(ar.end()); i!=e; ++i)
        {
            *(out++) = get<value_type>(*i);
        }
        return retval;
    }
    catch(boost::bad_get const& bg) // thrown from v.get<toml::array>
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Array>().pretty_name()).str());
    }
}

// table-like case
template<typename Map>
typename boost::enable_if<is_map_like<Map>, Map>::type
get(const toml::value& v)
{
    try
    {
        toml::table const& tb = v.get<toml::table>();
        Map retval;
        for(toml::table::const_iterator i(tb.begin()), e(tb.end()); i!=e; ++i)
        {
            retval.insert(*i);
        }
        return retval;
    }
    catch(boost::bad_get const& bg) // thrown from v.get<toml::table>
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Map>().pretty_name()).str());
    }
}

// pair
template<typename Pair>
typename boost::enable_if<is_pair_type<Pair>, Pair>::type
get(const toml::value& v)
{
    typedef typename detail::first_type_of<Pair>::type  first_type;
    typedef typename detail::second_type_of<Pair>::type second_type;
    try
    {
        toml::array const& ar = v.get<toml::array>();
        if(ar.size() != 2)
        {
            throw std::out_of_range((boost::format("toml::get<pair<T1, T2>>: "
                "no enough size (%1% != 2).") % ar.size()).str());
        }
        return std::make_pair(toml::get< first_type>(ar.at(0)),
                              toml::get<second_type>(ar.at(1)));
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Pair>().pretty_name()).str());
    }
}

#ifdef TOML_HAS_CXX11_TUPLE
namespace detail
{

template<typename Tuple, std::size_t ...I>
Tuple get_tuple_impl(const toml::array& a, index_sequence<I...>)
{
    return std::make_tuple(
        toml::get<typename std::tuple_element<I, Tuple>::type>(a.at(I))...);
}

} // detail

// c++11 tuple
template<typename Tuple>
typename boost::enable_if<is_tuple_type<Tuple>, Tuple>::type
get(const toml::value& v)
{
    constexpr std::size_t SZ = std::tuple_size<Tuple>::value;
    try
    {
        toml::array const& ar = v.get<toml::array>();
        if(ar.size() != SZ)
        {
            throw std::out_of_range((boost::format("toml::get<tuple>: "
                "no enough size (%1% != %2%).") % ar.size() % SZ).str());
        }
        return detail::get_tuple_impl<Tuple>(ar, make_index_sequence<SZ>{});
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Tuple>().pretty_name()).str());
    }
}
#endif// TOML_HAS_CXX11_TUPLE

#ifdef TOML_HAS_CXX11_CHRONO

// c++11 chrono
template<typename TimePoint>
typename boost::enable_if<
    is_std_chrono_system_clock_time_point<TimePoint>, TimePoint>::type
get(const toml::value& v)
{
    try
    {
        switch(v.which())
        {
            case value::date_tag:
            {
                const std::time_t t = boost::posix_time::to_time_t(
                    boost::posix_time::ptime(
                        v.get<date>(), boost::posix_time::hours(0)));
                return std::chrono::system_clock::from_time_t(t);
            }
            case value::local_datetime_tag:
            {
                const std::time_t t = boost::posix_time::to_time_t(
                        v.get<local_datetime>());
                return std::chrono::system_clock::from_time_t(t);
            }
            case value::offset_datetime_tag:
            {
                const std::time_t t = boost::posix_time::to_time_t(
                        v.get<offset_datetime>().utc_time());
                return std::chrono::system_clock::from_time_t(t);
            }
            default:
            {
                throw bad_get((boost::format("toml::get: type of toml value is "
                    "`toml::%1%`, but type `%2%` is specified.") % v.which() %
                    boost::typeindex::type_id<TimePoint>().pretty_name()).str());
            }
        }
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<TimePoint>().pretty_name()).str());
    }
}

template<typename Duration>
typename boost::enable_if<is_std_chrono_duration<Duration>, Duration>::type
get(const toml::value& v)
{
    try
    {
        const time& t = v.get<time>();
#ifdef BOOST_DATE_TIME_HAS_NANOSECONDS
        return std::chrono::duration_cast<Duration>(
                std::chrono::nanoseconds(t.total_nanoseconds()));
#else
        return std::chrono::duration_cast<Duration>(
                std::chrono::microseconds(t.total_microseconds()));
#endif
    }
    catch(boost::bad_get const& bg)
    {
        throw bad_get((boost::format("toml::get: type of toml value is "
            "`toml::%1%`, but type `%2%` is specified.") % v.which() %
            boost::typeindex::type_id<Duration>().pretty_name()).str());
    }
}

#endif // TOML_HAS_CXX11_CHRONO

} // toml
#endif// TOML98_GET_HPP


text:
/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <qi/log/headfileloghandler.hpp>

#include <boost/function.hpp>
#include <boost/filesystem.hpp>
#include <boost/bind.hpp>

#include <sstream>
#include <iomanip>
#include <string>
#include <qi/log.hpp>
#include "log_p.hpp"
#include <qi/os.hpp>
#include <cstdio>
#include <boost/thread/mutex.hpp>

qiLogCategory("qi.log.headfileloghandler");

namespace qi
{
namespace log
{
  struct PrivateHeadFileLogHandler
  {
    FILE* _file;
    int _count;
    int _max;
    boost::mutex _mutex;
  };

  HeadFileLogHandler::HeadFileLogHandler(const std::string& filePath, int length)
    : _p(new PrivateHeadFileLogHandler)
  {
    _p->_max = length;
    _p->_file = NULL;
    _p->_count = _p->_max + 1;

    boost::filesystem::path fPath(filePath);
    // Create the directory!
    try
    {
      if (!boost::filesystem::exists(fPath.make_preferred().parent_path()))
        boost::filesystem::create_directories(fPath.make_preferred().parent_path());
    }
    catch (const boost::filesystem::filesystem_error& e)
    {
      qiLogWarning() << e.what();
    }
    // Open the file.
    FILE* file = qi::os::fopen(fPath.make_preferred().string().c_str(), "w+");

    if (file)
    {
      _p->_file = file;
      _p->_count = 0;
    }
    else
    {
      qiLogWarning() << "Cannot open " << filePath;
    }
  }

  HeadFileLogHandler::~HeadFileLogHandler()
  {
    if (_p->_file != NULL)
      fclose(_p->_file);
    delete _p;
  }

  void HeadFileLogHandler::log(const qi::LogLevel verb,
                               const qi::Clock::time_point date,
                               const qi::SystemClock::time_point systemDate,
                               const char* category,
                               const char* msg,
                               const char* file,
                               const char* fct,
                               const int line)
  {
    boost::mutex::scoped_lock scopedLock(_p->_mutex);

    if (_p->_count < _p->_max)
    {
      if (verb > qi::log::logLevel() || _p->_file == NULL)
      {
        return;
      }
      else
      {
        std::string logline =
            qi::detail::logline(qi::log::context(), date, systemDate, category, msg, file, fct, line, verb);
        fprintf(_p->_file, "%s", logline.c_str());
        fflush(_p->_file);

        _p->_count++;
      }
    }
    else if (_p->_file != NULL)
    {
      fclose(_p->_file);
      _p->_file = NULL;
    }
  }
}
}

max_stars_repo_name: arntanguy/libqi

max_issues_repo_name: arntanguy/libqi

max_forks_repo_name: arntanguy/libqi


text:
#pragma once

#include <queue>

#include <boost/asio.hpp>
#include <GameObject.hpp>

#include "GameManager.hpp"
#include "PlayerConnection.hpp"
#include "GoPlayer.hpp"

namespace cf
{

using boost::asio::ip::udp;

class GoUdp : public sfs::GameObject
{
public:
	GoUdp(sfs::Scene &scene, GameManager &manager, boost::asio::io_service &service) noexcept;
	void start(sfs::Scene &scene) noexcept;
	void update(sfs::Scene &scene) noexcept;

private:
	PlayerConnection *getConnectionFromEndpoint(const tcp::endpoint &endpoint) const noexcept;
	GoPlayer *getPlayerFromConnection(PlayerConnection &connection) const noexcept;
	void onUpdate(PlayerConnection &connection, const boost::system::error_code &error,
				  std::size_t bytes_transferred);
	void executePackets(PlayerConnection &connection) noexcept;
	void asyncReceive(PlayerConnection &connection) noexcept;
	void pollPackets() noexcept;
	template <typename... Args>
	void autoBind(UdpPrctl::Type type, Args... args)
	{
		_callbacks[static_cast<int>(type)] =
			std::bind(args..., this, std::placeholders::_1, std::placeholders::_2);
	}
	/* udp handlers */
	int positionHandler(GoPlayer &player, Serializer &toRead);
	int velocityHandler(GoPlayer &player, Serializer &toRead);
	int spriteHandler(GoPlayer &player, Serializer &toRead);
	int spawnHandler(GoPlayer &player, Serializer &toRead);
	int inputHandler(GoPlayer &player, Serializer &toRead);
	int timeHandler(GoPlayer &player, Serializer &toRead);
	int stateHandler(GoPlayer &player, Serializer &toRead);
	int destroyHandler(GoPlayer &player, Serializer &toRead);
	int attackHandler(GoPlayer &player, Serializer &toRead);
	int unknownHandler(GoPlayer &player, Serializer &toRead);
	int ackHandler(GoPlayer &player, Serializer &toRead);
	/* private data */
	sfs::Scene &_scene;
	std::function<int(GoPlayer &, Serializer &toRead)>
		_callbacks[static_cast<int>(UdpPrctl::Type::ACK) + 1];
	boost::asio::io_service &_ingameService;
	GameManager &_manager;
};
} // namespace cf

max_stars_repo_name: LeandreBl/cautious-fiesta-server

max_issues_repo_name: LeandreBl/cautious-fiesta-server

max_forks_repo_name: LeandreBl/cautious-fiesta-server


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_RULE_SEQUENCE_HPP
#define BOOST_HTTP_PROTO_RULE_SEQUENCE_HPP

#include <boost/http_proto/detail/config.hpp>
#include <boost/http_proto/error.hpp>
#include <boost/http_proto/bnf/type_traits.hpp>
#include <boost/static_assert.hpp>
#include <cstddef>

namespace boost {
namespace http_proto {
namespace bnf {

/** Rule for a repeating number of elements

    This rule defines a sequence containing
    at least n and at most m of Element.

    @par BNF
    @code
    sequence          =  <n>*<m>element

    *<m>element     => <0>*<m>element
    <n>*element     => <n>*<inf.>element
    *element        => <0>*<inf.>element
    <n>element      => <n>*<n>element
    [ element ]     => *1( element )
    @endcode

    @see
        https://datatracker.ietf.org/doc/html/rfc5234#section-3.6

    @tparam Element The element type to repeat
    @tparam N The minimum number of repetitions, which may be zero
    @tparam M The maximum number of repetitions.
*/
template<
    class Element,
    std::size_t N = 0,
    std::size_t M = std::size_t(-1)>
class sequence
{
    BOOST_STATIC_ASSERT(M > 0);
    BOOST_STATIC_ASSERT(M >= N);
    BOOST_STATIC_ASSERT(
        is_element<Element>::value);

    Element element_;
    std::size_t n_;

public:
    using value_type =
        typename Element::value_type;

    value_type
    value() const noexcept
    {
        return element_.value();
    }

    char const*
    begin(
        char const* start,
        char const* end,
        error_code& ec);

    char const*
    increment(
        char const* start,
        char const* end,
        error_code& ec);
};

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

/** A BNF rule for zero or more repetitions of element
*/
template<class Element>
using zero_or_more = sequence<Element>;

/** A BNF rule for one or more repetitions of element
*/
template<class Element>
using one_or_more = sequence<Element, 1>;

} // bnf
} // http_proto
} // boost

#include <boost/http_proto/bnf/impl/sequence.hpp>

#endif


text:
#include "adaptor/dictionary.hpp"

#include "tool/container/dictionary.hpp"
#include "tool/container/string_table.hpp"

#include "id/dictionary.hpp"                   // for DictionaryID
#include "tool/dictionary.pb.h"                // for DictionaryEntry, Dict...
#include <algorithm>                           // for for_each, sort
#include <boost/assert.hpp>                    // for BOOST_ASSERT
#include <boost/range/iterator_range_core.hpp> // for iterator_range
#include <cstdint>
#include <iosfwd> // for string
#include <string>
#include <type_traits> // for enable_if<>::type
#include <utility>
#include <vector> // for vector, vector<>::val...

namespace nepomuk
{
namespace adaptor
{

io::container::Dictionary_proto Dictionary::encode(tool::container::Dictionary const &dictionary)
{
    io::container::Dictionary_proto message;

    auto const lookup = dictionary.get_lookup();
    using LookupType = std::pair<std::string, std::uint64_t>;
    std::vector<LookupType> data(lookup.begin(), lookup.end());

    auto const by_second = [](LookupType const &lhs, LookupType const &rhs) {
        return lhs.second < rhs.second;
    };
    std::sort(data.begin(), data.end(), by_second);

    auto const to_entry = [&dictionary](auto const &value) {
        io::container::DictionaryEntry entry;
        entry.set_id(value.second);
        auto const &display = dictionary.get_string(DictionaryID{value.second});
        entry.set_display(display);

        if (display != value.first)
            entry.set_categorized(value.first);

        return entry;
    };

    auto const add_entry = [&message, &to_entry](auto const &data) {
        auto new_entry = message.add_entries();
        *new_entry = to_entry(data);
    };

    std::for_each(data.begin(), data.end(), add_entry);

    return message;
}

void Dictionary::decode_into(tool::container::Dictionary &dictionary,
                             io::container::Dictionary_proto const &message)
{
    BOOST_ASSERT(dictionary.id_look_up.empty());
    BOOST_ASSERT(dictionary.dictionary.empty());
    dictionary.dictionary.resize(message.entries_size());
    for (int message_id = 0; message_id < message.entries_size(); ++message_id)
    {
        auto const &entry = message.entries(message_id);
        dictionary.dictionary[entry.id()] = entry.display();
        if (entry.has_categorized())
            dictionary.id_look_up.insert(std::make_pair(entry.categorized(), entry.id()));
        else
            dictionary.id_look_up.insert(std::make_pair(entry.display(), entry.id()));
    }
}
void Dictionary::decode_into(tool::container::StringTable &dictionary,
                             io::container::Dictionary_proto const &message)
{
    dictionary.resize(message.entries_size());
    for (int message_id = 0; message_id < message.entries_size(); ++message_id)
    {
        auto const &entry = message.entries(message_id);
        dictionary[entry.id()] = entry.display();
    }
}

} // namespace adaptor
} // namespace nepomuk

max_stars_repo_name: mapbox/nepomuk

max_issues_repo_name: mapbox/nepomuk

max_forks_repo_name: mapbox/nepomuk


text:
//
// Created by denn on 04/10/2018.
//
#include <optional>
#include <functional>
#include "milecsa.hpp"
#include "milecsa_jsonrpc.hpp"
#include <boost/program_options.hpp>
#include <boost/chrono/chrono.hpp>

static std::string opt_mile_node_address = "http://lotus000.testnet.mile.global/v1/api";
static std::string opt_method= "";
static std::string opt_method_params = "{}";
static int opt_reconnections = 3;
static time_t opt_timeout = 3;
static time_t opt_read_timeout = 5;

namespace po = boost::program_options;

static bool parse_cmdline(int ac, char *av[]);

int main(int argc, char *argv[]) {
    setlocale(LC_ALL, "");

    if (!parse_cmdline(argc, argv))
        return 1;

    milecsa::http::ResponseHandler response_fail_handler;
    milecsa::ErrorHandler error_handler;
    int reconnections = 0;

    auto do_request = [&]{
        if (auto rpc = milecsa::rpc::Client::Connect(
                opt_mile_node_address,
                true,
                response_fail_handler,
                error_handler)){

            try {
                nlohmann::json params;
                try {
                    params = nlohmann::json::parse(opt_method_params);
                }
                catch (std::exception &e) {
                    std::cerr << "Params parser error: " << e.what() << "\n";
                }

                auto result = rpc->call(opt_method,params);

                if (!result.has_value()) {
                    std::cerr << "Rpc error: response does not have any result"<< std::endl;
                    exit(-1);
                }

                std::cout<< "Call " << opt_method << ": ";

                if (result.type() == typeid(time_t))
                    std::cout << std::any_cast<time_t>(result);

                else if (result.type() == typeid(uint256_t)){
                    std::cout << std::any_cast<uint256_t>(result);
                }

                else if (result.type() == typeid(milecsa::rpc::response)){
                    std::cout << std::any_cast<milecsa::rpc::response>(result)->dump();
                }

                std::cout << std::endl;
            }
            catch (std::exception &e) {
                std::cerr << "Method error: " << e.what() << "\n";
            }
        }
    };

    response_fail_handler = [](
            const milecsa::http::status code,
            const std::string &method,
            const milecsa::http::response &http){
        std::cerr << "Response["<<code<<"] "<<method<<" error: " << http.result() << std::endl << http << std::endl;
    };

    error_handler = [&](
            milecsa::result code,
            const std::string &error){
        std::cerr << "Call ["<<reconnections<<"] error: " << error << std::endl;

        if (code != milecsa::result::FAIL) {
            exit(-1);
        }

        if (++reconnections >= opt_reconnections ) {
            exit(-1);
        }

        std::this_thread::sleep_for(std::chrono::seconds(opt_timeout));

        do_request();
    };

    do_request();

    exit(0);
}

static bool parse_cmdline(int ac, char *av[]) {

    try {

        po::options_description desc("Allowed options");

        std::string wallet_phrase="";

        desc.add_options()
                ("help", "produce help message")

                ("debug", "print debug messages")

                ("wallet,w", po::value<std::string>(&wallet_phrase),
                 "create wallet from random (-w \"random\") or secret phrase")

                ("output,o",
                 "node wallet file output format (-w only)")

                ("url,u", po::value<std::string>(&opt_mile_node_address)->
                         default_value(opt_mile_node_address),
                 "RPC url")

                ("method,m", po::value<std::string>(&opt_method)->
                         default_value(opt_method),
                 "blockchain command")

                ("params,p", po::value<std::string>(&opt_method_params)->
                         default_value(opt_method_params),
                 "blockchain params")

                ("reconnections,r", po::value<int>(&opt_reconnections)->
                         default_value(opt_reconnections),
                 "try to connect again reconnection times if any connection error occurred")

                ("timeout,t", po::value<time_t>(&opt_read_timeout)->
                         default_value(opt_reconnections),
                 "connection/read timeout in seconds")
                ;

        std::string ext = ""\
        "Methods: \n"\
        "\tget-blockchain-info \n"\
        "\tget-blockchain-state \n"\
        "\tget-network-state \n"\
        "\tget-nodes \n"\
        "\tget-current-block-id \n"\
        "\tget-block --params '{\"id\":1}'\n"\
        "\tget-wallet-state --params '{\"public-key\": \"...bHqSm8WTuY3gB9UXD...\"}' \n"\
        "\tget-wallet-transactions --params '{\"public-key\": \"...bHqSm8WTuY3gB9UXD...\"}' \n"\
        "\tsend-transfer --params '{\"private-key\": \"...bHqSm8WTuY3gB9UXD...\", \"to\":\"...pXg1MF4qxZTEsL..\", \"amount\": \"100\", \"asset-code\":0, \"description\":\"send my money back!\"}' \n"\
        "\tregister-node --params '{\"private-key\": \"...bHqSm8WTuY3gB9UXD....\", \"amount\": 10000.00, \"address\": \"xxx.yyy.zzz.www\"}'\n"\
        "\tunregister-node --params '{\"private-key\": \"...bHqSm8WTuY3gB9UXD....\"}'\n"\
        "\tvote-for-rate -p '{\"private-key\": \"...bHqSm8WTuY3gB9UXD....\", \"amount\": 1.21}'\n"\
        "";

        po::variables_map vm;
        po::store(po::parse_command_line(ac, av, desc), vm);
        po::notify(vm);

        if (vm.count("help")) {
            std::cout << desc << "\n";
            std::cout << ext << "\n";
            exit(0);
        }

        if (vm.count("wallet")) {
            std::optional<milecsa::keys::Pair> pair;
            if (wallet_phrase.empty() || wallet_phrase=="random"){
                pair = milecsa::keys::Pair::Random();
            }
            else {
                pair = milecsa::keys::Pair::WithSecret(wallet_phrase);
            }

            bool print_mess = vm.count("output");

            std::cout<< (!print_mess ? "Wallet private key: " : "") << pair->get_private_key().encode() << std::endl;
            std::cout<< (!print_mess ? "        public key: " : "") << pair->get_public_key().encode() << std::endl;

            exit(0);
        }

        if (opt_method.empty()) {
            std::cout << desc << "\n";
            std::cout << ext << "\n";
            exit(0);
        }

        if (vm.count("debug")) {
            milecsa::rpc::detail::RpcSession::debug_on = true;
        }

        milecsa::rpc::Client::timeout = opt_read_timeout;
    }

    catch (std::exception &e) {
        std::cerr << "error: " << e.what() << "\n";
        return false;
    }
    catch (...) {
        std::cerr << "Exception of unknown type!\n";
        return false;
    }

    return true;
}

max_stars_repo_name: mile-core/mile-csa-jsonrpc-client

max_issues_repo_name: mile-core/mile-csa-jsonrpc-client

max_forks_repo_name: mile-core/mile-csa-jsonrpc-client


text:
/*  $Id: $
 *
 *  Copyright 2010-2011 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/python.hpp>

#include "voronoidiagram_py.hpp"

/*
 *  Python wrapping of voronoi diagram
 */

using namespace ocl;

namespace bp = boost::python;

void export_voronoi() {

#ifndef WIN32
    bp::class_<VoronoiDiagram >("VoronoiDiagram_base")
    ;
    bp::class_< VoronoiDiagram_py, bp::bases<VoronoiDiagram> >("VoronoiDiagram")
        .def(bp::init<double, unsigned int>())
        .def("addVertexSite",  &VoronoiDiagram_py::addVertexSite)
        .def("getGenerators",  &VoronoiDiagram_py::getGenerators)
        .def("getEdgesGenerators",  &VoronoiDiagram_py::getEdgesGenerators)
        .def("getVoronoiVertices",  &VoronoiDiagram_py::getVoronoiVertices)
        .def("getFarVoronoiVertices",  &VoronoiDiagram_py::getFarVoronoiVertices)
        .def("getFarRadius",  &VoronoiDiagram_py::getFarRadius)
        .def("getVoronoiEdges",  &VoronoiDiagram_py::getVoronoiEdges)
        //.def("setDelaunayTriangulation",  &VoronoiDiagram_py::setDelaunayTriangulation)
        //.def("getDelaunayEdges",  &VoronoiDiagram_py::getDelaunayEdges)
        .def("getClosestFaceGenerator",  &VoronoiDiagram_py::getClosestFaceGenerator)
        .def("getSeedVertex",  &VoronoiDiagram_py::getSeedVertex)
        .def("getDeleteSet",  &VoronoiDiagram_py::getDeleteSet)
        .def("getDeleteEdges",  &VoronoiDiagram_py::getDeleteEdges)
        .def("getModEdges",  &VoronoiDiagram_py::getModEdges)
        .def("__str__", &VoronoiDiagram_py::str)
    ;
    bp::enum_<VoronoiVertexType>("VoronoiVertexType")
        .value("OUT", OUT)
        .value("IN", IN)
        .value("UNDECIDED", UNDECIDED)
        .value("NEW", NEW)
    ;
    bp::enum_<VoronoiFaceType>("VoronoiFaceType")
        .value("INCIDENT", INCIDENT)
        .value("NONINCIDENT", NONINCIDENT)
    ;

#endif
}


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef CORE_ASCENT_DIRECTION_PICKER_HPP
#define CORE_ASCENT_DIRECTION_PICKER_HPP

#include <iostream>
#include <boost/noncopyable.hpp>
#include <Eigen/Core>
#include <Eigen/Cholesky>
#include <Eigen/Eigenvalues>
#include "integration/ModifiedCholesky.hpp"

// #define DEBUG_ASCENT_DIRECTION_PICKER 1

namespace integration {
	template< typename Function >
	struct CholeskyOrEigenvalueSolver: public boost::noncopyable {
	public:
		typedef Eigen::VectorXd Vector ;
		typedef Eigen::MatrixXd Matrix ;

	public:
		CholeskyOrEigenvalueSolver(
			double const delta = -0.1
		):
			m_delta( delta )
		{
			assert( delta < 0 ) ;
		}

		void set_delta( double const delta ) {
			assert( delta < 0 ) ;
			m_delta = delta ;
		}

		Vector compute( Function& function, Vector const& point ) {
			function.evaluate_at( point, 2 ) ;
			Matrix const matrix = function.get_value_of_second_derivative() ;
			Vector const v = -function.get_value_of_first_derivative() ;
			m_cholesky_solver.compute( matrix ) ;
			if( m_cholesky_solver.info() == Eigen::Success && m_cholesky_solver.vectorD().array().maxCoeff() < 0 ) {
				return m_cholesky_solver.solve( v ) ;
			} else {
				m_eigen_solver.compute( matrix ) ;
				if( m_eigen_solver.info() == Eigen::NoConvergence ) {
					throw NumericalError( "integration::CholeskyOrEigenvalueSolver::solve()", "Eigenvalue decomposition did not converge" ) ;
				}

				m_d = m_eigen_solver.eigenvalues() ;
				for( int i = 0; i < m_d.size(); ++i ) {
					if( m_d(i) > m_delta ) {
						m_d(i) = m_delta ;
					}
				}
				m_d = m_d.array().inverse() ;

				return (
					m_eigen_solver.eigenvectors() * m_d.asDiagonal() * m_eigen_solver.eigenvectors().transpose()
				) * v ;
			}
		}

	private:
		double m_delta ;
		Eigen::LDLT< Matrix > m_cholesky_solver ;
		Eigen::SelfAdjointEigenSolver< Matrix > m_eigen_solver ;
		Eigen::VectorXd m_d ;
	} ;

}

#endif

max_stars_repo_name: gavinband/bingwa

max_issues_repo_name: gavinband/bingwa

max_forks_repo_name: gavinband/qctool


text:
#include "teca_shape_file_mask.h"

#include "teca_cartesian_mesh.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"
#include "teca_array_attributes.h"
#include "teca_geometry.h"
#include "teca_shape_file_util.h"
#include "teca_coordinate_util.h"
#include "teca_file_util.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <set>
#include <cmath>

#if defined(TECA_HAS_MPI)
#include <mpi.h>
#endif

#if defined(TECA_HAS_BOOST)
#include <boost/program_options.hpp>
#endif

//#define TECA_DEBUG

namespace internal
{
}

using poly_coord_t = double;

struct teca_shape_file_mask::internals_t
{
    std::vector<teca_geometry::polygon<poly_coord_t>> polys;
};

// --------------------------------------------------------------------------
teca_shape_file_mask::teca_shape_file_mask() : internals(new teca_shape_file_mask::internals_t)
{
    this->set_number_of_input_connections(1);
    this->set_number_of_output_ports(1);
}

// --------------------------------------------------------------------------
teca_shape_file_mask::~teca_shape_file_mask()
{}

#if defined(TECA_HAS_BOOST)
// --------------------------------------------------------------------------
void teca_shape_file_mask::get_properties_description(
    const std::string &prefix, options_description &global_opts)
{
    options_description opts("Options for "
        + (prefix.empty()?"teca_shape_file_mask":prefix));

    opts.add_options()
        TECA_POPTS_GET(std::string, prefix, shape_file,
            "Path and file name to one of the *.shp/*.shx files")

        TECA_POPTS_MULTI_GET(std::vector<std::string>, prefix, mask_variables,
            "Set the names of the variables to store the generated mask in."
            " Each name is assigned a reference to the mask.")
        ;

    this->teca_algorithm::get_properties_description(prefix, opts);

    global_opts.add(opts);
}

// --------------------------------------------------------------------------
void teca_shape_file_mask::set_properties(
    const std::string &prefix, variables_map &opts)
{
    this->teca_algorithm::set_properties(prefix, opts);

    TECA_POPTS_SET(opts, std::string, prefix, shape_file)
    TECA_POPTS_SET(opts, std::vector<std::string>, prefix, mask_variables)
}
#endif

// --------------------------------------------------------------------------
void teca_shape_file_mask::set_modified()
{
   this->teca_algorithm::set_modified();
   this->internals->polys.clear();
}

// --------------------------------------------------------------------------
teca_metadata teca_shape_file_mask::get_mask_array_attributes(unsigned long size)
{
    unsigned int centering = teca_array_attributes::point_centering;

    // construct output attributes
    teca_array_attributes mask_atts(
        teca_variant_array_code<char>::get(),
        centering, size, "none", "", "Mask array generated from "
        + teca_file_util::filename(this->shape_file));

    teca_metadata array_atts((teca_metadata)mask_atts);

    int have_mesh_dim[4] = {1, 1, 0, 0};
    int mesh_dim_active[4] = {1, 1, 0, 0};
    int n_mesh_dims = 2;
    int n_active_dims = 2;

    array_atts.set("have_mesh_dim", have_mesh_dim, 4);
    array_atts.set("mesh_dim_active", mesh_dim_active, 4);
    array_atts.set("n_mesh_dims", n_mesh_dims);
    array_atts.set("n_active_dims", n_active_dims);

    return array_atts;
}

// --------------------------------------------------------------------------
teca_metadata teca_shape_file_mask::get_output_metadata(
    unsigned int port,
    const std::vector<teca_metadata> &input_md)
{
#ifdef TECA_DEBUG
    std::cerr << teca_parallel_id()
        << "teca_shape_file_mask::get_output_metadata" << std::endl;
#endif
    (void)port;

    // validate runtime provided settings
    unsigned int n_mask_vars = this->mask_variables.size();
    if (n_mask_vars == 0)
    {
        TECA_FATAL_ERROR("The names of the mask_variables were not provided")
        return teca_metadata();
    }

    if (this->shape_file.empty())
    {
        TECA_FATAL_ERROR("A shape file was not provided")
        return teca_metadata();

    }

    // load the polygons
    if (this->internals->polys.empty() &&
        teca_shape_file_util::load_polygons(this->get_communicator(),
        this->shape_file, this->internals->polys, this->verbose))
    {
        TECA_FATAL_ERROR("Failed to read polygons from \"" << this->shape_file << "\"")
        return teca_metadata();
    }

    // pass metadata from the input mesh through.
    const teca_metadata &mesh_md = input_md[0];
    teca_metadata out_md(mesh_md);

    // add the mask arrays we will generate
    for (unsigned int i = 0; i < n_mask_vars; ++i)
        out_md.append("variables", this->mask_variables[i]);

    // insert attributes to enable this to be written by the CF writer
    teca_metadata attributes;
    out_md.get("attributes", attributes);

    teca_metadata array_atts = this->get_mask_array_attributes(0);

    // add one for each output
    for (unsigned int i = 0; i < n_mask_vars; ++i)
        attributes.set(this->mask_variables[i], array_atts);

    // update the attributes collection
    out_md.set("attributes", attributes);

    return out_md;
}

// --------------------------------------------------------------------------
std::vector<teca_metadata> teca_shape_file_mask::get_upstream_request(
    unsigned int port,
    const std::vector<teca_metadata> &input_md,
    const teca_metadata &request)
{
    (void)port;
    (void)input_md;

    std::vector<teca_metadata> up_reqs;

    // copy the incoming request to preserve the downstream
    // requirements and add the arrays we need
    teca_metadata req(request);

    std::set<std::string> arrays;
    if (req.has("arrays"))
        req.get("arrays", arrays);

    // intercept request for our output
    unsigned int n_mask_vars = this->mask_variables.size();
    for (unsigned int i = 0; i < n_mask_vars; ++i)
        arrays.erase(this->mask_variables[i]);

    req.set("arrays", arrays);
    up_reqs.push_back(req);

    return up_reqs;
}

// --------------------------------------------------------------------------
const_p_teca_dataset teca_shape_file_mask::execute(
    unsigned int port,
    const std::vector<const_p_teca_dataset> &input_data,
    const teca_metadata &request)
{
#ifdef TECA_DEBUG
    std::cerr << teca_parallel_id() << "teca_shape_file_mask::execute" << std::endl;
#endif
    (void)port;
    (void)request;

    // get the input mesh
    const_p_teca_cartesian_mesh in_mesh
        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);

    if (!in_mesh)
    {
        TECA_FATAL_ERROR("Failed to compute surface pressure. The dataset is"
            " not a teca_mesh")
        return nullptr;
    }

    // get the coordinate arrays.
    const_p_teca_variant_array x = in_mesh->get_x_coordinates();
    const_p_teca_variant_array y = in_mesh->get_y_coordinates();
    const_p_teca_variant_array z = in_mesh->get_z_coordinates();

    if (z->size() > 1)
    {
        TECA_FATAL_ERROR("The shape file mask requires 2D data but 3D data was found")
        return nullptr;
    }

    // allocate the mask array
    unsigned long nx = x->size();
    unsigned long ny = y->size();
    unsigned long nxy = nx*ny;

    p_teca_char_array mask = teca_char_array::New(nxy, 0);
    char *p_mask = mask->get();

    // visit each polygon
    unsigned long np = this->internals->polys.size();
    for (unsigned long p = 0; p < np; ++p)
    {
        // get the polygon's axis aligned bounding box
        poly_coord_t bounds[6] = {0};
        this->internals->polys[p].get_bounds(bounds);

        // convert it to the mesh extents
        unsigned long extent[6] = {0};
        if (teca_coordinate_util::bounds_to_extent(bounds,x, y, z, extent))
        {
            TECA_FATAL_ERROR("Failed to convert polygon " << p << " bounds ["
                << bounds[0] << ", " << bounds[1] << ", " << bounds[2]
                << ", " << bounds[3] << " to a valid mesh extent")
            continue;
        }

        // test each point in the extent for intersection with the polygon
        TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,
            x.get(),

            const NT *p_x = static_cast<TT*>(x.get())->get();
            const NT *p_y = static_cast<TT*>(y.get())->get();

            for (unsigned long j = extent[2]; j <= extent[3]; ++j)
            {
                for (unsigned long i = extent[0]; i <= extent[1]; ++i)
                {
                    if (this->internals->polys[p].inside(p_x[i], p_y[j]))
                        p_mask[j*nx + i] = 1;
                }
            }
            )
    }

    // pass incoming data
    p_teca_cartesian_mesh out_mesh =
        std::static_pointer_cast<teca_cartesian_mesh>(
            std::const_pointer_cast<teca_cartesian_mesh>(in_mesh)->new_shallow_copy());

    // pass a reference to the mask
    unsigned int n_mask_vars = this->mask_variables.size();
    for (unsigned int i = 0; i < n_mask_vars; ++i)
        out_mesh->get_point_arrays()->set(this->mask_variables[i], mask);

    // add attributes
    teca_metadata attributes;
    out_mesh->get_attributes(attributes);

    teca_metadata array_atts = this->get_mask_array_attributes(nxy);

    // add one for each output
    for (unsigned int i = 0; i < n_mask_vars; ++i)
        attributes.set(this->mask_variables[i], array_atts);

    // update the attributes collection
    out_mesh->set_attributes(attributes);

    return out_mesh;
}

ext: cxx

max_stars_repo_name: LBL-EESA/TECA

max_issues_repo_name: LBL-EESA/TECA

max_forks_repo_name: LBL-EESA/TECA


text:
//           Copyright Jeroen Habraken 2011 - 2012.
//
// Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file ../../LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#if !defined(BOOST_COERCE_STRING_HPP)
#define BOOST_COERCE_STRING_HPP

#if defined(_MSC_VER) && _MSC_VER >= 1200
    #pragma once
#endif  // defined(_MSC_VER) && _MSC_VER >= 1200

#include <boost/coerce/char.hpp>

#include <boost/mpl/bool.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <boost/type_traits/remove_const.hpp>

#include <cstddef>  // std::size_t
#include <string>
#include <vector>

namespace boost { namespace coerce { namespace traits {

    template <typename T>
    struct string_traits_impl;

    template <typename T>
    struct string_traits_impl<T *> {
        typedef T const * const_iterator;

        static inline const_iterator
        begin(T * const value) {
            return value;
        }

        static inline const_iterator
        end(T * const value) {
            return value + std::char_traits<
                               typename remove_const<T>::type
                           >::length(value);
        }
    };

    template <typename T, std::size_t N>
    struct string_traits_impl<T [N]> {
        typedef T const * const_iterator;

        static inline const_iterator
        begin(T const(& value)[N]) {
            return value;
        }

        static inline const_iterator
        end(T const(& value)[N]) {
            return value + (value[N - 1] == 0 ? N - 1 : N);
        }
    };

    template <typename T, typename Traits, typename Allocator>
    struct string_traits_impl<std::basic_string<T, Traits, Allocator> > {
        typedef std::basic_string<T, Traits, Allocator> type;

        typedef typename type::const_iterator const_iterator;

        static inline const_iterator
        begin(type const & value) {
            return value.begin();
        }

        static inline const_iterator
        end(type const & value) {
            return value.end();
        }

        typedef std::back_insert_iterator<type> back_insert_iterator;

        static inline back_insert_iterator
        back_inserter(type & value) {
            return std::back_inserter(value);
        }
    };

    template <typename T>
    struct string_traits_impl<boost::iterator_range<T> > {
        typedef boost::iterator_range<T> type;

        typedef typename type::const_iterator const_iterator;

        static inline const_iterator
        begin(type const & value) {
            return value.begin();
        }

        static inline const_iterator
        end(type const & value) {
            return value.end();
        }
    };

    template <typename T, typename Allocator>
    struct string_traits_impl<std::vector<T, Allocator> > {
        typedef std::vector<T, Allocator> type;

        typedef typename type::const_iterator const_iterator;

        static inline const_iterator
        begin(type const & value) {
            return value.begin();
        }

        static inline const_iterator
        end(type const & value) {
            return value.end();
        }

        typedef std::back_insert_iterator<type> back_insert_iterator;

        static inline back_insert_iterator
        back_inserter(type & value) {
            return std::back_inserter(value);
        }
    };

    template <typename T, typename Enable = void>
    struct string_traits
        : string_traits_impl<T> { };

    template <typename T>
    struct is_source_string_impl
        : mpl::false_ { };

    template <typename T>
    struct is_source_string_impl<T *>
        : traits::is_char<T> { };

    template <typename T, std::size_t N>
    struct is_source_string_impl<T [N]>
        : traits::is_char<T> { };

    template <typename T, typename Traits, typename Allocator>
    struct is_source_string_impl<std::basic_string<T, Traits, Allocator> >
        : traits::is_char<T> { };

    template <typename T>
    struct is_source_string_impl<boost::iterator_range<T> >
        : traits::is_char<typename boost::iterator_range<T>::value_type> { };

    template <typename T, typename Allocator>
    struct is_source_string_impl<std::vector<T, Allocator> >
        : traits::is_char<T> { };

    template <typename T, typename Enable = void>
    struct is_source_string
        : is_source_string_impl<T> { };

    template <typename T>
    struct is_target_string_impl
        : mpl::false_ { };

    template <typename T, typename Traits, typename Allocator>
    struct is_target_string_impl<std::basic_string<T, Traits, Allocator> >
        : traits::is_char<T> { };

    template <typename T, typename Allocator>
    struct is_target_string_impl<std::vector<T, Allocator> >
        : traits::is_char<T> { };

    template <typename T, typename Enable = void>
    struct is_target_string
        : is_target_string_impl<T> { };

} } }  // namespace boost::coerce::traits

#endif  // !defined(BOOST_COERCE_STRING_HPP)

max_stars_repo_name: VeXocide/coerce

max_issues_repo_name: VeXocide/coerce

max_forks_repo_name: VeXocide/coerce


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

//----
//--------------------------------------------------------------------------------------------------------
//
// Example: WebSocket client, synchronous
//
//----
//--------------------------------------------------------------------------------------------------------

//[example_websocket_client

#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>

namespace beast     = boost::beast;       // from <boost/beast.hpp>
namespace http      = beast::http;        // from <boost/beast/http.hpp>
namespace websocket = beast::websocket;   // from <boost/beast/websocket.hpp>
namespace net       = boost::asio;        // from <boost/asio.hpp>
using tcp           = boost::asio::ip::tcp;   // from <boost/asio/ip/tcp.hpp>

// Sends a WebSocket message and prints the response
int
main(int argc, char **argv)
{
    std::atomic_bool finished { false };

    for (int i = 0; i < 30000; i++)
    {
        if ((i % 1000) == 0)
            printf("Thread spawn %i\n", i);

        std::thread([&] {
            try
            {
                std::string host = "192.168.0.55";
                std::string port = "6761";
                std::string text =
                    "a8aunpw39rvu0a9p8weufvpoaidsjfkav8w39unfvapwo9ep8UPAOISUND"
                    "PVIOUPN(*&"
                    "Np98unp938upoiuoivasdfliJNASDOIVp028upn9v8upsoinjun:"
                    "OIASJDVN";

                // The io_context is required for all I/O
                net::io_context ioc;

                // These objects perform our I/O
                tcp::resolver                    resolver { ioc };
                websocket::stream< tcp::socket > ws { ioc };

                boost::beast::websocket::permessage_deflate opt;
                opt.client_enable = true;

                ws.set_option(opt);

                // Look up the domain name
                auto const results = resolver.resolve(host, port);

                // Make the connection on the IP address we get from a lookup
                auto ep = net::connect(ws.next_layer(), results);

                // Update the host_ string. This will provide the value of the
                // Host HTTP header during the WebSocket handshake.
                // See https://tools.ietf.org/html/rfc7230#section-5.4
                host += ':' + std::to_string(ep.port());

                // Set a decorator to change the User-Agent of the handshake
                ws.set_option(websocket::stream_base::decorator(
                    [](websocket::request_type &req) {
                        req.set(http::field::user_agent,
                                std::string(BOOST_BEAST_VERSION_STRING) +
                                    " websocket-client-coro");
                    }));

                // Perform the websocket handshake
                ws.handshake(host, "/");

                // Send the message
                ws.write(net::buffer(std::string(text)));

                /// only leaks if this is defined
#define LARGE_SIMULTANEOUS_CONNECTIONS
#ifdef LARGE_SIMULTANEOUS_CONNECTIONS
                while (!finished)
                {
                    std::this_thread::sleep_for(
                        std::chrono::milliseconds(1024));
                }
#endif   // LARGE_SIMULTANEOUS_CONNECTIONS

                /// this does nothing to change the nature of the leak
#ifdef GRACEFUL_SHUTDOWN
                // Close the WebSocket connection
                ws.close(websocket::close_code::normal);
#endif   // GRACEFUL_SHUTDOWN

                return EXIT_FAILURE;

                // If we get here then the connection is closed gracefully

                // The make_printable() function helps print a
                // ConstBufferSequence
            }
            catch (std::exception const &e)
            {
                std::cerr << "Error: " << e.what() << std::endl;
                return EXIT_FAILURE;
            }
        }).detach();

        // std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    printf("Finished\n");
    finished = true;

    while (1)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1024));
    }

    return EXIT_SUCCESS;
}

//]


text:
#pragma once

#include <polyfem/ElementBases.hpp>
#include <polyfem/Mesh2D.hpp>
#include <polyfem/LocalBoundary.hpp>
#include <polyfem/InterfaceData.hpp>
#include <polyfem/Navigation.hpp>

#include <polyfem/MeshNodes.hpp>

#include <Eigen/Dense>
#include <vector>

namespace polyfem
{
	class FEBasis2d
	{
	public:

		///
		/// @brief      Builds FE basis functions over the entire mesh (P1, P2 over triangles, Q1,
		///             Q2 over quads). Polygonal facets with > 4 vertices are dealt later on by the
		///             PolygonalBasis2d class.
		///
		/// @param[in]  mesh               The input surface mesh
		/// @param[in]  quadrature_order   The quadrature order
		/// @param[in]  discr_order        The order of the elements (1 or 2)
		/// @param[out] bases              List of basis functions per element
		/// @param[out] local_boundary     List of descriptor per element, indicating which edge of
		///                                the canonical elements lie on the boundary of the mesh
		/// @param[out] poly_edge_to_data  Data for edges at the interface with a polygon (used to
		///                                build the harmonics inside polygons)
		///
		/// @return     The number of basis functions created.
		///
		static int build_bases(
			const Mesh2D &mesh,
			const int quadrature_order,
			const int discr_order,
			const bool serendipity,
			const bool has_polys,
			const bool is_geom_bases,
			std::vector<ElementBases> &bases,
			std::vector<LocalBoundary> &local_boundary,
			std::map<int, InterfaceData> &poly_edge_to_data);

		static int build_bases(
			const Mesh2D &mesh,
			const int quadrature_order,
			const Eigen::VectorXi &discr_order,
			const bool serendipity,
			const bool has_polys,
			const bool is_geom_bases,
			std::vector<ElementBases> &bases,
			std::vector<LocalBoundary> &local_boundary,
			std::map<int, InterfaceData> &poly_edge_to_data);

		static Eigen::VectorXi tri_edge_local_nodes(const int p, const Mesh2D &mesh, Navigation::Index index);
		static Eigen::VectorXi quad_edge_local_nodes(const int q, const Mesh2D &mesh, Navigation::Index index);
	};
}

max_stars_repo_name: ldXiao/polyfem

max_issues_repo_name: ldXiao/polyfem

max_forks_repo_name: ldXiao/polyfem


text:
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 <boost/ut.hpp>

#include <mpp/mat.hpp>

#include "../include/utils.hpp"

using namespace boost::ut::literals;
using namespace boost::ut::bdd;
using namespace boost::ut;
using namespace mpp;

void test_iter_semantics(const auto& mat)
{
	auto begin  = mat.begin();
	auto cbegin = mat.cbegin();
	auto end    = mat.end() - 1;
	auto cend   = mat.cend() - 1;

	expect(*begin == 1);
	expect(*cbegin == 1);
	expect(*end == 6);
	expect(*cend == 6);

	auto begin_old  = begin++;
	auto cbegin_old = cbegin++;

	expect(*begin == 2);
	expect(*cbegin == 2);
	expect(*begin_old == 1);
	expect(*cbegin_old == 1);

	++begin_old;
	++cbegin_old;

	expect(begin == begin_old);
	expect(cbegin == cbegin_old);

	begin += 2;
	cbegin += 2;
	end -= 2;
	cend -= 2;

	expect(begin == end);
	expect(cbegin == cend);

	auto rbegin  = mat.rbegin();
	auto crbegin = mat.crbegin();
	auto rend    = mat.rend() - 1;
	auto crend   = mat.crend() - 1;

	expect(*rbegin == 6);
	expect(*crbegin == 6);
	expect(*rend == 1);
	expect(*crend == 1);

	auto begin_2 = mat.begin();
	begin_2 += { 1, 2 };
	expect(*begin_2 == 6);

	begin_2 -= { 1, 0 };
	expect(*begin_2 == 3);

	auto begin_3 = begin_2 + std::pair{ 0, 0 };
	expect(begin_3 == begin_2);
}

void test_iter_semantics_write(auto& mat)
{
	auto cbegin  = mat.cbegin();
	auto cend    = mat.cend() - 1;
	auto crbegin = mat.crbegin();
	auto crend   = mat.crend() - 1;

	expect(*cbegin == 1_i);
	expect(*cend == 6_i);
	expect(*crbegin == 6_i);
	expect(*crend == 1_i);

	auto begin  = mat.begin();
	auto end    = mat.end() - 1;
	auto rbegin = mat.rbegin();
	auto rend   = mat.rend() - 1;

	*begin = 2;
	*end   = 2;
	expect(*begin == 2);
	expect(*end == 2);

	*rbegin = 3;
	*rend   = 4;
	expect(*end == 3);
	expect(*begin == 4);
}

int main()
{
	const auto mats_types = all_mats<int, 0, 0>{};

	const auto range_2d = std::vector<std::vector<int>>{ { 1, 2, 3 }, { 4, 5, 6 } };
	const auto mats = std::tuple{ mat<int, std::array<int, 6>>{ range_2d }, mat<int, std::vector<int>>{ range_2d } };

	feature("Standard conforming iterators") = []<typename Mat>(std::type_identity<Mat>) {
		using mat_iter               = typename Mat::iterator;
		using mat_reverse_iter       = typename Mat::iterator;
		using mat_const_iter         = typename Mat::const_iterator;
		using mat_const_reverse_iter = typename Mat::const_reverse_iterator;

		given("Mutable and immutable iterators should meet contiguous_iterator") = [&]() {
			expect(constant<std::contiguous_iterator<mat_iter>>);
			expect(constant<std::contiguous_iterator<mat_const_iter>>);
		};

		given("Mutable and immutable reverse iterators should meet bidirectional_iterator") = [&]() {
			expect(constant<std::bidirectional_iterator<mat_reverse_iter>>);
			expect(constant<std::bidirectional_iterator<mat_const_reverse_iter>>);
		};

		given("Mutable iterators should meet output_iterator") = [&]() {
			expect(constant<std::output_iterator<mat_iter, int>>);
		};
	} | mats_types;

	feature("Iterator semantics") = [&]() {
		given("Mutable and immutable iterators should have right semantics") = [](const auto& mat) {
			test_iter_semantics(mat);
		} | mats;

		given("Mutable iterators should have right mutable semantics") = [](const auto& mat) {
			// Explicitly allow mutating because we're not actually writing through const_* version of iterators but the
			// test somehow always pass the matrix as a const object
			test_iter_semantics_write(mut(mat));
		} | mats;
	};

	return 0;
}


text:
//
// Boost.Pointer Container
//
//  Copyright Thorsten Ottosen 2003-2005. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//

#include "test_data.hpp"
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/progress.hpp>

using namespace boost;
using namespace std;

typedef shared_ptr<Base> PolyPtr;

struct PolyPtrOps
{
  void operator()( const PolyPtr& a )
    { a->foo(); }
};

struct less_than
{
    bool operator()( const PolyPtr& l, const PolyPtr& r ) const
    {
        return *l < *r;
    }

    bool operator()( const Base* l, const Base* r ) const
    {
        return *l < *r;
    }
};

struct greater_than
{
    bool operator()( const PolyPtr& l, const PolyPtr& r ) const
    {
        return *l > *r;
    }

    bool operator()( const Base* l, const Base* r ) const
    {
        return *l > *r;
    }
};

struct data_less_than
{
    bool operator()( const PolyPtr& l, const PolyPtr& r ) const
    {
        return l->data_less_than(*r);
    }

    bool operator()( const Base* l, const Base* r ) const
    {
        return l->data_less_than(*r);
    }
};

struct data_less_than2
{
    bool operator()( const PolyPtr& l, const PolyPtr& r ) const
    {
        return l->data_less_than2(*r);
    }

    bool operator()( const Base* l, const Base* r ) const
    {
        return l->data_less_than2(*r);
    }
};

void test_speed()
{
    enum { size = 50000 };
    vector<PolyPtr>   svec;
    ptr_vector<Base>  pvec;

    {
        progress_timer timer;
        for( int i = 0; i < size; ++i )
            svec.push_back( PolyPtr( new Derived ) );
        cout << "\n shared_ptr call new: ";
    }

    {
        progress_timer timer;
        for( int i = 0; i < size; ++i )
            pvec.push_back( new Derived );
        cout << "\n smart container call new: ";
    }

    {
        progress_timer timer;
        for_each( svec.begin(), svec.end(), PolyPtrOps() );
        cout << "\n shared_ptr call foo(): ";
    }

    {
        progress_timer timer;
        for_each( pvec.begin(), pvec.end(), mem_fun_ref( &Base::foo ) );
        cout << "\n smart container call foo(): ";
    }

    {
        progress_timer timer;
        sort( svec.begin(), svec.end(), less_than() );
        cout << "\n shared_ptr call sort(): ";
    }

    {
        progress_timer timer;
        sort( pvec.ptr_begin(), pvec.ptr_end(), less_than() );
        cout << "\n smart container call sort(): ";
    }

    {
        progress_timer timer;
        sort( svec.begin(), svec.end(), greater_than() );
        cout << "\n shared_ptr call sort() #2: ";
    }

    {
        progress_timer timer;
        sort( pvec.ptr_begin(), pvec.ptr_end(), greater_than() );
        cout << "\n smart container call sort() #2: ";
    }

    {
        progress_timer timer;
        sort( svec.begin(), svec.end(), data_less_than() );
        cout << "\n shared_ptr call sort() #3: ";
    }

    {
        progress_timer timer;
        sort( pvec.ptr_begin(), pvec.ptr_end(), data_less_than() );
        cout << "\n smart container call sort() #3: ";
    }

    {
        progress_timer timer;
        sort( svec.begin(), svec.end(), data_less_than2() );
        cout << "\n shared_ptr call sort() #4: ";
    }

    {
        progress_timer timer;
        sort( pvec.ptr_begin(), pvec.ptr_end(), data_less_than2() );
        cout << "\n smart container call sort() #4: ";
    }

     vector<Base*> copy1;
     for( ptr_vector<Base>::ptr_iterator i = pvec.ptr_begin(); i != pvec.ptr_end(); ++ i )
         copy1.push_back( *i );

     sort( pvec.ptr_begin(), pvec.ptr_end() );

    vector<Base*> copy2;
    for( ptr_vector<Base>::ptr_iterator i = pvec.ptr_begin(); i != pvec.ptr_end(); ++ i )
        copy2.push_back( *i );

    for( unsigned int i =  0; i < copy1.size(); ++i )
    {
        bool found = false;
        for( int j = 0; j < copy1.size(); ++ j )
            if( copy1[i] == copy2[j] )
                found = true;

        if( !found )
            cout << copy1[i] << endl;
    }

    BOOST_REQUIRE( pvec.size() == size );
    cout << endl;
}

#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;

test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" );

    test->add( BOOST_TEST_CASE( &test_speed ) );

    return test;
}