<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Felix Hammer   *
 *   f.hammer@web.de   *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "gametablestylereader.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <fstream>

using namespace std;

GameTableStyleReader::GameTableStyleReader(ConfigFile *c, gameTableImpl *w) : myConfig(c), myW(w)
{

}

GameTableStyleReader::~GameTableStyleReader()
{
}

void GameTableStyleReader::readStyleFile(QString file) {

	string tinyFileName;

	//if style file failed --> default style fallback
	if(QFile(file).exists()) {
		currentFileName = QFile(file).fileName();
		tinyFileName = currentFileName.toStdString();

		QMessageBox::warning(myW, tr("WORKS"),
                                currentFileName,
                                QMessageBox::Ok);
	}
	else {
		currentFileName = QFile(QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str())+"/gfx/gui/table/default/defaulttablestyle.xml").fileName();
		tinyFileName = currentFileName.toStdString();
		QMessageBox::warning(myW, tr("FALLBACK"),
                                currentFileName,
                                QMessageBox::Ok);

	}
	QFileInfo info(currentFileName);
	currentFileDir = info.absolutePath();

	//start reading the file and fill vars
	string tempString1("");
	TiXmlDocument doc(tinyFileName);

	if(doc.LoadFile()) {
		TiXmlHandle docHandle( &doc );

		TiXmlElement* itemsList = docHandle.FirstChild( "PokerTH" ).FirstChild( "TableStyle" ).FirstChild().ToElement();
		for( ; itemsList; itemsList=itemsList->NextSiblingElement()) {
			const char *tmpStr1 = itemsList->Attribute("value");
			if (tmpStr1) {
				tempString1 = tmpStr1;

				if(itemsList->ValueStr() == "StyleDescription") { StyleDescription = QString::fromUtf8(tempString1.c_str()); }
				else if(itemsList->ValueStr() == "StyleMaintainerEMail") { StyleMaintainerEMail = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "Preview") { Preview = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "IfFixedWindowSize") { IfFixedWindowSize = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FixedWindowWidth") { FixedWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FixedWindowHeight") { FixedWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MinimumWindowWidth") { MinimumWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MinimumWindowHeight") { MinimumWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MaximumWindowWidth") { MaximumWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MaximumWindowHeight") { MaximumWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionAllIn") { ActionAllIn = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionRaise") { ActionRaise = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionBet") { ActionBet = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionCall") { ActionCall = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionCheck") { ActionCheck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionFold") { ActionFold = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionWinner") { ActionWinner = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BigBlindPuck") { BigBlindPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "SmallBlindPuck") { SmallBlindPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "DealerPuck") { DealerPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "DefaultAvatar") { DefaultAvatar = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderFlop") { CardHolderFlop = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderTurn") { CardHolderTurn = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderRiver") { CardHolderRiver = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonDefault") { FoldButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonHover") { FoldButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonChecked") { FoldButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonCheckedHover") { FoldButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonDefault") { CheckCallButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonHover") { CheckCallButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonChecked") { CheckCallButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonCheckedHover") { CheckCallButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonDefault") { BetRaiseButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonHover") { BetRaiseButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonChecked") { BetRaiseButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonCheckedHover") { BetRaiseButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonDefault") { AllInButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonHover") { AllInButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonChecked") { AllInButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonCheckedHover") { AllInButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "PlayerSeatInActive") { PlayerSeatInActive = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "PlayerSeatActive") { PlayerSeatActive = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "Table") { Table = QString::fromUtf8(tempString1.c_str()); }

// 				std::cout << "ÖLP" << itemsList->ValueStr() <<"§4s"<< itemsList->ValueStr()<<"§89"<< endl;
			}
		}
		wrongItems.clear();

		if(IfFixedWindowSize == "") { wrongItems << "IfFixedWindowSize"; }
		if(FixedWindowWidth == "") { wrongItems << "FixedWindowWidth"; }
		if(FixedWindowHeight == "") { wrongItems << "FixedWindowHeight"; }
		if(MinimumWindowWidth == "") { wrongItems << "MinimumWindowWidth"; }
		if(MinimumWindowHeight == "") { wrongItems << "MinimumWindowHeight"; }
		if(MaximumWindowWidth == "") { wrongItems << "MaximumWindowWidth"; }
		if(MaximumWindowHeight == "") { wrongItems << "MaximumWindowHeight"; }
		if(ActionAllIn == "") { wrongItems << "ActionAllIn"; }
		if(ActionRaise == "") { wrongItems << "ActionRaise"; }
		if(ActionBet == "") { wrongItems << "ActionBet"; }
		if(ActionCall == "") { wrongItems << "ActionCall"; }
		if(ActionCheck == "") { wrongItems << "ActionCheck"; }
		if(ActionFold == "") { wrongItems << "ActionFold"; }
		if(ActionWinner == "") { wrongItems << "ActionWinner"; }
		if(BigBlindPuck == "") { wrongItems << "BigBlindPuck"; }
		if(SmallBlindPuck == "") { wrongItems << "SmallBlindPuck"; }
		if(DealerPuck == "") { wrongItems << "DealerPuck"; }
		if(DefaultAvatar == "") { wrongItems << "DefaultAvatar"; }
		if(CardHolderFlop == "") { wrongItems << "CardHolderFlop"; }
		if(CardHolderTurn == "") { wrongItems << "CardHolderTurn"; }
		if(CardHolderRiver == "") { wrongItems << "CardHolderRiver"; }
		if(FoldButtonDefault == "") { wrongItems << "FoldButtonDefault"; }
		if(FoldButtonHover == "") { wrongItems << "FoldButtonHover"; }
		if(FoldButtonChecked == "") { wrongItems << "FoldButtonChecked"; }
		if(FoldButtonCheckedHover == "") { wrongItems << "FoldButtonCheckedHover"; }
		if(CheckCallButtonDefault == "") { wrongItems << "CheckCallButtonDefault"; }
		if(CheckCallButtonHover == "") { wrongItems << "CheckCallButtonHover"; }
		if(CheckCallButtonChecked == "") { wrongItems << "CheckCallButtonChecked"; }
		if(CheckCallButtonCheckedHover == "") { wrongItems << "CheckCallButtonCheckedHover"; }
		if(BetRaiseButtonDefault == "") { wrongItems << "BetRaiseButtonDefault"; }
		if(BetRaiseButtonHover == "") { wrongItems << "BetRaiseButtonHover"; }
		if(BetRaiseButtonChecked == "") { wrongItems << "BetRaiseButtonChecked"; }
		if(BetRaiseButtonCheckedHover == "") { wrongItems << "BetRaiseButtonCheckedHover"; }
		if(AllInButtonDefault == "") { wrongItems << "AllInButtonDefault"; }
		if(AllInButtonHover == "") { wrongItems << "AllInButtonHover"; }
		if(AllInButtonChecked == "") { wrongItems << "AllInButtonChecked"; }
		if(AllInButtonCheckedHover == "") { wrongItems << "AllInButtonCheckedHover"; }
		if(PlayerSeatActive == "") { wrongItems << "PlayerSeatActive"; }
		if(PlayerSeatInActive == "") { wrongItems << "PlayerSeatInActive"; }
		if(Table == "") { wrongItems << "Table"; }

		//if one or more items are wrong or left show detailed error message
		if(!wrongItems.isEmpty() && myW != 0) showErrorMessage(StyleDescription, wrongItems, StyleMaintainerEMail);
	}
}

