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

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code 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.

Daemon Source Code 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 Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

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

extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}

#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>

using namespace tinygettext;

DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary        trans_dict;
Dictionary        trans_dictgame;

cvar_t            *language;
cvar_t            *trans_encodings;
cvar_t            *trans_languages;
bool              enabled = false;
int               modificationCount=0;

#define _(x) Trans_Gettext(x)

/*
====================
Trans_ReturnLanguage

Return a loaded language. If desired language, return closest match.
If no languages are close, force English.
====================
*/
Language Trans_ReturnLanguage( const char *lang )
{
	int bestScore = 0;
	Language bestLang, language = Language::from_env( std::string( lang ) );

	std::set<Language> langs = trans_manager.get_languages();
	for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
	{
		int score = Language::match( language, *i );

		if( score > bestScore )
		{
			bestScore = score;
			bestLang = *i;
		}
	}

	// Return "en" if language not found
	if( !bestLang )
	{
		Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"),
					language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(),
					lang );
		bestLang = Language::from_env( "en" );
	}

	return bestLang;
}

extern "C" void Trans_UpdateLanguage_f( void )
{
	Language lang = Trans_ReturnLanguage( language->string );
	trans_dict = trans_manager.get_dictionary( lang );
	trans_dictgame = trans_managergame.get_dictionary( lang );
	Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() );
}

/*
============
Trans_Init
============
*/
extern "C" void Trans_Init( void )
{
	char                **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];
	int                 numPoFiles, i;
	FL_Locale           *locale;
	std::set<Language>  langs;
	Language            lang;

	language = Cvar_Get( "language", "", CVAR_ARCHIVE );
	trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
	trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM );

	// Only detect locale if no previous language set.
	if( !language->string[0] )
	{
		FL_FindLocale( &locale, FL_MESSAGES );

		// Invalid or not found. Just use builtin language.
		if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
		{
			Cvar_Set( "language", "en" );
		}
		else
		{
			Cvar_Set( "language", va( "%s_%s", locale->lang, locale->country ) );
		}
	}

	poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );

	// This assumes that the filenames in both folders are the same
	for( i = 0; i < numPoFiles; i++ )
	{
		int ret;
		Dictionary *dict1;
		Dictionary *dict2;
		char *buffer, language[ 6 ];

		if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
		{
			dict1 = new Dictionary();
			COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
			std::stringstream ss( buffer );
			trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
			FS_FreeFile( buffer );
		}
		else
		{
			Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] );
		}

		if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
		{
			dict2 = new Dictionary();
			COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
			std::stringstream ss( buffer );
			trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
			FS_FreeFile( buffer );
		}
		else
		{
			Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] );
		}
	}
	FS_FreeFileList( poFiles );
	langs = trans_manager.get_languages();
	for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
	{
		Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
		Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(),
												  p->get_country().c_str()[0] ? "_" : "",
												  p->get_country().c_str() ) );
	}
	Cvar_Set( "trans_languages", langList );
	Cvar_Set( "trans_encodings", encList );
	Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() );
	Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );

	lang = Trans_ReturnLanguage( language->string );
	trans_dict = trans_manager.get_dictionary( lang );
	trans_dictgame = trans_managergame.get_dictionary( lang );
	enabled = true;
}

extern "C" const char* Trans_Gettext( const char *msgid )
{
	if( !enabled ) { return msgid; }
	return trans_dict.translate( std::string( msgid ) ).c_str();
}

extern "C" const char* Trans_GettextGame( const char *msgid )
{
	if( !enabled ) { return msgid; }
	return trans_dictgame.translate( std::string( msgid ) ).c_str();
}

extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
	if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
	return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}

extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
	if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
	return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<commit_msg>Fix case where only a language is detected, but no country<commit_after>/*
===========================================================================

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code 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.

Daemon Source Code 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 Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

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

extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}

#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>

using namespace tinygettext;

DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary        trans_dict;
Dictionary        trans_dictgame;

cvar_t            *language;
cvar_t            *trans_encodings;
cvar_t            *trans_languages;
bool              enabled = false;
int               modificationCount=0;

#define _(x) Trans_Gettext(x)

/*
====================
Trans_ReturnLanguage

Return a loaded language. If desired language, return closest match.
If no languages are close, force English.
====================
*/
Language Trans_ReturnLanguage( const char *lang )
{
	int bestScore = 0;
	Language bestLang, language = Language::from_env( std::string( lang ) );

	std::set<Language> langs = trans_manager.get_languages();
	for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
	{
		int score = Language::match( language, *i );

		if( score > bestScore )
		{
			bestScore = score;
			bestLang = *i;
		}
	}

	// Return "en" if language not found
	if( !bestLang )
	{
		Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"),
					language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(),
					lang );
		bestLang = Language::from_env( "en" );
	}

	return bestLang;
}

extern "C" void Trans_UpdateLanguage_f( void )
{
	Language lang = Trans_ReturnLanguage( language->string );
	trans_dict = trans_manager.get_dictionary( lang );
	trans_dictgame = trans_managergame.get_dictionary( lang );
	Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() );
}

/*
============
Trans_Init
============
*/
extern "C" void Trans_Init( void )
{
	char                **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];
	int                 numPoFiles, i;
	FL_Locale           *locale;
	std::set<Language>  langs;
	Language            lang;

	language = Cvar_Get( "language", "", CVAR_ARCHIVE );
	trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
	trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM );

	// Only detect locale if no previous language set.
	if( !language->string[0] )
	{
		FL_FindLocale( &locale, FL_MESSAGES );

		// Invalid or not found. Just use builtin language.
		if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
		{
			Cvar_Set( "language", "en" );
		}
		else
		{
			Cvar_Set( "language", va( "%s%s%s", locale->lang,
									  locale->country[0] ? "_" : "",
									  locale->country ) );
		}
	}

	poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );

	// This assumes that the filenames in both folders are the same
	for( i = 0; i < numPoFiles; i++ )
	{
		int ret;
		Dictionary *dict1;
		Dictionary *dict2;
		char *buffer, language[ 6 ];

		if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
		{
			dict1 = new Dictionary();
			COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
			std::stringstream ss( buffer );
			trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
			FS_FreeFile( buffer );
		}
		else
		{
			Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] );
		}

		if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
		{
			dict2 = new Dictionary();
			COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
			std::stringstream ss( buffer );
			trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
			FS_FreeFile( buffer );
		}
		else
		{
			Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] );
		}
	}
	FS_FreeFileList( poFiles );
	langs = trans_manager.get_languages();
	for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
	{
		Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
		Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(),
												  p->get_country().c_str()[0] ? "_" : "",
												  p->get_country().c_str() ) );
	}
	Cvar_Set( "trans_languages", langList );
	Cvar_Set( "trans_encodings", encList );
	Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() );
	Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );

	lang = Trans_ReturnLanguage( language->string );
	trans_dict = trans_manager.get_dictionary( lang );
	trans_dictgame = trans_managergame.get_dictionary( lang );
	enabled = true;
}

extern "C" const char* Trans_Gettext( const char *msgid )
{
	if( !enabled ) { return msgid; }
	return trans_dict.translate( std::string( msgid ) ).c_str();
}

extern "C" const char* Trans_GettextGame( const char *msgid )
{
	if( !enabled ) { return msgid; }
	return trans_dictgame.translate( std::string( msgid ) ).c_str();
}

extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
	if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
	return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}

extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
	if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
	return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
#endif

#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>

#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>

// Path compound #####################################################################################################

DEF_STD_CMD_A(CmdPathCompound);

CmdPathCompound::CmdPathCompound()
    :Command("Path_Compound")
{
    sAppModule      = "Path";
    sGroup          = QT_TR_NOOP("Path");
    sMenuText       = QT_TR_NOOP("Compound");
    sToolTipText    = QT_TR_NOOP("Creates a compound from selected paths");
    sWhatsThis      = "Path_Compound";
    sStatusTip      = sToolTipText;
    sPixmap         = "Path-Compound";
    sAccel          = "P,C";

}