void GameTableStyleReader::showErrorMessage(QString style, QStringList failedItems, QString email)
{
	QString items = failedItems.join(", ");

	QMessageBox::warning(myW, tr("Game Table Style Error"),
                                tr("Selected game table style \"%1\" seems to be incomplete or defective. \nThe value of \"%2\" is wrong or left. Please contact the style builder %3.").arg(style).arg(items).arg(email),
                                QMessageBox::Ok);
}

<commit_msg>next steps skinning implementation (TESTING!!!)<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Felix Hammer   *
 *   f.hammer@web.de   *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "gametablestylereader.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <fstream>

using namespace std;

GameTableStyleReader::GameTableStyleReader(ConfigFile *c, gameTableImpl *w) : myConfig(c), myW(w)
{

}

GameTableStyleReader::~GameTableStyleReader()
{
}

void GameTableStyleReader::readStyleFile(QString file) {

	string tinyFileName;

	QMessageBox::warning(myW, tr("FILE"),
                                file,
                                QMessageBox::Ok);

	//if style file failed --> default style fallback
	if(QFile(file).exists()) {
		currentFileName = QFile(file).fileName();
		tinyFileName = currentFileName.toStdString();

		QMessageBox::warning(myW, tr("WORKS"),
                                currentFileName,
                                QMessageBox::Ok);
	}
	else {
		currentFileName = QFile(QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str())+"/gfx/gui/table/default/defaulttablestyle.xml").fileName();
		tinyFileName = currentFileName.toStdString();
		QMessageBox::warning(myW, tr("FALLBACK"),
                                currentFileName,
                                QMessageBox::Ok);

	}
	QFileInfo info(currentFileName);
	currentFileDir = info.absolutePath();

	//start reading the file and fill vars
	string tempString1("");
	TiXmlDocument doc(tinyFileName);

	if(doc.LoadFile()) {
		TiXmlHandle docHandle( &doc );

		TiXmlElement* itemsList = docHandle.FirstChild( "PokerTH" ).FirstChild( "TableStyle" ).FirstChild().ToElement();
		for( ; itemsList; itemsList=itemsList->NextSiblingElement()) {
			const char *tmpStr1 = itemsList->Attribute("value");
			if (tmpStr1) {
				tempString1 = tmpStr1;

				if(itemsList->ValueStr() == "StyleDescription") { StyleDescription = QString::fromUtf8(tempString1.c_str()); }
				else if(itemsList->ValueStr() == "StyleMaintainerEMail") { StyleMaintainerEMail = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "Preview") { Preview = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "IfFixedWindowSize") { IfFixedWindowSize = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FixedWindowWidth") { FixedWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FixedWindowHeight") { FixedWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MinimumWindowWidth") { MinimumWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MinimumWindowHeight") { MinimumWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MaximumWindowWidth") { MaximumWindowWidth = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "MaximumWindowHeight") { MaximumWindowHeight = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionAllIn") { ActionAllIn = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionRaise") { ActionRaise = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionBet") { ActionBet = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionCall") { ActionCall = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionCheck") { ActionCheck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionFold") { ActionFold = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "ActionWinner") { ActionWinner = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BigBlindPuck") { BigBlindPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "SmallBlindPuck") { SmallBlindPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "DealerPuck") { DealerPuck = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "DefaultAvatar") { DefaultAvatar = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderFlop") { CardHolderFlop = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderTurn") { CardHolderTurn = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CardHolderRiver") { CardHolderRiver = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonDefault") { FoldButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonHover") { FoldButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonChecked") { FoldButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "FoldButtonCheckedHover") { FoldButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonDefault") { CheckCallButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonHover") { CheckCallButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonChecked") { CheckCallButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "CheckCallButtonCheckedHover") { CheckCallButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonDefault") { BetRaiseButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonHover") { BetRaiseButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonChecked") { BetRaiseButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "BetRaiseButtonCheckedHover") { BetRaiseButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonDefault") { AllInButtonDefault = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonHover") { AllInButtonHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonChecked") { AllInButtonChecked = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "AllInButtonCheckedHover") { AllInButtonCheckedHover = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "PlayerSeatInActive") { PlayerSeatInActive = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "PlayerSeatActive") { PlayerSeatActive = QString::fromUtf8(tempString1.c_str()); }
				else if (itemsList->ValueStr() == "Table") { Table = QString::fromUtf8(tempString1.c_str()); }

// 				std::cout << "ÖLP" << itemsList->ValueStr() <<"§4s"<< itemsList->ValueStr()<<"§89"<< endl;
			}
		}
		wrongItems.clear();

		if(IfFixedWindowSize == "") { wrongItems << "IfFixedWindowSize"; }
		if(FixedWindowWidth == "") { wrongItems << "FixedWindowWidth"; }
		if(FixedWindowHeight == "") { wrongItems << "FixedWindowHeight"; }
		if(MinimumWindowWidth == "") { wrongItems << "MinimumWindowWidth"; }
		if(MinimumWindowHeight == "") { wrongItems << "MinimumWindowHeight"; }
		if(MaximumWindowWidth == "") { wrongItems << "MaximumWindowWidth"; }
		if(MaximumWindowHeight == "") { wrongItems << "MaximumWindowHeight"; }
		if(ActionAllIn == "") { wrongItems << "ActionAllIn"; }
		if(ActionRaise == "") { wrongItems << "ActionRaise"; }
		if(ActionBet == "") { wrongItems << "ActionBet"; }
		if(ActionCall == "") { wrongItems << "ActionCall"; }
		if(ActionCheck == "") { wrongItems << "ActionCheck"; }
		if(ActionFold == "") { wrongItems << "ActionFold"; }
		if(ActionWinner == "") { wrongItems << "ActionWinner"; }
		if(BigBlindPuck == "") { wrongItems << "BigBlindPuck"; }
		if(SmallBlindPuck == "") { wrongItems << "SmallBlindPuck"; }
		if(DealerPuck == "") { wrongItems << "DealerPuck"; }
		if(DefaultAvatar == "") { wrongItems << "DefaultAvatar"; }
		if(CardHolderFlop == "") { wrongItems << "CardHolderFlop"; }
		if(CardHolderTurn == "") { wrongItems << "CardHolderTurn"; }
		if(CardHolderRiver == "") { wrongItems << "CardHolderRiver"; }
		if(FoldButtonDefault == "") { wrongItems << "FoldButtonDefault"; }
		if(FoldButtonHover == "") { wrongItems << "FoldButtonHover"; }
		if(FoldButtonChecked == "") { wrongItems << "FoldButtonChecked"; }
		if(FoldButtonCheckedHover == "") { wrongItems << "FoldButtonCheckedHover"; }
		if(CheckCallButtonDefault == "") { wrongItems << "CheckCallButtonDefault"; }
		if(CheckCallButtonHover == "") { wrongItems << "CheckCallButtonHover"; }
		if(CheckCallButtonChecked == "") { wrongItems << "CheckCallButtonChecked"; }
		if(CheckCallButtonCheckedHover == "") { wrongItems << "CheckCallButtonCheckedHover"; }
		if(BetRaiseButtonDefault == "") { wrongItems << "BetRaiseButtonDefault"; }
		if(BetRaiseButtonHover == "") { wrongItems << "BetRaiseButtonHover"; }
		if(BetRaiseButtonChecked == "") { wrongItems << "BetRaiseButtonChecked"; }
		if(BetRaiseButtonCheckedHover == "") { wrongItems << "BetRaiseButtonCheckedHover"; }
		if(AllInButtonDefault == "") { wrongItems << "AllInButtonDefault"; }
		if(AllInButtonHover == "") { wrongItems << "AllInButtonHover"; }
		if(AllInButtonChecked == "") { wrongItems << "AllInButtonChecked"; }
		if(AllInButtonCheckedHover == "") { wrongItems << "AllInButtonCheckedHover"; }
		if(PlayerSeatActive == "") { wrongItems << "PlayerSeatActive"; }
		if(PlayerSeatInActive == "") { wrongItems << "PlayerSeatInActive"; }
		if(Table == "") { wrongItems << "Table"; }

		//if one or more items are wrong or left show detailed error message
		if(!wrongItems.isEmpty() && myW != 0) showErrorMessage(StyleDescription, wrongItems, StyleMaintainerEMail);
	}
}

void GameTableStyleReader::showErrorMessage(QString style, QStringList failedItems, QString email)
{
	QString items = failedItems.join(", ");

	QMessageBox::warning(myW, tr("Game Table Style Error"),
                                tr("Selected game table style \"%1\" seems to be incomplete or defective. \nThe value of \"%2\" is wrong or left. Please contact the style builder %3.").arg(style).arg(items).arg(email),
                                QMessageBox::Ok);
}

<|endoftext|>


<commit_before>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  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.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

#pragma once

#include <thrust/device_ptr.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/static_assert.h>
#include <thrust/pair.h>

#include <thrust/detail/device/cuda/dispatch/reduce.h>
#include <thrust/detail/device/cuda/reduce_n.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{
//////////////
// Functors //
//////////////
template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType>
  struct wide_unary_op : public thrust::unary_function<WideType,OutputType>
{
    BinaryFunction binary_op;

    __host__ __device__
        wide_unary_op(BinaryFunction binary_op)
            : binary_op(binary_op) {}

    __host__ __device__
        OutputType operator()(WideType x)
        {
            WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1;

            OutputType sum = static_cast<InputType>(x & mask);

            for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++)
                sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) );

            return sum;
        }
};

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::true_type)
{
    // "wide" reduction for small types like char, short, etc.
    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;
    typedef unsigned int WideType;

    // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType *

    // TODO use simple threshold and ensure alignment of wide_first

    // process first part
    size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); size_t n_wide = (last - first) / input_type_per_wide_type;

    const WideType * wide_first = reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first));

    OutputType result = thrust::detail::device::cuda::reduce_n
        (thrust::make_transform_iterator(wide_first, wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)),
         n_wide, init, binary_op);

    // process tail
    InputIterator tail_first = first + n_wide * input_type_per_wide_type;
    return thrust::detail::device::cuda::reduce_n(tail_first, last - tail_first, result, binary_op);
}

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::false_type)
{
    // standard reduction
    return thrust::detail::device::cuda::reduce_n(first, last - first, init, binary_op);
}

template<typename Iterator, typename InputType = typename thrust::iterator_value<Iterator>::type>
  struct use_wide_reduction
    : thrust::detail::integral_constant<
        bool,
        thrust::detail::is_pod<InputType>::value
        && thrust::detail::is_trivial_iterator<Iterator>::value
        && (sizeof(InputType) == 1 || sizeof(InputType) == 2)
      >
{};

} // end namespace detail

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op)
{
    // we're attempting to launch a kernel, assert we're compiling with nvcc
    // ========================================================================
    // X Note to the user: If you've found this line due to a compiler error, X
    // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
    // ========================================================================
    THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

    return detail::reduce_device(first, last, init, binary_op,
      typename detail::use_wide_reduction<InputIterator>::type());
}

template<typename RandomAccessIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  thrust::pair<SizeType,SizeType>
    get_blocked_reduce_n_schedule(RandomAccessIterator first,
                                  SizeType n,
                                  OutputType init,
                                  BinaryFunction binary_op)
{
  // dispatch on whether or not to use the wide reduction
  return thrust::detail::device::cuda::dispatch::get_blocked_reduce_n_schedule(first, n, init, binary_op,
    typename detail::use_wide_reduction<RandomAccessIterator>::type());
}

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

<commit_msg>Rename cuda::detail::reduce_device -> cuda::detail::reduce<commit_after>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  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.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

#pragma once

#include <thrust/device_ptr.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/static_assert.h>
#include <thrust/pair.h>

#include <thrust/detail/device/cuda/dispatch/reduce.h>
#include <thrust/detail/device/cuda/reduce_n.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{
//////////////
// Functors //
//////////////
template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType>
  struct wide_unary_op : public thrust::unary_function<WideType,OutputType>
{
    BinaryFunction binary_op;

    __host__ __device__
        wide_unary_op(BinaryFunction binary_op)
            : binary_op(binary_op) {}

    __host__ __device__
        OutputType operator()(WideType x)
        {
            WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1;

            OutputType sum = static_cast<InputType>(x & mask);

            for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++)
                sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) );

            return sum;
        }
};

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op,
                    thrust::detail::true_type)
{
    // "wide" reduction for small types like char, short, etc.
    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;
    typedef unsigned int WideType;

    // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType *

    // TODO use simple threshold and ensure alignment of wide_first

    // process first part
    size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); size_t n_wide = (last - first) / input_type_per_wide_type;

    const WideType * wide_first = reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first));

    OutputType result = thrust::detail::device::cuda::reduce_n
        (thrust::make_transform_iterator(wide_first, wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)),
         n_wide, init, binary_op);

    // process tail
    InputIterator tail_first = first + n_wide * input_type_per_wide_type;
    return thrust::detail::device::cuda::reduce_n(tail_first, last - tail_first, result, binary_op);
}

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op,
                    thrust::detail::false_type)
{
    // standard reduction
    return thrust::detail::device::cuda::reduce_n(first, last - first, init, binary_op);
}

template<typename Iterator, typename InputType = typename thrust::iterator_value<Iterator>::type>
  struct use_wide_reduction
    : thrust::detail::integral_constant<
        bool,
        thrust::detail::is_pod<InputType>::value
        && thrust::detail::is_trivial_iterator<Iterator>::value
        && (sizeof(InputType) == 1 || sizeof(InputType) == 2)
      >
{};

} // end namespace detail

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op)
{
    // we're attempting to launch a kernel, assert we're compiling with nvcc
    // ========================================================================
    // X Note to the user: If you've found this line due to a compiler error, X
    // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
    // ========================================================================
    THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

    return thrust::detail::device::cuda::detail::reduce(first, last, init, binary_op,
      typename detail::use_wide_reduction<InputIterator>::type());
}

template<typename RandomAccessIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  thrust::pair<SizeType,SizeType>
    get_blocked_reduce_n_schedule(RandomAccessIterator first,
                                  SizeType n,
                                  OutputType init,
                                  BinaryFunction binary_op)
{
  // dispatch on whether or not to use the wide reduction
  return thrust::detail::device::cuda::dispatch::get_blocked_reduce_n_schedule(first, n, init, binary_op,
    typename detail::use_wide_reduction<RandomAccessIterator>::type());
}

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

<|endoftext|>


<commit_before>#include "PsfLoader.h"
#include "StdStream.h"

#include "psx/PsxBios.h"
#include "ps2/PsfBios.h"
#include "Iop_PsfSubSystem.h"
#include "Ps2Const.h"

#include "psp/Psp_PsfSubSystem.h"

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

using namespace Framework;
using namespace std;
namespace filesystem = boost::filesystem;