void CmdPathCompound::activated(int iMsg)
{
    std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
    if (Sel.size() > 0) {
        std::ostringstream cmd;
        cmd << "[";
        Path::Feature *pcPathObject;
        for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
            if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
                pcPathObject = dynamic_cast<Path::Feature*>((*it).pObject);
                cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
            } else {
                Base::Console().Error("Only Path objects must be selected before running this command\n");
                return;
            }
        }
        cmd << "]";
        std::string FeatName = getUniqueObjectName("PathCompound");
        openCommand("Create Path Compound");
        doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
        doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
        commitCommand();
        updateActive();
    } else {
        Base::Console().Error("At least one Path object must be selected\n");
        return;
    }
}

bool CmdPathCompound::isActive(void)
{
    return hasActiveDocument();
}

 // Path Shape #####################################################################################################

DEF_STD_CMD_A(CmdPathShape);

CmdPathShape::CmdPathShape()
    :Command("Path_Shape")
{
    sAppModule      = "Path";
    sGroup          = QT_TR_NOOP("Path");
    sMenuText       = QT_TR_NOOP("From Shape");
    sToolTipText    = QT_TR_NOOP("Creates a path from a selected shape");
    sWhatsThis      = "Path_Shape";
    sStatusTip      = sToolTipText;
    sPixmap         = "Path-Shape";
    sAccel          = "P,S";
}

void CmdPathShape::activated(int iMsg)
{
    std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
    if (Sel.size() == 1) {
        if (Sel[0].pObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
            Part::Feature *pcPartObject = dynamic_cast<Part::Feature*>(Sel[0].pObject);
            std::string FeatName = getUniqueObjectName("PathShape");
            openCommand("Create Path Compound");
            doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
            doCommand(Doc,"FreeCAD.activeDocument().%s.Shape = FreeCAD.activeDocument().%s.Shape.copy()",FeatName.c_str(),pcPartObject->getNameInDocument());
            commitCommand();
            updateActive();
        } else {
            Base::Console().Error("Exactly one shape object must be selected\n");
            return;
        }
    } else {
        Base::Console().Error("Exactly one shape object must be selected\n");
        return;
    }
}

bool CmdPathShape::isActive(void)
{
    return hasActiveDocument();
}

void CreatePathCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
    rcCmdMgr.addCommand(new CmdPathCompound());
    rcCmdMgr.addCommand(new CmdPathShape());
}
<commit_msg>fix Coverity issues<commit_after>/***************************************************************************
 *   Copyright (c) Yorik van Havre (yorik@uncreated.net) 2014              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
#endif

#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>

#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>

// Path compound #####################################################################################################

DEF_STD_CMD_A(CmdPathCompound)

CmdPathCompound::CmdPathCompound()
    :Command("Path_Compound")
{
    sAppModule      = "Path";
    sGroup          = QT_TR_NOOP("Path");
    sMenuText       = QT_TR_NOOP("Compound");
    sToolTipText    = QT_TR_NOOP("Creates a compound from selected paths");
    sWhatsThis      = "Path_Compound";
    sStatusTip      = sToolTipText;
    sPixmap         = "Path-Compound";
    sAccel          = "P,C";

}

void CmdPathCompound::activated(int iMsg)
{
    std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
    if (Sel.size() > 0) {
        std::ostringstream cmd;
        cmd << "[";
        Path::Feature *pcPathObject;
        for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
            if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
                pcPathObject = static_cast<Path::Feature*>((*it).pObject);
                cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
            } else {
                Base::Console().Error("Only Path objects must be selected before running this command\n");
                return;
            }
        }
        cmd << "]";
        std::string FeatName = getUniqueObjectName("PathCompound");
        openCommand("Create Path Compound");
        doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
        doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
        commitCommand();
        updateActive();
    } else {
        Base::Console().Error("At least one Path object must be selected\n");
        return;
    }
}

bool CmdPathCompound::isActive(void)
{
    return hasActiveDocument();
}

 // Path Shape #####################################################################################################

DEF_STD_CMD_A(CmdPathShape)

CmdPathShape::CmdPathShape()
    :Command("Path_Shape")
{
    sAppModule      = "Path";
    sGroup          = QT_TR_NOOP("Path");
    sMenuText       = QT_TR_NOOP("From Shape");
    sToolTipText    = QT_TR_NOOP("Creates a path from a selected shape");
    sWhatsThis      = "Path_Shape";
    sStatusTip      = sToolTipText;
    sPixmap         = "Path-Shape";
    sAccel          = "P,S";
}

void CmdPathShape::activated(int iMsg)
{
    std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
    if (Sel.size() == 1) {
        if (Sel[0].pObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
            Part::Feature *pcPartObject = static_cast<Part::Feature*>(Sel[0].pObject);
            std::string FeatName = getUniqueObjectName("PathShape");
            openCommand("Create Path Compound");
            doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
            doCommand(Doc,"FreeCAD.activeDocument().%s.Shape = FreeCAD.activeDocument().%s.Shape.copy()",FeatName.c_str(),pcPartObject->getNameInDocument());
            commitCommand();
            updateActive();
        } else {
            Base::Console().Error("Exactly one shape object must be selected\n");
            return;
        }
    } else {
        Base::Console().Error("Exactly one shape object must be selected\n");
        return;
    }
}

bool CmdPathShape::isActive(void)
{
    return hasActiveDocument();
}

void CreatePathCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
    rcCmdMgr.addCommand(new CmdPathCompound());
    rcCmdMgr.addCommand(new CmdPathShape());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableConnectionData.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:28:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

using namespace dbaui;
using namespace comphelper;
//==================================================================
// class OTableConnectionData
//==================================================================
DBG_NAME(OTableConnectionData)
TYPEINIT0(OTableConnectionData);
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData()
{
    DBG_CTOR(OTableConnectionData,NULL);
    Init();
}

//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const String& rSourceWinName, const String& rDestWinName, const String& rConnName )
    :m_aSourceWinName( rSourceWinName )
    ,m_aDestWinName( rDestWinName )
    ,m_aConnName( rConnName )
{
    DBG_CTOR(OTableConnectionData,NULL);
    Init();
}

//------------------------------------------------------------------------
void OTableConnectionData::Init()
{
    //////////////////////////////////////////////////////////////////////
    // LineDataList mit Defaults initialisieren
    DBG_ASSERT(m_vConnLineData.size() == 0, "OTableConnectionData::Init() : nur mit leere Linienliste aufzurufen !");
    ResetConnLines(TRUE);
        // das legt Defaults an
}

//------------------------------------------------------------------------
void OTableConnectionData::Init(const String& rSourceWinName, const String& rDestWinName, const String& rConnName)
{
    // erst mal alle LineDatas loeschen
    OConnectionLineDataVec().swap(m_vConnLineData);
    // dann die Strings
    m_aSourceWinName = rSourceWinName;
    m_aDestWinName = rDestWinName;
    m_aConnName = rConnName;

    // den Rest erledigt das andere Init
    Init();
}

//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const OTableConnectionData& rConnData )
{
    DBG_CTOR(OTableConnectionData,NULL);
    *this = rConnData;
}

//------------------------------------------------------------------------
void OTableConnectionData::CopyFrom(const OTableConnectionData& rSource)
{
    *this = rSource;
    // hier ziehe ich mich auf das (nicht-virtuelle) operator= zurueck, das nur meine Members kopiert
}

//------------------------------------------------------------------------
OTableConnectionData::~OTableConnectionData()
{
    DBG_DTOR(OTableConnectionData,NULL);
    // LineDataList loeschen
    ResetConnLines(FALSE);
}

//------------------------------------------------------------------------
OTableConnectionData& OTableConnectionData::operator=( const OTableConnectionData& rConnData )
{
    if (&rConnData == this)
        return *this;

    m_aSourceWinName = rConnData.GetSourceWinName();
    m_aDestWinName = rConnData.GetDestWinName();
    m_aConnName = rConnData.GetConnName();

    // clear line list
    ResetConnLines(FALSE);

    // und kopieren
    OConnectionLineDataVec* pLineData = const_cast<OTableConnectionData*>(&rConnData)->GetConnLineDataList();

    OConnectionLineDataVec::const_iterator aIter = pLineData->begin();
    for(;aIter != pLineData->end();++aIter)
        m_vConnLineData.push_back(new OConnectionLineData(**aIter));

    return *this;
}

//------------------------------------------------------------------------
BOOL OTableConnectionData::SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName )
{
    if (USHORT(m_vConnLineData.size()) < nIndex)
        return FALSE;
        // == ist noch erlaubt, das entspricht einem Append

    if (m_vConnLineData.size() == nIndex)
        return AppendConnLine(rSourceFieldName, rDestFieldName);

    OConnectionLineDataRef pConnLineData = m_vConnLineData[nIndex];
    DBG_ASSERT(pConnLineData != NULL, "OTableConnectionData::SetConnLine : habe ungueltiges LineData-Objekt");

    pConnLineData->SetSourceFieldName( rSourceFieldName );
    pConnLineData->SetDestFieldName( rDestFieldName );

    return TRUE;
}

//------------------------------------------------------------------------
BOOL OTableConnectionData::AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName )
{
    OConnectionLineDataVec::iterator aIter = m_vConnLineData.begin();
    for(;aIter != m_vConnLineData.end();++aIter)
    {
        if((*aIter)->GetDestFieldName() == rDestFieldName && (*aIter)->GetSourceFieldName() == rSourceFieldName)
            break;
    }
    if(aIter == m_vConnLineData.end())
    {
        OConnectionLineDataRef pNew = new OConnectionLineData(rSourceFieldName, rDestFieldName);
        if (!pNew.isValid())
            return FALSE;

        m_vConnLineData.push_back(pNew);
    }
    return TRUE;
}

//------------------------------------------------------------------------
void OTableConnectionData::ResetConnLines( BOOL bUseDefaults )
{
    OConnectionLineDataVec().swap(m_vConnLineData);

    if (bUseDefaults)
    {
        for (USHORT i=0; i<MAX_CONN_COUNT; i++)
            m_vConnLineData.push_back( new OConnectionLineData());
    }
}

//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj()
{
    return new OConnectionLineData();
}

//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj( const OConnectionLineData& rConnLineData )
{
    return new OConnectionLineData( rConnLineData );
}
// -----------------------------------------------------------------------------
OTableConnectionData* OTableConnectionData::NewInstance() const
{
    return new OTableConnectionData();
}
// -----------------------------------------------------------------------------
void OTableConnectionData::normalizeLines()
{
    // noch ein wenig Normalisierung auf den LineDatas : leere Lines vom Anfang an das Ende verschieben
    sal_Int32 nCount = m_vConnLineData.size();
    for(sal_Int32 i=0;i<nCount;)
    {
        if(!m_vConnLineData[i]->GetSourceFieldName().getLength() && !m_vConnLineData[i]->GetDestFieldName().getLength())
        {
            OConnectionLineDataRef pData = m_vConnLineData[i];
            m_vConnLineData.erase(m_vConnLineData.begin()+i);
            m_vConnLineData.push_back(pData);
            --nCount;
        }
        else
            ++i;
    }
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba204b (1.7.12); FILE MERGED 2006/07/11 05:26:26 oj 1.7.12.1: #i67034# call swap directly<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableConnectionData.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-26 07:49:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

using namespace dbaui;
using namespace comphelper;
//==================================================================
// class OTableConnectionData
//==================================================================
DBG_NAME(OTableConnectionData)
TYPEINIT0(OTableConnectionData);
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData()
{
    DBG_CTOR(OTableConnectionData,NULL);
    Init();
}

//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const String& rSourceWinName, const String& rDestWinName, const String& rConnName )
    :m_aSourceWinName( rSourceWinName )
    ,m_aDestWinName( rDestWinName )
    ,m_aConnName( rConnName )
{
    DBG_CTOR(OTableConnectionData,NULL);
    Init();
}

//------------------------------------------------------------------------
void OTableConnectionData::Init()
{
    //////////////////////////////////////////////////////////////////////
    // LineDataList mit Defaults initialisieren
    DBG_ASSERT(m_vConnLineData.size() == 0, "OTableConnectionData::Init() : nur mit leere Linienliste aufzurufen !");
    ResetConnLines(TRUE);
        // das legt Defaults an
}

//------------------------------------------------------------------------
void OTableConnectionData::Init(const String& rSourceWinName, const String& rDestWinName, const String& rConnName)
{
    // erst mal alle LineDatas loeschen
    OConnectionLineDataVec().swap(m_vConnLineData);
    // dann die Strings
    m_aSourceWinName = rSourceWinName;
    m_aDestWinName = rDestWinName;
    m_aConnName = rConnName;

    // den Rest erledigt das andere Init
    Init();
}

//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const OTableConnectionData& rConnData )
{
    DBG_CTOR(OTableConnectionData,NULL);
    *this = rConnData;
}

//------------------------------------------------------------------------
void OTableConnectionData::CopyFrom(const OTableConnectionData& rSource)
{
    *this = rSource;
    // hier ziehe ich mich auf das (nicht-virtuelle) operator= zurueck, das nur meine Members kopiert
}

//------------------------------------------------------------------------
OTableConnectionData::~OTableConnectionData()
{
    DBG_DTOR(OTableConnectionData,NULL);
    // LineDataList loeschen
    OConnectionLineDataVec().swap(m_vConnLineData);
    //ResetConnLines(FALSE);
}

//------------------------------------------------------------------------
OTableConnectionData& OTableConnectionData::operator=( const OTableConnectionData& rConnData )
{
    if (&rConnData == this)
        return *this;

    m_aSourceWinName = rConnData.GetSourceWinName();
    m_aDestWinName = rConnData.GetDestWinName();
    m_aConnName = rConnData.GetConnName();

    // clear line list
    ResetConnLines(FALSE);

    // und kopieren
    OConnectionLineDataVec* pLineData = const_cast<OTableConnectionData*>(&rConnData)->GetConnLineDataList();

    OConnectionLineDataVec::const_iterator aIter = pLineData->begin();
    for(;aIter != pLineData->end();++aIter)
        m_vConnLineData.push_back(new OConnectionLineData(**aIter));

    return *this;
}

//------------------------------------------------------------------------
BOOL OTableConnectionData::SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName )
{
    if (USHORT(m_vConnLineData.size()) < nIndex)
        return FALSE;
        // == ist noch erlaubt, das entspricht einem Append

    if (m_vConnLineData.size() == nIndex)
        return AppendConnLine(rSourceFieldName, rDestFieldName);

    OConnectionLineDataRef pConnLineData = m_vConnLineData[nIndex];
    DBG_ASSERT(pConnLineData != NULL, "OTableConnectionData::SetConnLine : habe ungueltiges LineData-Objekt");

    pConnLineData->SetSourceFieldName( rSourceFieldName );
    pConnLineData->SetDestFieldName( rDestFieldName );

    return TRUE;
}

//------------------------------------------------------------------------
BOOL OTableConnectionData::AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName )
{
    OConnectionLineDataVec::iterator aIter = m_vConnLineData.begin();
    for(;aIter != m_vConnLineData.end();++aIter)
    {
        if((*aIter)->GetDestFieldName() == rDestFieldName && (*aIter)->GetSourceFieldName() == rSourceFieldName)
            break;
    }
    if(aIter == m_vConnLineData.end())
    {
        OConnectionLineDataRef pNew = new OConnectionLineData(rSourceFieldName, rDestFieldName);
        if (!pNew.isValid())
            return FALSE;

        m_vConnLineData.push_back(pNew);
    }
    return TRUE;
}

//------------------------------------------------------------------------
void OTableConnectionData::ResetConnLines( BOOL bUseDefaults )
{
    OConnectionLineDataVec().swap(m_vConnLineData);

    if (bUseDefaults)
    {
        for (USHORT i=0; i<MAX_CONN_COUNT; i++)
            m_vConnLineData.push_back( new OConnectionLineData());
    }
}

//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj()
{
    return new OConnectionLineData();
}

//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj( const OConnectionLineData& rConnLineData )
{
    return new OConnectionLineData( rConnLineData );
}
// -----------------------------------------------------------------------------
OTableConnectionData* OTableConnectionData::NewInstance() const
{
    return new OTableConnectionData();
}
// -----------------------------------------------------------------------------
void OTableConnectionData::normalizeLines()
{
    // noch ein wenig Normalisierung auf den LineDatas : leere Lines vom Anfang an das Ende verschieben
    sal_Int32 nCount = m_vConnLineData.size();
    for(sal_Int32 i=0;i<nCount;)
    {
        if(!m_vConnLineData[i]->GetSourceFieldName().getLength() && !m_vConnLineData[i]->GetDestFieldName().getLength())
        {
            OConnectionLineDataRef pData = m_vConnLineData[i];
            m_vConnLineData.erase(m_vConnLineData.begin()+i);
            m_vConnLineData.push_back(pData);
            --nCount;
        }
        else
            ++i;
    }
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"

#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/cc/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/core/frame_buffer_c_api.h"

namespace tflite {
namespace task {
namespace vision {
namespace {

using ::tflite::task::JoinPath;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
    "mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";

ImageData LoadImage(const char* image_name) {
  return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
                                      kTestDataDirectory, image_name).data());
}

TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
//   ImageClassifierOptions *options = ImageClassifierOptionsCreate();

  ImageClassifier *image_classifier = ImageClassifierFromFile("");
  ASSERT_EQ(image_classifier, nullptr);
}

TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
  ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data());
  EXPECT_NE(image_classifier, nullptr);
  ImageClassifierDelete(image_classifier);
}

TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
  ImageClassifierOptions *options = ImageClassifierOptionsCreate();
  ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
  ASSERT_EQ(image_classifier, nullptr);
}

TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
  ImageClassifierOptions *options = ImageClassifierOptionsCreate();
  const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data();

  ImageClassifierOptionsSetModelFilePath(options, model_path);
  ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
  EXPECT_NE(image_classifier, nullptr);
  ImageClassifierDelete(image_classifier);
}

class ImageClassifierClassifyTest : public ::testing::Test {
 protected:
  void SetUp() override {
     image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data());
     ASSERT_NE(image_classifier, nullptr);
  }

  void TearDown() override {
     ImageClassifierDelete(image_classifier);
  }

  ImageClassifier *image_classifier;
};

TEST_F(ImageClassifierClassifyTest, SucceedsWithModelPath) {
  struct ImageData image_data = LoadImage("burger-224.png");

  struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
                                     .dimension.height = image_data.width,
                                     .plane.buffer = image_data.pixel_data,
                                     .plane.stride.row_stride_bytes = image_data.width  * image_data.channels,
                                     .plane.stride.pixel_stride_bytes = image_data.channels,
                                     .format = kRGB};

  struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);

  ImageDataFree(&image_data);

  ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
  EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
  EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
  EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
  EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";

  ImageClassifierClassificationResultDelete(classification_result);
}

}  // namespace
}  // namespace vision
}  // namespace task
}  // namespace tflite
<commit_msg>Fixed Typo in code<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"

#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/cc/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/core/frame_buffer_c_api.h"

namespace tflite {
namespace task {
namespace vision {
namespace {

using ::tflite::task::JoinPath;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
    "mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";

ImageData LoadImage(const char* image_name) {
  return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
                                      kTestDataDirectory, image_name).data());
}

TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
//   ImageClassifierOptions *options = ImageClassifierOptionsCreate();

  ImageClassifier *image_classifier = ImageClassifierFromFile("");
  ASSERT_EQ(image_classifier, nullptr);
}

TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
  ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data());
  EXPECT_NE(image_classifier, nullptr);
  ImageClassifierDelete(image_classifier);
}

TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
  ImageClassifierOptions *options = ImageClassifierOptionsCreate();
  ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
  ASSERT_EQ(image_classifier, nullptr);
}

TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
  ImageClassifierOptions *options = ImageClassifierOptionsCreate();
  const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data();

  ImageClassifierOptionsSetModelFilePath(options, model_path);
  ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
  EXPECT_NE(image_classifier, nullptr);
  ImageClassifierDelete(image_classifier);
}

class ImageClassifierClassifyTest : public ::testing::Test {
 protected:
  void SetUp() override {
     image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
               kMobileNetQuantizedWithMetadata).data());
     ASSERT_NE(image_classifier, nullptr);
  }

  void TearDown() override {
     ImageClassifierDelete(image_classifier);
  }

  ImageClassifier *image_classifier;
};

TEST_F(ImageClassifierClassifyTest, SucceedsWithModelPath) {
  struct ImageData image_data = LoadImage("burger-224.png");

  struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
                                     .dimension.height = image_data.height,
                                     .plane.buffer = image_data.pixel_data,
                                     .plane.stride.row_stride_bytes = image_data.width  * image_data.channels,
                                     .plane.stride.pixel_stride_bytes = image_data.channels,
                                     .format = kRGB};

  struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);

  ImageDataFree(&image_data);

  ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
  EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
  EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
  EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
  EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";

  ImageClassifierClassificationResultDelete(classification_result);
}

}  // namespace
}  // namespace vision
}  // namespace task
}  // namespace tflite
<|endoftext|>


<commit_before>#ifndef MeanshiftClusteringFilter_hxx_
#define MeanshiftClusteringFilter_hxx_

#include "itkNumericTraits.h"

#include "MeanshiftClusteringFilter.h"

namespace gth818n
{

  template< typename TCoordRep, unsigned int NPointDimension >
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::MeanshiftClusteringFilter()
  {
    m_epoch = 2;
    m_inputPointSet = 0;
    m_seedPoints = 0;

    m_numberOfMSIteration = 100;

    m_radius = 3.0;
    m_allDone = false;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::update()
  {
    // //dbg
    // std::cout<<"_constructKdTree..."<<std::flush;
    // //dbg, end
    _constructKdTree();
    // //dbg
    // std::cout<<"done"<<std::endl<<std::flush;
    // //dbg, end

    if (!m_seedPoints)
      {
        _constructSeedPoints();
      }

    _meanshiftIteration();

    _findUniqueCenters();

    _findLabelOfPoints();

    m_allDone = true;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setRadius(RealType rad)
  {
    if (rad <= 0.0)
      {
        std::cerr<<"Error: rad should > 0, but got "<<rad<<std::endl;
        abort();
      }

    m_radius = rad;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setEpoch(int epoch)
  {
    if (epoch < 0)
      {
        std::cerr<<"Error: epoch should >= 0, but got "<<epoch<<std::endl;
        abort();
      }

    m_epoch = epoch;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructKdTree()
  {
    m_treeGenerator = TreeGeneratorType::New();
    m_treeGenerator->SetSample( m_inputPointSet );
    m_treeGenerator->SetBucketSize( 16 );
    m_treeGenerator->Update();

    m_tree = m_treeGenerator->GetOutput();

    // VectorType queryPoint;
    // queryPoint[0] = 10.0;
    // queryPoint[1] = 7.0;

    // // K-Neighbor search
    // std::cout << "K-Neighbor search:" << std::endl;
    // unsigned int numberOfNeighbors = 3;
    // typename TreeType::InstanceIdentifierVectorType neighbors;
    // m_tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;

    // for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
    //   {
    //     std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
    //   }

    // // Radius search
    // std::cout << "Radius search:" << std::endl;
    // double radius = 4.0;
    // m_tree->Search( queryPoint, radius, neighbors ) ;
    // std::cout << "There are " << neighbors.size() << " neighbors." << std::endl;
    // for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
    //   {
    //     std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
    //   }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_computeInputPointRange()
  {
    VectorType inputPointSetMin;
    inputPointSetMin.Fill(itk::NumericTraits< RealType >::max());

    VectorType inputPointSetMax;
    inputPointSetMax.Fill(itk::NumericTraits< RealType >::min());

    for (long itp = 0; itp < m_inputPointSet->Size(); ++itp)
      {
        VectorType thisPoint = m_inputPointSet->GetMeasurementVector(itp);

        for (unsigned int idim = 0; idim < NPointDimension; ++idim)
          {
            inputPointSetMin[idim] = inputPointSetMin[idim]<thisPoint[idim]?inputPointSetMin[idim]:thisPoint[idim];
            inputPointSetMax[idim] = inputPointSetMax[idim]<thisPoint[idim]?inputPointSetMax[idim]:thisPoint[idim];
          }
      }

    m_inputPointSetRange = inputPointSetMax - inputPointSetMin;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_meanshiftIteration()
  {
    VectorType queryPoint;
    typename TreeType::InstanceIdentifierVectorType neighbors;

    for (long it = 0; it < m_numberOfMSIteration; ++it)
      {
        for (long itp = 0; itp < m_seedPoints->Size(); ++itp)
          {
            queryPoint = m_seedPoints->GetMeasurementVector(itp);
            m_tree->Search( queryPoint, m_radius, neighbors ) ;

            VectorType newPosition;
            newPosition.Fill(0);

            for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
              {
                newPosition += m_tree->GetMeasurementVector( neighbors[i] );
                //std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
              }

            newPosition /= static_cast<RealType>(neighbors.size());

            m_seedPoints->SetMeasurementVector(itp, newPosition);

            /// If relative increamental is small enough, break
            VectorType del = queryPoint - newPosition;
            for (unsigned int idim = 0; idim < NPointDimension; ++idim)
              {
                del[idim] /= m_inputPointSetRange[idim];
              }

            if (del.GetNorm() < 1e-1)
              {
                break;
              }
          }
      }

    if (m_epoch)
      {
        MeanshiftClusteringFilter<TCoordRep, NPointDimension> ms;
        ms.setInputPointSet(m_seedPoints);
        ms.setEpoch(--m_epoch);
        ms.update();
        m_seedPoints = ms._getSeedPoints();
      }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_getSeedPoints()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_seedPoints;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getCenters()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_centers;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findUniqueCenters()
  {
    m_centers = VectorSampleType::New();
    m_centers->PushBack( m_seedPoints->GetMeasurementVector(0) );

    for (unsigned int i = 1 ; i < m_seedPoints->Size() ; ++i )
      {
        const VectorType& newCenterCandidate = m_seedPoints->GetMeasurementVector(i);
        bool IAmNotCloseToAnyExistingCenter = true;

        for (unsigned int ii = 0 ; ii < m_centers->Size() ; ++ii )
          {
            VectorType distVector = newCenterCandidate - m_centers->GetMeasurementVector(ii);
            if (distVector.GetNorm() < m_radius )
              {
                IAmNotCloseToAnyExistingCenter = false;
                break;
              }
          }

        if (IAmNotCloseToAnyExistingCenter)
          {
            m_centers->PushBack( newCenterCandidate );
          }
      }

    m_numberOfModes = m_centers->Size();

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  std::vector<long>
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getLabelOfPoints()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_labelOfPoints;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findLabelOfPoints()
  {
    typename TreeGeneratorType::Pointer newTreeGen = TreeGeneratorType::New();
    newTreeGen->SetSample( m_centers );
    newTreeGen->SetBucketSize( 16 );
    newTreeGen->Update();
    typename TreeType::Pointer newTree = newTreeGen->GetOutput();

    m_labelOfPoints.resize(m_inputPointSet->Size());

    // K-Neighbor search
    //std::cout << "K-Neighbor search:" << std::endl;
    unsigned int numberOfNeighbors = 1;
    typename TreeType::InstanceIdentifierVectorType neighbors;

    for (unsigned int i = 0 ; i < m_seedPoints->Size() ; ++i )
      {
        const VectorType& queryPoint = m_seedPoints->GetMeasurementVector(i);
        newTree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
        m_labelOfPoints[i] = static_cast<long>(neighbors[0]);
      }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructSeedPoints()
  {
    /// Duplicate input points as seed points
    m_seedPoints = VectorSampleType::New();
    m_seedPoints->Resize(m_inputPointSet->Size() );

    for (unsigned int i = 0 ; i < m_inputPointSet->Size() ; ++i )
      {
        m_seedPoints->SetMeasurementVector( i, m_inputPointSet->GetMeasurementVector(i) );
      }

    return;
  }

}// namespace gth818n

#endif
<commit_msg>Fixed signed/unsigned comparison warning Merge branch 'develop'<commit_after>#ifndef MeanshiftClusteringFilter_hxx_
#define MeanshiftClusteringFilter_hxx_

#include "itkNumericTraits.h"

#include "MeanshiftClusteringFilter.h"

namespace gth818n
{

  template< typename TCoordRep, unsigned int NPointDimension >
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::MeanshiftClusteringFilter()
  {
    m_epoch = 2;
    m_inputPointSet = 0;
    m_seedPoints = 0;

    m_numberOfMSIteration = 100;

    m_radius = 3.0;
    m_allDone = false;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::update()
  {
    // //dbg
    // std::cout<<"_constructKdTree..."<<std::flush;
    // //dbg, end
    _constructKdTree();
    // //dbg
    // std::cout<<"done"<<std::endl<<std::flush;
    // //dbg, end

    if (!m_seedPoints)
      {
        _constructSeedPoints();
      }

    _meanshiftIteration();

    _findUniqueCenters();

    _findLabelOfPoints();

    m_allDone = true;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setRadius(RealType rad)
  {
    if (rad <= 0.0)
      {
        std::cerr<<"Error: rad should > 0, but got "<<rad<<std::endl;
        abort();
      }

    m_radius = rad;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setEpoch(int epoch)
  {
    if (epoch < 0)
      {
        std::cerr<<"Error: epoch should >= 0, but got "<<epoch<<std::endl;
        abort();
      }

    m_epoch = epoch;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructKdTree()
  {
    m_treeGenerator = TreeGeneratorType::New();
    m_treeGenerator->SetSample( m_inputPointSet );
    m_treeGenerator->SetBucketSize( 16 );
    m_treeGenerator->Update();

    m_tree = m_treeGenerator->GetOutput();

    // VectorType queryPoint;
    // queryPoint[0] = 10.0;
    // queryPoint[1] = 7.0;

    // // K-Neighbor search
    // std::cout << "K-Neighbor search:" << std::endl;
    // unsigned int numberOfNeighbors = 3;
    // typename TreeType::InstanceIdentifierVectorType neighbors;
    // m_tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;

    // for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
    //   {
    //     std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
    //   }

    // // Radius search
    // std::cout << "Radius search:" << std::endl;
    // double radius = 4.0;
    // m_tree->Search( queryPoint, radius, neighbors ) ;
    // std::cout << "There are " << neighbors.size() << " neighbors." << std::endl;
    // for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
    //   {
    //     std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
    //   }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_computeInputPointRange()
  {
    VectorType inputPointSetMin;
    inputPointSetMin.Fill(itk::NumericTraits< RealType >::max());

    VectorType inputPointSetMax;
    inputPointSetMax.Fill(itk::NumericTraits< RealType >::min());

    for (long itp = 0; itp < m_inputPointSet->Size(); ++itp)
      {
        VectorType thisPoint = m_inputPointSet->GetMeasurementVector(itp);

        for (unsigned int idim = 0; idim < NPointDimension; ++idim)
          {
            inputPointSetMin[idim] = inputPointSetMin[idim]<thisPoint[idim]?inputPointSetMin[idim]:thisPoint[idim];
            inputPointSetMax[idim] = inputPointSetMax[idim]<thisPoint[idim]?inputPointSetMax[idim]:thisPoint[idim];
          }
      }

    m_inputPointSetRange = inputPointSetMax - inputPointSetMin;

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_meanshiftIteration()
  {
    VectorType queryPoint;
    typename TreeType::InstanceIdentifierVectorType neighbors;

    for (long it = 0; it < m_numberOfMSIteration; ++it)
      {
        for (unsigned int itp = 0; itp < m_seedPoints->Size(); ++itp)
          {
            queryPoint = m_seedPoints->GetMeasurementVector(itp);
            m_tree->Search( queryPoint, m_radius, neighbors ) ;

            VectorType newPosition;
            newPosition.Fill(0);

            for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
              {
                newPosition += m_tree->GetMeasurementVector( neighbors[i] );
                //std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
              }

            newPosition /= static_cast<RealType>(neighbors.size());

            m_seedPoints->SetMeasurementVector(itp, newPosition);

            /// If relative increamental is small enough, break
            VectorType del = queryPoint - newPosition;
            for (unsigned int idim = 0; idim < NPointDimension; ++idim)
              {
                del[idim] /= m_inputPointSetRange[idim];
              }

            if (del.GetNorm() < 1e-1)
              {
                break;
              }
          }
      }

    if (m_epoch)
      {
        MeanshiftClusteringFilter<TCoordRep, NPointDimension> ms;
        ms.setInputPointSet(m_seedPoints);
        ms.setEpoch(--m_epoch);
        ms.update();
        m_seedPoints = ms._getSeedPoints();
      }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_getSeedPoints()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_seedPoints;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getCenters()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_centers;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findUniqueCenters()
  {
    m_centers = VectorSampleType::New();
    m_centers->PushBack( m_seedPoints->GetMeasurementVector(0) );

    for (unsigned int i = 1 ; i < m_seedPoints->Size() ; ++i )
      {
        const VectorType& newCenterCandidate = m_seedPoints->GetMeasurementVector(i);
        bool IAmNotCloseToAnyExistingCenter = true;

        for (unsigned int ii = 0 ; ii < m_centers->Size() ; ++ii )
          {
            VectorType distVector = newCenterCandidate - m_centers->GetMeasurementVector(ii);
            if (distVector.GetNorm() < m_radius )
              {
                IAmNotCloseToAnyExistingCenter = false;
                break;
              }
          }

        if (IAmNotCloseToAnyExistingCenter)
          {
            m_centers->PushBack( newCenterCandidate );
          }
      }

    m_numberOfModes = m_centers->Size();

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  std::vector<long>
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getLabelOfPoints()
  {
    if (!m_allDone)
      {
        std::cerr<<"Error: not done.\n";
      }

    return m_labelOfPoints;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void
  MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findLabelOfPoints()
  {
    typename TreeGeneratorType::Pointer newTreeGen = TreeGeneratorType::New();
    newTreeGen->SetSample( m_centers );
    newTreeGen->SetBucketSize( 16 );
    newTreeGen->Update();
    typename TreeType::Pointer newTree = newTreeGen->GetOutput();

    m_labelOfPoints.resize(m_inputPointSet->Size());

    // K-Neighbor search
    //std::cout << "K-Neighbor search:" << std::endl;
    unsigned int numberOfNeighbors = 1;
    typename TreeType::InstanceIdentifierVectorType neighbors;

    for (unsigned int i = 0 ; i < m_seedPoints->Size() ; ++i )
      {
        const VectorType& queryPoint = m_seedPoints->GetMeasurementVector(i);
        newTree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
        m_labelOfPoints[i] = static_cast<long>(neighbors[0]);
      }

    return;
  }

  template< typename TCoordRep, unsigned int NPointDimension >
  void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructSeedPoints()
  {
    /// Duplicate input points as seed points
    m_seedPoints = VectorSampleType::New();
    m_seedPoints->Resize(m_inputPointSet->Size() );

    for (unsigned int i = 0 ; i < m_inputPointSet->Size() ; ++i )
      {
        m_seedPoints->SetMeasurementVector( i, m_inputPointSet->GetMeasurementVector(i) );
      }

    return;
  }

}// namespace gth818n

#endif
<|endoftext|>


<commit_before>#include "config.h"

#include <iostream>
#include <algorithm>
#include <map>

#include "clotho/utility/log_helper.hpp"
#include "common_commandline.h"

#include "clotho/genetics/qtl_allele.h"
#include "clotho/utility/timer.hpp"
#include "simulate_engine.hpp"

#include <boost/random/mersenne_twister.hpp>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//#include <boost/foreach.hpp>
//
//#include "clotho/powerset/variable_subset_iterator.hpp"
//#include "clotho/genetics/individual_phenotyper.hpp"

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>

#include "clotho/genetics/fitness_toolkit.hpp"

namespace accum=boost::accumulators;

typedef boost::random::mt19937                                              rng_type;
typedef qtl_allele                                                          allele_type;
typedef boost::property_tree::ptree                                         log_type;
typedef clotho::utility::timer                                              timer_type;

typedef simulate_engine< rng_type, allele_type, log_type, timer_type > simulate_type;

// allele set typedef
typedef typename simulate_type::sequence_type    sequence_type;
typedef typename simulate_type::sequence_pointer sequence_pointer;
typedef typename simulate_type::allele_set_type allele_set_type;

// population typedefs
typedef typename simulate_type::individual_type                        individual_type;
typedef typename simulate_type::population_type                        population_type;
typedef typename population_type::iterator                             population_iterator;

typedef std::map< sequence_pointer, unsigned int >  ref_map_type;
typedef typename ref_map_type::iterator             ref_map_iterator;
typedef std::vector< unsigned int >                 allele_dist_type;

const string BASE_SEQUENCE_BIAS_K = "base_bias";
const string TRAIT_BLOCK_K = "traits";
const string ALLELE_BLOCK_K = "allele";
const string NEUTRAL_P_K = "neutral.p";

const string SAMPLING_K = "sampling_size";

//const string FITNESS_BLOCK_K = "fitness";
const string QUADRATIC_SCALE_K = "quadratic.scale";
const string CONSTANT_K = "constant";

const string SIZE_K = "size";
const string PAIRWISE_K = "pairwise";

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

    log_type config;
    int res = parse_commandline(argc, argv, config);
    if( res ) {
        return res;
    }

    log_type conf_child = ( (config.get_child_optional( CONFIG_BLOCK_K) == boost::none) ? config : config.get_child( CONFIG_BLOCK_K ));

    const unsigned int nRep = conf_child.get< unsigned int >( REPEAT_K, 1 );
    const unsigned int nGen = conf_child.get< unsigned int >( GEN_BLOCK_K + "." + SIZE_K, 1);
    const unsigned int nLog = conf_child.get< unsigned int >( LOG_BLOCK_K + "." + PERIOD_K, -1);
    const unsigned int seed = conf_child.get< unsigned int >( RNG_BLOCK_K + "." + SEED_K, 0 );
    string out_path = conf_child.get<string>( OUTPUT_K, "");

    rng_type rng(seed);

    for( unsigned int i = 0; i < nRep; ++i ) {
        // change the seed value of the random number generator
        rng.discard( 15 );
        const unsigned int tmp_seed = rng();
        log_type rep_child_conf = conf_child;

        rep_child_conf.put( RNG_BLOCK_K + "." + SEED_K, tmp_seed );

        simulate_type sim( rep_child_conf );

        if( nGen == 0 ) {
            fitness_toolkit::getInstance()->tool_configurations( rep_child_conf );

            log_type tmp;
            tmp.add_child( CONFIG_BLOCK_K, rep_child_conf );
            boost::property_tree::write_json( std::cerr, tmp );
        }

        unsigned int log_period = ((nGen < nLog) ? nGen : nLog);
        for( unsigned int j = 0; j < nGen; ++j ) {
            sim.simulate();

            sim.reset_parent();
            if( !(--log_period) ) {
                log_type stat_log;
                sim.computeStats( stat_log );

                // combine simulation log and configuration log into single object
                BOOST_FOREACH( auto& upd, sim.getLog() ) {
                    stat_log.put_child( upd.first, upd.second );
                }
                sim.clearLog();

//                BOOST_FOREACH( auto& upd, config ) {
//                    stat_log.put_child(upd.first, upd.second );
//                }
                stat_log.put_child( CONFIG_BLOCK_K, rep_child_conf);

                log_period = ((j + log_period < nGen) ? nLog : (nGen - j - 1) );

                if( !stat_log.empty() ) {
                    if( out_path.empty() ) {
                        boost::property_tree::write_json( std::cout, stat_log );
                    } else {
                        std::ostringstream oss;
                        oss << out_path << "." << i << "." << j << ".json";

                        boost::property_tree::write_json( oss.str(), stat_log );
                    }
                }
            }
        }
    }

    return 0;
}
<commit_msg>Added performance tracking amounts<commit_after>#include "config.h"

#include <iostream>
#include <algorithm>
#include <map>

#include "clotho/utility/log_helper.hpp"
#include "common_commandline.h"

#include "clotho/genetics/qtl_allele.h"
#include "clotho/utility/timer.hpp"
#include "simulate_engine.hpp"

#include <boost/random/mersenne_twister.hpp>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//#include <boost/foreach.hpp>
//
//#include "clotho/powerset/variable_subset_iterator.hpp"
//#include "clotho/genetics/individual_phenotyper.hpp"

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>

#include "clotho/genetics/fitness_toolkit.hpp"

namespace accum=boost::accumulators;

typedef boost::random::mt19937                                              rng_type;
typedef qtl_allele                                                          allele_type;
typedef boost::property_tree::ptree                                         log_type;
typedef clotho::utility::timer                                              timer_type;

typedef simulate_engine< rng_type, allele_type, log_type, timer_type > simulate_type;

// allele set typedef
typedef typename simulate_type::sequence_type    sequence_type;
typedef typename simulate_type::sequence_pointer sequence_pointer;
typedef typename simulate_type::allele_set_type allele_set_type;

// population typedefs
typedef typename simulate_type::individual_type                        individual_type;
typedef typename simulate_type::population_type                        population_type;
typedef typename population_type::iterator                             population_iterator;

typedef std::map< sequence_pointer, unsigned int >  ref_map_type;
typedef typename ref_map_type::iterator             ref_map_iterator;
typedef std::vector< unsigned int >                 allele_dist_type;

const string BASE_SEQUENCE_BIAS_K = "base_bias";
const string TRAIT_BLOCK_K = "traits";
const string ALLELE_BLOCK_K = "allele";
const string NEUTRAL_P_K = "neutral.p";

const string SAMPLING_K = "sampling_size";

//const string FITNESS_BLOCK_K = "fitness";
const string QUADRATIC_SCALE_K = "quadratic.scale";
const string CONSTANT_K = "constant";

const string SIZE_K = "size";
const string PAIRWISE_K = "pairwise";

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

    log_type config;
    int res = parse_commandline(argc, argv, config);
    if( res ) {
        return res;
    }

    log_type conf_child = ( (config.get_child_optional( CONFIG_BLOCK_K) == boost::none) ? config : config.get_child( CONFIG_BLOCK_K ));

    const unsigned int nRep = conf_child.get< unsigned int >( REPEAT_K, 1 );
    const unsigned int nGen = conf_child.get< unsigned int >( GEN_BLOCK_K + "." + SIZE_K, 1);
    const unsigned int nLog = conf_child.get< unsigned int >( LOG_BLOCK_K + "." + PERIOD_K, -1);
    const unsigned int seed = conf_child.get< unsigned int >( RNG_BLOCK_K + "." + SEED_K, 0 );
    string out_path = conf_child.get<string>( OUTPUT_K, "");

    rng_type rng(seed);

    for( unsigned int i = 0; i < nRep; ++i ) {
        // change the seed value of the random number generator
        rng.discard( 15 );
        const unsigned int tmp_seed = rng();
        log_type rep_child_conf = conf_child;

        rep_child_conf.put( RNG_BLOCK_K + "." + SEED_K, tmp_seed );

        simulate_type sim( rep_child_conf );

        if( nGen == 0 ) {
            fitness_toolkit::getInstance()->tool_configurations( rep_child_conf );

            log_type tmp;
            tmp.add_child( CONFIG_BLOCK_K, rep_child_conf );
            boost::property_tree::write_json( std::cerr, tmp );

            continue;
        }

        unsigned int log_period = ((nGen < nLog) ? nGen : nLog);
        log_type sim_times, stat_times;

        timer_type rep_time;
        for( unsigned int j = 0; j < nGen; ++j ) {
            timer_type sim_time;
            sim.simulate();
            sim_time.stop();

            clotho::utility::add_value_array( sim_times, sim_time );

            sim.reset_parent();
            if( !(--log_period) ) {
                timer_type stat_time;

                log_type stat_log;
                sim.computeStats( stat_log );

                // combine simulation log and configuration log into single object
                BOOST_FOREACH( auto& upd, sim.getLog() ) {
                    stat_log.put_child( upd.first, upd.second );
                }
                sim.clearLog();

//                BOOST_FOREACH( auto& upd, config ) {
//                    stat_log.put_child(upd.first, upd.second );
//                }
                stat_log.put_child( CONFIG_BLOCK_K, rep_child_conf);

                log_period = ((j + log_period < nGen) ? nLog : (nGen - j - 1) );

                if( !stat_log.empty() ) {
                    if( out_path.empty() ) {
                        boost::property_tree::write_json( std::cout, stat_log );
                    } else {
                        std::ostringstream oss;
                        oss << out_path << "." << i << "." << j << ".json";

                        boost::property_tree::write_json( oss.str(), stat_log );
                    }
                }
                stat_time.stop();
                clotho::utility::add_value_array( stat_times, stat_time );
            }
        }
        rep_time.stop();

        log_type perform_log;
        perform_log.add( "performance.runtime", rep_time.elapsed().count() );
        perform_log.put_child( "performance.simulate", sim_times );
        perform_log.put_child( "performance.stats", stat_times );

        if( out_path.empty() ) {
            boost::property_tree::write_json( std::cout, perform_log );
        } else {
            std::ostringstream oss;
            oss << out_path << "." << i << ".performance.json";

            boost::property_tree::write_json( oss.str(), perform_log );
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "inspector_entity.h"
#include "inspectors.h"

struct Inspector_Entity::component
{
	struct instance
	{
		PathNameTagTree _tree;
		std::vector<runtime::CHandle<runtime::Component>> _list;
		instance();
		void setup(const std::vector<runtime::CHandle<runtime::Component>>& list);
		void inspect(bool& changed);
	};

	struct type
	{
		PathNameTagTree _tree;
		PathNameTagTree::iterator _itor;
		std::vector<rttr::type*> _list;

		type();

		void inspect(ImGuiTextFilter& filter, runtime::Entity data);
	};

	instance _instance;
	type _type;
};

Inspector_Entity::component::instance::instance() :
	_tree('/', -1)
{ }

void Inspector_Entity::component::instance::setup(const std::vector<runtime::CHandle<runtime::Component>>& list)
{
	_list = list;
	_tree.reset();
	{
		size_t i = 0;
		for (auto& ptr : _list)
		{
			auto component = ptr.lock().get();

			auto info = rttr::type::get(*component);

			auto meta_category = info.get_metadata("Category");
			auto meta_id = info.get_metadata("Id");

			std::string name = info.get_name();

			if (meta_id)
			{
				name = meta_id.to_string();
			}

			if (meta_category)
			{
				std::string category = meta_category.to_string();
				name = category + "/" + name;
			}

			_tree.set(name, i++);

		}
	}
}
void Inspector_Entity::component::instance::inspect(bool& changed)
{
	struct TreeScoped
	{
		TreeScoped(const char* id) { gui::TreePush(id); }
		~TreeScoped() { gui::TreePop(); }
	};

	bool opened = true;

	auto it = _tree.create_iterator();

	while (it.steps())
	{
		while (it.steping())
		{
			const char* name = it.name().data();

			if (it.is_leaf() ? it.tag() < _list.size() : it.tag() > 0)
			{
				bool remove = false;

				if (opened)
				{
					gui::SetNextTreeNodeOpen(true, ImGuiSetCond_FirstUseEver);
					if (gui::CollapsingHeader(name, &opened))
					{
						gui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 8.0f);
						TreeScoped t(name);
						gui::PopStyleVar();

						if (it.step_in())
						{
							continue;
						}
						else
						{
							rttr::variant componentVar = _list[it.tag()].lock().get();
							changed |= inspect_var(componentVar);

						}
					}

					if (!opened && it.is_leaf())
					{
						opened = remove = true;
					}
				}
				else
				{
					if (it.step_in())
					{
						continue;
					}
					else
					{
						remove = true;
					}
				}

				if (remove)
				{
					auto& component_ptr = _list[it.tag()];
					auto component = component_ptr.lock().get();

					component->get_entity().remove(component_ptr.lock());
				}
			}

			it.step();
		}

		if (it.step_out())
		{
			it.step();
		}
	}
}

Inspector_Entity::component::type::type() :
	_tree('/', -1)
{
	auto types = rttr::type::get<runtime::Component>().get_derived_classes();
	for (auto& info : types)
	{
		auto meta_category = info.get_metadata("Category");
		auto meta_id = info.get_metadata("Id");

		std::string name = info.get_name();

		if (meta_id)
		{
			name = meta_id.to_string();
		}

		if (meta_category)
		{
			std::string category = meta_category.to_string();
			name = category + "/" + name;
		}

		_tree.set(name, _list.size());
		_list.push_back(&info);

	}
	_tree.setup_iterator(_itor);
}

void Inspector_Entity::component::type::inspect(ImGuiTextFilter& filter, runtime::Entity data)
{
	gui::Separator();
	std::string path = "<";

	if (gui::ButtonEx(path.data(), ImVec2(0, 0), _itor.steps() > 1 ? 0 : ImGuiButtonFlags_Disabled))
	{
		_itor.step_out();
	}
	gui::Separator();

	if (_itor.step_stack_pop())
	{
		_itor.step_in();
	}
	else
	{
		_itor.step_reset();
	}

	while (_itor.steping())
	{
		std::string name = _itor.name();

		auto component_type = _list[_itor.tag()];

		if (filter.PassFilter(name.c_str()))
		{
			if (!_itor.is_leaf())
			{
				name += "   >";
			}

			if (gui::Selectable(name.c_str()))
			{
				if (_itor.is_leaf())
				{
					auto cstructor = component_type->get_constructor();

					auto c = cstructor.invoke();
					auto c_ptr = c.get_value<std::shared_ptr<runtime::Component>>();
					if (c_ptr)
						data.assign(c_ptr);

					gui::CloseCurrentPopup();
				}
				else
				{
					_itor.step_stack_push();
				}
			}
		}

		_itor.step();
	}
}

Inspector_Entity::Inspector_Entity()
	: _component(std::make_unique<component>())
{ }

Inspector_Entity::Inspector_Entity(const Inspector_Entity& other)
	: _component(std::make_unique<component>())
{ }

Inspector_Entity::~Inspector_Entity()
{
}

bool Inspector_Entity::inspect(rttr::variant& var, bool readOnly, std::function<rttr::variant(const rttr::variant&)> get_metadata)
{
	auto data = var.get_value<runtime::Entity>();
	if (!data)
		return false;
	bool changed = false;
	{
		PropertyLayout propName("Name");
		rttr::variant varName = data.to_string();

		changed |= inspect_var(varName);

		if(changed)
		{
			data.set_name(varName.to_string());
		}
	}

	_component->_instance.setup(data.all_components());

	_component->_instance.inspect(changed);

	gui::Separator();
	if (gui::Button("+Component"))
	{
		gui::OpenPopup("ComponentMenu");

	}

	if (gui::BeginPopup("ComponentMenu"))
	{
		static ImGuiTextFilter filter;
		filter.Draw("Filter", 180);
		gui::Separator();
		gui::BeginChild("ComponentMenuContent", ImVec2(gui::GetContentRegionAvailWidth(), 200.0f));

		_component->_type.inspect(filter, data);

		gui::EndChild();
		gui::EndPopup();
	}

	if (changed)
	{
		var = data;
		return true;
	}

	return false;
}<commit_msg>cleanup<commit_after>#include "inspector_entity.h"
#include "inspectors.h"

struct Inspector_Entity::component
{
	struct instance
	{
		PathNameTagTree _tree;
		std::vector<runtime::CHandle<runtime::Component>> _list;
		instance();
		void setup(const std::vector<runtime::CHandle<runtime::Component>>& list);
		void inspect(bool& changed);
	};

	struct type
	{
		PathNameTagTree _tree;
		PathNameTagTree::iterator _itor;
		std::vector<rttr::type> _list;

		type();

		void inspect(ImGuiTextFilter& filter, runtime::Entity data);
	};

	instance _instance;
	type _type;
};

Inspector_Entity::component::instance::instance() :
	_tree('/', -1)
{ }

void Inspector_Entity::component::instance::setup(const std::vector<runtime::CHandle<runtime::Component>>& list)
{
	_list = list;
	_tree.reset();
	{
		size_t i = 0;
		for (auto& ptr : _list)
		{
			auto component = ptr.lock().get();

			auto info = rttr::type::get(*component);

			auto meta_category = info.get_metadata("Category");
			auto meta_id = info.get_metadata("Id");

			std::string name = info.get_name();

			if (meta_id)
			{
				name = meta_id.to_string();
			}

			if (meta_category)
			{
				std::string category = meta_category.to_string();
				name = category + "/" + name;
			}

			_tree.set(name, i++);

		}
	}
}
void Inspector_Entity::component::instance::inspect(bool& changed)
{
	bool opened = true;

	auto it = _tree.create_iterator();

	while (it.steps())
	{
		while (it.steping())
		{
			const char* name = it.name().data();

			if (it.is_leaf() ? it.tag() < _list.size() : it.tag() > 0)
			{
				bool remove = false;

				if (opened)
				{
					gui::SetNextTreeNodeOpen(true, ImGuiSetCond_FirstUseEver);
					if (gui::CollapsingHeader(name, &opened))
					{
						gui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 8.0f);
						gui::TreePush(name);

						if (it.step_in())
						{
							continue;
						}
						else
						{
							rttr::variant var = _list[it.tag()].lock().get();
							changed |= inspect_var(var);

							gui::TreePop();
							gui::PopStyleVar();
						}
					}

					if (!opened && it.is_leaf())
					{
						opened = remove = true;
					}
				}
				else
				{
					if (it.step_in())
					{
						continue;
					}
					else
					{
						remove = true;
					}
				}

				if (remove)
				{
					auto& component_ptr = _list[it.tag()];
					auto component = component_ptr.lock().get();

					component->get_entity().remove(component_ptr.lock());

				}
			}

			it.step();
		}

		if (it.step_out())
		{
			opened = it.step();
			gui::TreePop();
			gui::PopStyleVar();
		}
	}
}

Inspector_Entity::component::type::type() :
	_tree('/', -1)
{
	auto types = rttr::type::get<runtime::Component>().get_derived_classes();
	for (auto& info : types)
	{
		auto meta_category = info.get_metadata("Category");
		auto meta_id = info.get_metadata("Id");

		std::string name = info.get_name();

		if (meta_id)
		{
			name = meta_id.to_string();
		}

		if (meta_category)
		{
			std::string category = meta_category.to_string();
			name = category + "/" + name;
		}

		_tree.set(name, _list.size());
		_list.push_back(info);

	}
	_tree.setup_iterator(_itor);
}

void Inspector_Entity::component::type::inspect(ImGuiTextFilter& filter, runtime::Entity data)
{
	gui::Separator();
	std::string path = "<";

	if (gui::ButtonEx(path.data(), ImVec2(0, 0), _itor.steps() > 1 ? 0 : ImGuiButtonFlags_Disabled))
	{
		_itor.step_out();
	}
	gui::Separator();

	if (_itor.step_stack_pop())
	{
		_itor.step_in();
	}
	else
	{
		_itor.step_reset();
	}

	while (_itor.steping())
	{
		std::string name = _itor.name();

		auto component_type = _list[_itor.tag()];

		if (filter.PassFilter(name.c_str()))
		{
			if (gui::Selectable(name.c_str()))
			{
				if (_itor.is_leaf())
				{
					auto cstructor = component_type.get_constructor();

					auto c = cstructor.invoke();
					auto c_ptr = c.get_value<std::shared_ptr<runtime::Component>>();
					if (c_ptr)
						data.assign(c_ptr);

					gui::CloseCurrentPopup();
				}
				else
				{
					_itor.step_stack_push();
				}
			}
		}

		_itor.step();
	}
}

Inspector_Entity::Inspector_Entity()
	: _component(std::make_unique<component>())
{ }

Inspector_Entity::Inspector_Entity(const Inspector_Entity& other)
	: _component(std::make_unique<component>())
{ }

Inspector_Entity::~Inspector_Entity()
{
}

bool Inspector_Entity::inspect(rttr::variant& var, bool readOnly, std::function<rttr::variant(const rttr::variant&)> get_metadata)
{
	auto data = var.get_value<runtime::Entity>();
	if (!data)
		return false;
	bool changed = false;
	{
		PropertyLayout propName("Name");
		rttr::variant varName = data.to_string();

		changed |= inspect_var(varName);

		if(changed)
		{
			data.set_name(varName.to_string());
		}
	}

	_component->_instance.setup(data.all_components());

	_component->_instance.inspect(changed);

	gui::Separator();
	if (gui::Button("+Component"))
	{
		gui::OpenPopup("ComponentMenu");

	}

	if (gui::BeginPopup("ComponentMenu"))
	{
		static ImGuiTextFilter filter;
		filter.Draw("Filter", 180);
		gui::Separator();
		gui::BeginChild("ComponentMenuContent", ImVec2(gui::GetContentRegionAvailWidth(), 200.0f));

		_component->_type.inspect(filter, data);

		gui::EndChild();
		gui::EndPopup();
	}

	if (changed)
	{
		var = data;
		return true;
	}

	return false;
}<|endoftext|>