void CPsfLoader::LoadPsf(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	size_t pathLength = strlen(pathString);
	if(pathString[pathLength - 1] == '2')
	{
		LoadPs2(virtualMachine, pathString, tags);
	}
	else if(pathString[pathLength - 1] == 'p')
	{
		LoadPsp(virtualMachine, pathString, tags);
	}
	else
	{
		LoadPsx(virtualMachine, pathString, tags);
	}
}

void CPsfLoader::LoadPsx(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Iop::PsfSubSystemPtr subSystem = Iop::PsfSubSystemPtr(new Iop::CPsfSubSystem());
	virtualMachine.SetSubSystem(subSystem);

	{
		Iop::CSubSystem::BiosPtr bios = Iop::CSubSystem::BiosPtr(new CPsxBios(virtualMachine.GetCpu(), virtualMachine.GetRam(), PS2::IOP_RAM_SIZE));
		subSystem->SetBios(bios);
		LoadPsxRecurse(virtualMachine, static_cast<CPsxBios*>(bios.get()), pathString, tags);
	}
}

void CPsfLoader::LoadPsxRecurse(CPsfVm& virtualMachine, CPsxBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATION)
	{
		throw runtime_error("Not a PlayStation psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	{
		uint32 sp = 0, pc = 0;
		if(libPath != NULL)
		{
			filesystem::path path(pathString);
			path = path.branch_path() / libPath;
			LoadPsxRecurse(virtualMachine, bios, path.string().c_str());
			sp = virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nV0;
			pc = virtualMachine.GetCpu().m_State.nPC;
		}
        bios->LoadExe(psfFile.GetProgram());
		if(sp != 0)
		{
			virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nD0 = static_cast<int32>(sp);
		}
		if(pc != 0)
		{
			virtualMachine.GetCpu().m_State.nPC = pc;
		}
	}
	{
		unsigned int currentLib = 2;
		while(1)
		{
			string libName = "_lib" + boost::lexical_cast<string>(currentLib);
			const char* libPath = psfFile.GetTagValue(libName.c_str());
			if(libPath == NULL)
			{
				break;
			}
			filesystem::path path(pathString);
			path = path.branch_path() / libPath;
			uint32 sp = virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nV0;
			uint32 pc = virtualMachine.GetCpu().m_State.nPC;
			LoadPsxRecurse(virtualMachine, bios, path.string().c_str());
			virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nD0 = static_cast<int32>(sp);
			virtualMachine.GetCpu().m_State.nPC = pc;
			currentLib++;
		}
	}
}

void CPsfLoader::LoadPs2(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Iop::PsfSubSystemPtr subSystem = Iop::PsfSubSystemPtr(new Iop::CPsfSubSystem());
	virtualMachine.SetSubSystem(subSystem);

	{
		Iop::CSubSystem::BiosPtr bios = Iop::CSubSystem::BiosPtr(new PS2::CPsfBios(virtualMachine.GetCpu(), virtualMachine.GetRam(), PS2::IOP_RAM_SIZE));
		subSystem->SetBios(bios);
	    LoadPs2Recurse(virtualMachine, static_cast<PS2::CPsfBios*>(bios.get()), pathString, tags);
		static_cast<PS2::CPsfBios*>(bios.get())->Start();
	}
}

void CPsfLoader::LoadPs2Recurse(CPsfVm& virtualMachine, PS2::CPsfBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATION2)
	{
		throw runtime_error("Not a PlayStation2 psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags != NULL)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	if(libPath != NULL)
	{
		filesystem::path path(pathString);
		path = path.branch_path() / libPath;
		LoadPs2Recurse(virtualMachine, bios, path.string().c_str());
	}
	bios->AppendArchive(psfFile);
}

void CPsfLoader::LoadPsp(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Psp::PsfSubSystemPtr subSystem = Psp::PsfSubSystemPtr(new Psp::CPsfSubSystem(0x00400000));
	virtualMachine.SetSubSystem(subSystem);

	{
		Psp::CPsfBios* bios = &subSystem->GetBios();
		LoadPspRecurse(virtualMachine, bios, pathString, tags);
		bios->Start();
	}
}

void CPsfLoader::LoadPspRecurse(CPsfVm& virtualMachine, Psp::CPsfBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATIONPORTABLE)
	{
		throw runtime_error("Not a PlayStation Portable psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags != NULL)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	if(libPath != NULL)
	{
		filesystem::path path(pathString);
		path = path.branch_path() / libPath;
		LoadPspRecurse(virtualMachine, bios, path.string().c_str());
	}
	bios->AppendArchive(psfFile);
}
<commit_msg>PsfPlayer: Doubled RAM amount in PspVm.<commit_after>#include "PsfLoader.h"
#include "StdStream.h"

#include "psx/PsxBios.h"
#include "ps2/PsfBios.h"
#include "Iop_PsfSubSystem.h"
#include "Ps2Const.h"

#include "psp/Psp_PsfSubSystem.h"

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

using namespace Framework;
using namespace std;
namespace filesystem = boost::filesystem;

void CPsfLoader::LoadPsf(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	size_t pathLength = strlen(pathString);
	if(pathString[pathLength - 1] == '2')
	{
		LoadPs2(virtualMachine, pathString, tags);
	}
	else if(pathString[pathLength - 1] == 'p')
	{
		LoadPsp(virtualMachine, pathString, tags);
	}
	else
	{
		LoadPsx(virtualMachine, pathString, tags);
	}
}

void CPsfLoader::LoadPsx(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Iop::PsfSubSystemPtr subSystem = Iop::PsfSubSystemPtr(new Iop::CPsfSubSystem());
	virtualMachine.SetSubSystem(subSystem);

	{
		Iop::CSubSystem::BiosPtr bios = Iop::CSubSystem::BiosPtr(new CPsxBios(virtualMachine.GetCpu(), virtualMachine.GetRam(), PS2::IOP_RAM_SIZE));
		subSystem->SetBios(bios);
		LoadPsxRecurse(virtualMachine, static_cast<CPsxBios*>(bios.get()), pathString, tags);
	}
}

void CPsfLoader::LoadPsxRecurse(CPsfVm& virtualMachine, CPsxBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATION)
	{
		throw runtime_error("Not a PlayStation psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	{
		uint32 sp = 0, pc = 0;
		if(libPath != NULL)
		{
			filesystem::path path(pathString);
			path = path.branch_path() / libPath;
			LoadPsxRecurse(virtualMachine, bios, path.string().c_str());
			sp = virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nV0;
			pc = virtualMachine.GetCpu().m_State.nPC;
		}
        bios->LoadExe(psfFile.GetProgram());
		if(sp != 0)
		{
			virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nD0 = static_cast<int32>(sp);
		}
		if(pc != 0)
		{
			virtualMachine.GetCpu().m_State.nPC = pc;
		}
	}
	{
		unsigned int currentLib = 2;
		while(1)
		{
			string libName = "_lib" + boost::lexical_cast<string>(currentLib);
			const char* libPath = psfFile.GetTagValue(libName.c_str());
			if(libPath == NULL)
			{
				break;
			}
			filesystem::path path(pathString);
			path = path.branch_path() / libPath;
			uint32 sp = virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nV0;
			uint32 pc = virtualMachine.GetCpu().m_State.nPC;
			LoadPsxRecurse(virtualMachine, bios, path.string().c_str());
			virtualMachine.GetCpu().m_State.nGPR[CMIPS::SP].nD0 = static_cast<int32>(sp);
			virtualMachine.GetCpu().m_State.nPC = pc;
			currentLib++;
		}
	}
}

void CPsfLoader::LoadPs2(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Iop::PsfSubSystemPtr subSystem = Iop::PsfSubSystemPtr(new Iop::CPsfSubSystem());
	virtualMachine.SetSubSystem(subSystem);

	{
		Iop::CSubSystem::BiosPtr bios = Iop::CSubSystem::BiosPtr(new PS2::CPsfBios(virtualMachine.GetCpu(), virtualMachine.GetRam(), PS2::IOP_RAM_SIZE));
		subSystem->SetBios(bios);
	    LoadPs2Recurse(virtualMachine, static_cast<PS2::CPsfBios*>(bios.get()), pathString, tags);
		static_cast<PS2::CPsfBios*>(bios.get())->Start();
	}
}

void CPsfLoader::LoadPs2Recurse(CPsfVm& virtualMachine, PS2::CPsfBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATION2)
	{
		throw runtime_error("Not a PlayStation2 psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags != NULL)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	if(libPath != NULL)
	{
		filesystem::path path(pathString);
		path = path.branch_path() / libPath;
		LoadPs2Recurse(virtualMachine, bios, path.string().c_str());
	}
	bios->AppendArchive(psfFile);
}

void CPsfLoader::LoadPsp(CPsfVm& virtualMachine, const char* pathString, CPsfBase::TagMap* tags)
{
	Psp::PsfSubSystemPtr subSystem = Psp::PsfSubSystemPtr(new Psp::CPsfSubSystem(0x00800000));
	virtualMachine.SetSubSystem(subSystem);

	{
		Psp::CPsfBios* bios = &subSystem->GetBios();
		LoadPspRecurse(virtualMachine, bios, pathString, tags);
		bios->Start();
	}
}

void CPsfLoader::LoadPspRecurse(CPsfVm& virtualMachine, Psp::CPsfBios* bios, const char* pathString, CPsfBase::TagMap* tags)
{
	CStdStream input(pathString, "rb");
	CPsfBase psfFile(input);
	if(psfFile.GetVersion() != CPsfBase::VERSION_PLAYSTATIONPORTABLE)
	{
		throw runtime_error("Not a PlayStation Portable psf.");
	}
	const char* libPath = psfFile.GetTagValue("_lib");
	if(tags != NULL)
	{
		tags->insert(psfFile.GetTagsBegin(), psfFile.GetTagsEnd());
	}
	if(libPath != NULL)
	{
		filesystem::path path(pathString);
		path = path.branch_path() / libPath;
		LoadPspRecurse(virtualMachine, bios, path.string().c_str());
	}
	bios->AppendArchive(psfFile);
}
<|endoftext|>


<commit_before>#include "ExecutionEngine.h"

#include <chrono>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>

#pragma GCC diagnostic pop

#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"

namespace dev
{
namespace eth
{
namespace jit
{

ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	if (auto cachedExec = Cache::findExec(key))
	{
		return run(*cachedExec, _data, _env);
	}

	auto module = Compiler({}).compile(_code);
	return run(std::move(module), _data, _env, _code);
}

ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
	auto module = _module.get(); // Keep ownership of the module in _module

	llvm::sys::PrintStackTraceOnErrorSignal();
	static const auto program = "EVM JIT";
	llvm::PrettyStackTraceProgram X(1, &program);

	auto&& context = llvm::getGlobalContext();

	llvm::InitializeNativeTarget();
	llvm::InitializeNativeTargetAsmPrinter();
	llvm::InitializeNativeTargetAsmParser();

	std::string errorMsg;
	llvm::EngineBuilder builder(module);
	//builder.setMArch(MArch);
	//builder.setMCPU(MCPU);
	//builder.setMAttrs(MAttrs);
	//builder.setRelocationModel(RelocModel);
	//builder.setCodeModel(CMModel);
	builder.setErrorStr(&errorMsg);
	builder.setEngineKind(llvm::EngineKind::JIT);
	builder.setUseMCJIT(true);
	builder.setMCJITMemoryManager(new llvm::SectionMemoryManager());
	builder.setOptLevel(llvm::CodeGenOpt::None);

	auto triple = llvm::Triple(llvm::sys::getProcessTriple());
	if (triple.getOS() == llvm::Triple::OSType::Win32)
		triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF);    // MCJIT does not support COFF format
	module->setTargetTriple(triple.str());

	ExecBundle exec;
	exec.engine.reset(builder.create());
	if (!exec.engine)
		return ReturnCode::LLVMConfigError;
	_module.release();  // Successfully created llvm::ExecutionEngine takes ownership of the module

	auto finalizationStartTime = std::chrono::high_resolution_clock::now();
	exec.engine->finalizeObject();
	auto finalizationEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();

	auto executionStartTime = std::chrono::high_resolution_clock::now();

	exec.entryFunc = module->getFunction("main");
	if (!exec.entryFunc)
		return ReturnCode::LLVMLinkError;

	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	auto& cachedExec = Cache::registerExec(key, std::move(exec));
	auto returnCode = run(cachedExec, _data, _env);

	auto executionEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
	//clog(JIT) << "Max stack size: " << Stack::maxStackSize;

	clog(JIT) << "\n";

	return returnCode;
}

ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)
{
	ReturnCode returnCode;
	Runtime runtime(_data, _env);

	auto r = setjmp(runtime.getJmpBuf());
	if (r == 0)
	{
		auto result = _exec.engine->runFunction(_exec.entryFunc, {{}, llvm::GenericValue(&runtime)});
		returnCode = static_cast<ReturnCode>(result.IntVal.getZExtValue());
	}
	else
		returnCode = static_cast<ReturnCode>(r);

	if (returnCode == ReturnCode::Return)
	{
		returnData = runtime.getReturnData();

		auto&& log = clog(JIT);
		log << "RETURN [ ";
		for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)
			log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " ";
		log << "]";
	}
	else
		clog(JIT) << "RETURN " << (int)returnCode;

	return returnCode;
}

}
}
}
<commit_msg>Change the way entry function is called.<commit_after>#include "ExecutionEngine.h"

#include <chrono>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>

#pragma GCC diagnostic pop

#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"

namespace dev
{
namespace eth
{
namespace jit
{

ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	if (auto cachedExec = Cache::findExec(key))
	{
		return run(*cachedExec, _data, _env);
	}

	auto module = Compiler({}).compile(_code);
	return run(std::move(module), _data, _env, _code);
}

ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
	auto module = _module.get(); // Keep ownership of the module in _module

	llvm::sys::PrintStackTraceOnErrorSignal();
	static const auto program = "EVM JIT";
	llvm::PrettyStackTraceProgram X(1, &program);

	auto&& context = llvm::getGlobalContext();

	llvm::InitializeNativeTarget();
	llvm::InitializeNativeTargetAsmPrinter();
	llvm::InitializeNativeTargetAsmParser();

	std::string errorMsg;
	llvm::EngineBuilder builder(module);
	//builder.setMArch(MArch);
	//builder.setMCPU(MCPU);
	//builder.setMAttrs(MAttrs);
	//builder.setRelocationModel(RelocModel);
	//builder.setCodeModel(CMModel);
	builder.setErrorStr(&errorMsg);
	builder.setEngineKind(llvm::EngineKind::JIT);
	builder.setUseMCJIT(true);
	builder.setMCJITMemoryManager(new llvm::SectionMemoryManager());
	builder.setOptLevel(llvm::CodeGenOpt::None);

	auto triple = llvm::Triple(llvm::sys::getProcessTriple());
	if (triple.getOS() == llvm::Triple::OSType::Win32)
		triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF);    // MCJIT does not support COFF format
	module->setTargetTriple(triple.str());

	ExecBundle exec;
	exec.engine.reset(builder.create());
	if (!exec.engine)
		return ReturnCode::LLVMConfigError;
	_module.release();  // Successfully created llvm::ExecutionEngine takes ownership of the module

	auto finalizationStartTime = std::chrono::high_resolution_clock::now();
	exec.engine->finalizeObject();
	auto finalizationEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();

	auto executionStartTime = std::chrono::high_resolution_clock::now();

	exec.entryFunc = module->getFunction("main");
	if (!exec.entryFunc)
		return ReturnCode::LLVMLinkError;

	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	auto& cachedExec = Cache::registerExec(key, std::move(exec));
	auto returnCode = run(cachedExec, _data, _env);

	auto executionEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
	//clog(JIT) << "Max stack size: " << Stack::maxStackSize;

	clog(JIT) << "\n";

	return returnCode;
}

ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)
{
	ReturnCode returnCode;
	Runtime runtime(_data, _env);

	std::vector<llvm::GenericValue> args{{}, llvm::GenericValue(&runtime)};
	llvm::GenericValue result;

	typedef ReturnCode(*EntryFuncPtr)(int, Runtime*);

	auto entryFuncVoidPtr = _exec.engine->getPointerToFunction(_exec.entryFunc);
	auto entryFuncPtr = static_cast<EntryFuncPtr>(entryFuncVoidPtr);

	auto r = setjmp(runtime.getJmpBuf());
	if (r == 0)
	{
		returnCode = entryFuncPtr(0, &runtime);
	}
	else
		returnCode = static_cast<ReturnCode>(r);

	if (returnCode == ReturnCode::Return)
	{
		returnData = runtime.getReturnData();

		auto&& log = clog(JIT);
		log << "RETURN [ ";
		for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)
			log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " ";
		log << "]";
	}
	else
		clog(JIT) << "RETURN " << (int)returnCode;

	return returnCode;
}

}
}
}
<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include <sstream>
#include <deque>
#include <list>
#include <set>
#include <algorithm>
#include "moses/ScoreComponentCollection.h"
#include "moses/TargetPhrase.h"
#include "moses/Hypothesis.h"
#include "moses/FF/NMT/NMT_Wrapper.h"
#include "moses/FF/NeuralScoreFeature.h"
#include "util/string_piece.hh"

namespace Moses
{

class NeuralScoreState : public FFState
{
public:
  NeuralScoreState(PyObject* context, const std::string& lastWord, PyObject* state)
  : m_context(context), m_lastWord(lastWord), m_state(state) {
    m_lastContext.push_back(m_lastWord);
  }

  NeuralScoreState(PyObject* context, const std::vector<std::string>& lastPhrase, PyObject* state)
  : m_context(context), m_lastWord(lastPhrase.back()), m_state(state) {
    for(size_t i = 0; i < lastPhrase.size(); i++)
      m_lastContext.push_back(lastPhrase[i]);
  }

  int Compare(const FFState& other) const
  {
    const NeuralScoreState &otherState = static_cast<const NeuralScoreState&>(other);
    if(m_lastContext.size() == otherState.m_lastContext.size() &&
        std::equal(m_lastContext.begin(),
                   m_lastContext.end(),
                   otherState.m_lastContext.begin()))
      return 0;
    return (std::lexicographical_compare(m_lastContext.begin(), m_lastContext.end(),
                   otherState.m_lastContext.begin(),
                   otherState.m_lastContext.end())) ? -1 : +1;
  }

  void LimitLength(size_t length) {
    while(m_lastContext.size() > length)
      m_lastContext.pop_front();
  }

  PyObject* GetContext() const {
    return m_context;
  }

  PyObject* GetState() const {
    return m_state;
  }

  std::string GetLastWord() const {
    return m_lastWord;
  }

private:
  PyObject* m_context;
  std::string m_lastWord;
  std::deque<std::string> m_lastContext;
  PyObject* m_state;
};

const FFState* NeuralScoreFeature::EmptyHypothesisState(const InputType &input) const {
  UTIL_THROW_IF2(input.GetType() != SentenceInput,
                 "This feature function requires the Sentence input type");

  const Sentence& sentence = static_cast<const Sentence&>(input);
  std::stringstream ss;
  for(size_t i = 0; i < sentence.GetSize(); i++)
    ss << sentence.GetWord(i).GetString(0) << " ";

  std::string sentenceString = Trim(ss.str());
  PyObject* pyContextVectors;
  m_wrapper->GetContextVectors(sentenceString, pyContextVectors);

  return new NeuralScoreState(pyContextVectors, "", NULL);
}

NeuralScoreFeature::NeuralScoreFeature(const std::string &line)
  : StatefulFeatureFunction(1, line), m_stateLength(3), m_factor(0),
    m_wrapper(new NMT_Wrapper())
{
  ReadParameters();
  m_wrapper->Init(m_statePath, m_modelPath, m_wrapperPath);
}

void NeuralScoreFeature::ProcessStack(const HypothesisStackNormal& hstack,
                                      const TranslationOptionCollection& to,
                                      size_t index) {

  PyObject* sourceContext = 0;
  std::vector<PyObject*> states;
  std::vector<std::string> lastWords;

  std::vector<std::set<std::string> > words;
  for (HypothesisStackNormal::const_iterator h = hstack.begin();
       h != hstack.end(); ++h) {
    Hypothesis& hypothesis = **h;

    const FFState* ffstate = hypothesis.GetFFState(index);
    const NeuralScoreState* state
      = static_cast<const NeuralScoreState*>(ffstate);

    states.push_back(state->GetState());
    lastWords.push_back(state->GetLastWord());

    if(sourceContext == 0)
      sourceContext = state->GetContext();

    const WordsBitmap hypoBitmap = hypothesis.GetWordsBitmap();
    const size_t hypoFirstGapPos = hypoBitmap.GetFirstGapPos();
    const size_t sourceSize = hypothesis.GetInput().GetSize();
    for (size_t startPos = hypoFirstGapPos ; startPos < sourceSize ; ++startPos) {
      TranslationOptionList const* tol;
      size_t endPos = startPos;
      for (tol = to.GetTranslationOptionList(startPos, endPos);
           tol && endPos < sourceSize;
           tol = to.GetTranslationOptionList(startPos, ++endPos)) {

        if (tol->size() == 0 || hypoBitmap.Overlap(WordsRange(startPos, endPos)))
          continue;

        TranslationOptionList::const_iterator iter;
        for (iter = tol->begin() ; iter != tol->end() ; ++iter) {
          const TranslationOption& to = **iter;
          const TargetPhrase& tp = to.GetTargetPhrase();
          if(tp.GetSize() > words.size())
            words.resize(tp.GetSize());
          for(size_t i = 0; i < tp.GetSize(); ++i)
            words[i].insert(to.GetTargetPhrase().GetWord(i).GetString(m_factor).as_string());
        }
      }
    }
  }

  std::vector<std::string> currWords(words[0].begin(), words[0].end());
  std::cerr << "Collected vocab test: " << currWords.size() << " " << states.size() << std::endl;

  std::vector<std::vector<double> > logProbs;
  std::vector<std::vector<PyObject*> > outputStates;

  m_wrapper->GetProb(currWords, sourceContext, lastWords, states,
                     logProbs, outputStates);

  std::cerr << "done" << std::endl;
  //for(size_t i = 0; i < words.size(); ++i) {
  //  std::cerr << i << " " << words[i].size() << std::endl;
  //}
}

void NeuralScoreFeature::EvaluateInIsolation(const Phrase &source
    , const TargetPhrase &targetPhrase
    , ScoreComponentCollection &scoreBreakdown
    , ScoreComponentCollection &estimatedFutureScore) const
{}

void NeuralScoreFeature::EvaluateWithSourceContext(const InputType &input
    , const InputPath &inputPath
    , const TargetPhrase &targetPhrase
    , const StackVec *stackVec
    , ScoreComponentCollection &scoreBreakdown
    , ScoreComponentCollection *estimatedFutureScore) const
{}

void NeuralScoreFeature::EvaluateTranslationOptionListWithSourceContext(const InputType &input
    , const TranslationOptionList &translationOptionList) const
{}

FFState* NeuralScoreFeature::EvaluateWhenApplied(
  const Hypothesis& cur_hypo,
  const FFState* prev_state,
  ScoreComponentCollection* accumulator) const
{
  NeuralScoreState* prevState = static_cast<NeuralScoreState*>(
                                  const_cast<FFState*>(prev_state));

  PyObject* context = prevState->GetContext();
  std::vector<float> newScores(m_numScoreComponents);

  double prob = 0;
  PyObject* nextState = NULL;
  const TargetPhrase& tp = cur_hypo.GetCurrTargetPhrase();
  std::vector<std::string> phrase;
  for(size_t i = 0; i < tp.GetSize(); ++i) {
    std::string word = tp.GetWord(i).GetString(m_factor).as_string();
    phrase.push_back(word);
  }

  m_wrapper->GetProb(phrase, context,
                     prevState->GetLastWord(),
                     prevState->GetState(),
                     prob, nextState);

  prevState = new NeuralScoreState(context, phrase, nextState);
  nextState = NULL;

  newScores[0] = prob;
  accumulator->PlusEquals(this, newScores);

  prevState->LimitLength(m_stateLength);
  return prevState;
}

FFState* NeuralScoreFeature::EvaluateWhenApplied(
  const ChartHypothesis& /* cur_hypo */,
  int /* featureID - used to index the state in the previous hypotheses */,
  ScoreComponentCollection* accumulator) const
{
  return new NeuralScoreState(NULL, "", NULL);
}

void NeuralScoreFeature::SetParameter(const std::string& key, const std::string& value)
{
  if (key == "state") {
    m_statePath = value;
  } else if (key == "state-length") {
    m_stateLength = Scan<size_t>(value);
  } else if (key == "model") {
    m_modelPath = value;
  } else if (key == "wrapper-path") {
    m_wrapperPath = value;
  } else {
    StatefulFeatureFunction::SetParameter(key, value);
  }
}

}

<commit_msg>small mods<commit_after>#include <vector>
#include <string>
#include <sstream>
#include <deque>
#include <list>
#include <set>
#include <algorithm>
#include "moses/ScoreComponentCollection.h"
#include "moses/TargetPhrase.h"
#include "moses/Hypothesis.h"
#include "moses/FF/NMT/NMT_Wrapper.h"
#include "moses/FF/NeuralScoreFeature.h"
#include "util/string_piece.hh"

namespace Moses
{

class NeuralScoreState : public FFState
{
public:
  NeuralScoreState(PyObject* context, const std::string& lastWord, PyObject* state)
  : m_context(context), m_lastWord(lastWord), m_state(state) {
    m_lastContext.push_back(m_lastWord);
  }

  NeuralScoreState(PyObject* context, const std::vector<std::string>& lastPhrase, PyObject* state)
  : m_context(context), m_lastWord(lastPhrase.back()), m_state(state) {
    for(size_t i = 0; i < lastPhrase.size(); i++)
      m_lastContext.push_back(lastPhrase[i]);
  }

  int Compare(const FFState& other) const
  {
    const NeuralScoreState &otherState = static_cast<const NeuralScoreState&>(other);
    if(m_lastContext.size() == otherState.m_lastContext.size() &&
        std::equal(m_lastContext.begin(),
                   m_lastContext.end(),
                   otherState.m_lastContext.begin()))
      return 0;
    return (std::lexicographical_compare(m_lastContext.begin(), m_lastContext.end(),
                   otherState.m_lastContext.begin(),
                   otherState.m_lastContext.end())) ? -1 : +1;
  }

  void LimitLength(size_t length) {
    while(m_lastContext.size() > length)
      m_lastContext.pop_front();
  }

  PyObject* GetContext() const {
    return m_context;
  }

  PyObject* GetState() const {
    return m_state;
  }

  std::string GetLastWord() const {
    return m_lastWord;
  }

private:
  PyObject* m_context;
  std::string m_lastWord;
  std::deque<std::string> m_lastContext;
  PyObject* m_state;
};

const FFState* NeuralScoreFeature::EmptyHypothesisState(const InputType &input) const {
  UTIL_THROW_IF2(input.GetType() != SentenceInput,
                 "This feature function requires the Sentence input type");

  const Sentence& sentence = static_cast<const Sentence&>(input);
  std::stringstream ss;
  for(size_t i = 0; i < sentence.GetSize(); i++)
    ss << sentence.GetWord(i).GetString(0) << " ";

  std::string sentenceString = Trim(ss.str());
  PyObject* pyContextVectors;
  m_wrapper->GetContextVectors(sentenceString, pyContextVectors);

  return new NeuralScoreState(pyContextVectors, "", NULL);
}

NeuralScoreFeature::NeuralScoreFeature(const std::string &line)
  : StatefulFeatureFunction(1, line), m_stateLength(3), m_factor(0),
    m_wrapper(new NMT_Wrapper())
{
  ReadParameters();
  m_wrapper->Init(m_statePath, m_modelPath, m_wrapperPath);
}

void NeuralScoreFeature::ProcessStack(const HypothesisStackNormal& hstack,
                                      const TranslationOptionCollection& to,
                                      size_t index) {

  PyObject* sourceContext = 0;
  std::vector<PyObject*> states;
  std::vector<std::string> lastWords;

  std::vector<std::set<std::string> > words;
  for (HypothesisStackNormal::const_iterator h = hstack.begin();
       h != hstack.end(); ++h) {
    Hypothesis& hypothesis = **h;

    const FFState* ffstate = hypothesis.GetFFState(index);
    const NeuralScoreState* state
      = static_cast<const NeuralScoreState*>(ffstate);

    states.push_back(state->GetState());
    lastWords.push_back(state->GetLastWord());

    if(sourceContext == 0)
      sourceContext = state->GetContext();

    const WordsBitmap hypoBitmap = hypothesis.GetWordsBitmap();
    const size_t hypoFirstGapPos = hypoBitmap.GetFirstGapPos();
    const size_t sourceSize = hypothesis.GetInput().GetSize();
    for (size_t startPos = hypoFirstGapPos ; startPos < sourceSize ; ++startPos) {
      TranslationOptionList const* tol;
      size_t endPos = startPos;
      for (tol = to.GetTranslationOptionList(startPos, endPos);
           tol && endPos < sourceSize;
           tol = to.GetTranslationOptionList(startPos, ++endPos)) {

        if (tol->size() == 0 || hypoBitmap.Overlap(WordsRange(startPos, endPos)))
          continue;

        TranslationOptionList::const_iterator iter;
        for (iter = tol->begin() ; iter != tol->end() ; ++iter) {
          const TranslationOption& to = **iter;
          const TargetPhrase& tp = to.GetTargetPhrase();
          if(tp.GetSize() > words.size())
            words.resize(tp.GetSize());
          for(size_t i = 0; i < tp.GetSize(); ++i)
            words[i].insert(to.GetTargetPhrase().GetWord(i).GetString(m_factor).as_string());
        }
      }
    }
  }

  // construct TRIE that has N states in nodes

  std::vector<std::string> currWords(words[0].begin(), words[0].end());
  std::cerr << "Collected vocab test: " << currWords.size() << " " << states.size() << std::endl;

  std::vector<std::vector<double> > logProbs;
  std::vector<std::vector<PyObject*> > outputStates;

  m_wrapper->GetProb(currWords, sourceContext, lastWords, states,
                     logProbs, outputStates);

  std::cerr << "done" << std::endl;
  //for(size_t i = 0; i < words.size(); ++i) {
  //  std::cerr << i << " " << words[i].size() << std::endl;
  //}
}

void NeuralScoreFeature::EvaluateInIsolation(const Phrase &source
    , const TargetPhrase &targetPhrase
    , ScoreComponentCollection &scoreBreakdown
    , ScoreComponentCollection &estimatedFutureScore) const
{}

void NeuralScoreFeature::EvaluateWithSourceContext(const InputType &input
    , const InputPath &inputPath
    , const TargetPhrase &targetPhrase
    , const StackVec *stackVec
    , ScoreComponentCollection &scoreBreakdown
    , ScoreComponentCollection *estimatedFutureScore) const
{}

void NeuralScoreFeature::EvaluateTranslationOptionListWithSourceContext(const InputType &input
    , const TranslationOptionList &translationOptionList) const
{}

FFState* NeuralScoreFeature::EvaluateWhenApplied(
  const Hypothesis& cur_hypo,
  const FFState* prev_state,
  ScoreComponentCollection* accumulator) const
{
  NeuralScoreState* prevState = static_cast<NeuralScoreState*>(
                                  const_cast<FFState*>(prev_state));

  PyObject* context = prevState->GetContext();
  std::vector<float> newScores(m_numScoreComponents);

  double prob = 0;
  PyObject* nextState = NULL;
  const TargetPhrase& tp = cur_hypo.GetCurrTargetPhrase();
  std::vector<std::string> phrase;
  for(size_t i = 0; i < tp.GetSize(); ++i) {
    std::string word = tp.GetWord(i).GetString(m_factor).as_string();
    phrase.push_back(word);
  }

  m_wrapper->GetProb(phrase, context,
                     prevState->GetLastWord(),
                     prevState->GetState(),
                     prob, nextState);

  prevState = new NeuralScoreState(context, phrase, nextState);
  nextState = NULL;

  newScores[0] = prob;
  accumulator->PlusEquals(this, newScores);

  prevState->LimitLength(m_stateLength);
  return prevState;
}

FFState* NeuralScoreFeature::EvaluateWhenApplied(
  const ChartHypothesis& /* cur_hypo */,
  int /* featureID - used to index the state in the previous hypotheses */,
  ScoreComponentCollection* accumulator) const
{
  return new NeuralScoreState(NULL, "", NULL);
}

void NeuralScoreFeature::SetParameter(const std::string& key, const std::string& value)
{
  if (key == "state") {
    m_statePath = value;
  } else if (key == "state-length") {
    m_stateLength = Scan<size_t>(value);
  } else if (key == "model") {
    m_modelPath = value;
  } else if (key == "wrapper-path") {
    m_wrapperPath = value;
  } else {
    StatefulFeatureFunction::SetParameter(key, value);
  }
}

}

<|endoftext|>


<commit_before>/*
Program which runs the performance tests and decides whether they succeeded.

Copyright 2014 Ilja Honkonen
All rights reserved.

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

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

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

* Neither the name of copyright holders nor the names of their contributors
  may be used to endorse or promote products derived from this software
  without specific prior written permission.

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

#include "chrono"
#include "cmath"
#include "cstdlib"
#include "iostream"
#include "string"

using namespace std;
using namespace std::chrono;

/*!
Runs the given program and returns the execution time in seconds.
*/
double run_test(const string& path)
{
	cout << "Running " + path + "...  ";
	cout.flush();

	const auto start = high_resolution_clock::now();
	if (system(path.c_str()) != EXIT_SUCCESS) {
		cout <<
			"Running " + path + " probably failed, "
			"was this program run from the gensimcell directory?\n";
		abort();
	}
	const auto end = high_resolution_clock::now();

	return duration_cast<duration<double>>(end - start).count();

}

int main(int, char**)
{
	const double allowed_relative_difference = 0.01;
	double run_time, ref_run_time;
	const string prefix("tests/serial/game_of_life/");

	run_time = run_test(prefix + "speed.exe"),
	ref_run_time = run_test(prefix + "speed_reference.exe");
	if (
		fabs(run_time - ref_run_time)
		<= allowed_relative_difference * max(run_time, ref_run_time)
	) {
		return EXIT_SUCCESS;
	}

	cout << "Too large difference in speeds, trying again just in case" << endl;
	run_time = run_test(prefix + "speed.exe"),
	ref_run_time = run_test(prefix + "speed_reference.exe");
	if (
		fabs(run_time - ref_run_time)
		> allowed_relative_difference * max(run_time, ref_run_time)
	) {
		cout << "Speed difference too large: "
			<< run_time << " s vs. " << ref_run_time
			<< " s\nFAILED" << endl;
		abort();
	}

	return EXIT_SUCCESS;
}
<commit_msg>Error out in game of life performance test only if gensimcell version is slower.<commit_after>/*
Program which runs the performance tests and decides whether they succeeded.

Copyright 2014 Ilja Honkonen
All rights reserved.

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

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

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

* Neither the name of copyright holders nor the names of their contributors
  may be used to endorse or promote products derived from this software
  without specific prior written permission.

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

#include "chrono"
#include "cmath"
#include "cstdlib"
#include "iostream"
#include "string"

using namespace std;
using namespace std::chrono;

/*!
Runs the given program and returns the execution time in seconds.
*/
double run_test(const string& path)
{
	cout << "Running " + path + "...  ";
	cout.flush();

	const auto start = high_resolution_clock::now();
	if (system(path.c_str()) != EXIT_SUCCESS) {
		cout <<
			"Running " + path + " probably failed, "
			"was this program run from the gensimcell directory?\n";
		abort();
	}
	const auto end = high_resolution_clock::now();

	return duration_cast<duration<double>>(end - start).count();

}

int main(int, char**)
{
	const double allowed_relative_difference = 0.01;
	double run_time, ref_run_time;
	const string prefix("tests/serial/game_of_life/");

	run_time = run_test(prefix + "speed.exe"),
	ref_run_time = run_test(prefix + "speed_reference.exe");
	if (
		run_time - ref_run_time
		<= allowed_relative_difference * max(run_time, ref_run_time)
	) {
		return EXIT_SUCCESS;
	}

	cout << "Reference too fast, trying again just in case" << endl;
	run_time = run_test(prefix + "speed.exe"),
	ref_run_time = run_test(prefix + "speed_reference.exe");
	if (
		run_time - ref_run_time
		> allowed_relative_difference * max(run_time, ref_run_time)
	) {
		cout << "Reference game of life too fast (struct: "
			<< ref_run_time << " s vs. gensimcell: " << run_time
			<< " s)\nFAILED" << endl;
		abort();
	}

	return EXIT_SUCCESS;
}
<|endoftext|>