<commit_before>/* Copyright (C) Extensible Service Proxy 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 "src/api_manager/service_management_fetch.h"

namespace google {
namespace api_manager {

namespace {
// The default HTTP request timeout in ms.
const int kHttpRequestTimeout = 1000;
// Maximum number of HTTP request retries
const int kHttpRequestRetries = 5;

// Default service management API url
const char kServiceManagementHost[] =
    "https://servicemanagement.googleapis.com";
const char kServiceManagementPath[] =
    "/google.api.servicemanagement.v1.ServiceManager";
}  // namespace anonymous

ServiceManagementFetch::ServiceManagementFetch(
    std::shared_ptr<context::GlobalContext> global_context)
    : global_context_(global_context), host_(kServiceManagementHost) {
  if (global_context_->server_config() &&
      global_context->server_config()->has_service_management_config()) {
    if (!global_context->server_config()
             ->service_management_config()
             .url()
             .empty()) {
      host_ =
          global_context->server_config()->service_management_config().url();
    }
  }

  if (global_context_->service_account_token()) {
    // register auth token for servicemanagement services
    global_context_->service_account_token()->SetAudience(
        auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES,
        host_ + kServiceManagementPath);
  }
}

void ServiceManagementFetch::GetConfig(const std::string& config_id,
                                       HttpCallbackFunction on_done) {
  const std::string url = host_ + "/v1/services/" +
                          global_context_->service_name() + "/configs/" +
                          config_id;
  Call(url, on_done);
}

void ServiceManagementFetch::GetRollouts(HttpCallbackFunction on_done) {
  const std::string url = host_ + "/v1/services/" +
                          global_context_->service_name() +
                          "/rollouts?filter=status=SUCCESS";
  Call(url, on_done);
}

void ServiceManagementFetch::Call(const std::string& url,
                                  HttpCallbackFunction on_done) {
  std::unique_ptr<HTTPRequest> http_request(new HTTPRequest([this, url,
                                                             on_done](
      utils::Status status, std::map<std::string, std::string>&& headers,
      std::string&& body) {

    if (!status.ok()) {
      global_context_->env()->LogError(std::string("Failed to call ") + url +
                                       ", Error: " + status.ToString() +
                                       ", Response body: " + body);

      // Handle NGX error as opposed to pass-through error code
      if (status.code() < 0) {
        status = utils::Status(Code::UNAVAILABLE,
                               "Failed to connect to the service management");
      } else {
        status = utils::Status(Code::UNAVAILABLE,
                               "Service management request was failed with "
                               "HTTP response code " +
                                   std::to_string(status.code()));
      }
    }

    on_done(status, std::move(body));
  }));

  http_request->set_url(url)
      .set_method("GET")
      .set_auth_token(GetAuthToken())
      .set_timeout_ms(kHttpRequestTimeout)
      .set_max_retries(kHttpRequestRetries);

  global_context_->env()->RunHTTPRequest(std::move(http_request));
}

const std::string& ServiceManagementFetch::GetAuthToken() {
  if (global_context_->service_account_token()) {
    return global_context_->service_account_token()->GetAuthToken(
        auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES);
  } else {
    static std::string empty;
    return empty;
  }
}

}  // namespace api_manager
}  // namespace google
<commit_msg>Increase timeout to call servicemanagement to 5s (#543)<commit_after>/* Copyright (C) Extensible Service Proxy 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 "src/api_manager/service_management_fetch.h"

namespace google {
namespace api_manager {

namespace {
// The default HTTP request timeout in ms.
// The latency to the service management service could be in seconds.
// This is a background checking process, is ok to have a big timeout.
// Hence use 5 seconds timeout.
const int kHttpRequestTimeout = 5000;
// Maximum number of HTTP request retries
const int kHttpRequestRetries = 5;

// Default service management API url
const char kServiceManagementHost[] =
    "https://servicemanagement.googleapis.com";
const char kServiceManagementPath[] =
    "/google.api.servicemanagement.v1.ServiceManager";
}  // namespace anonymous

ServiceManagementFetch::ServiceManagementFetch(
    std::shared_ptr<context::GlobalContext> global_context)
    : global_context_(global_context), host_(kServiceManagementHost) {
  if (global_context_->server_config() &&
      global_context->server_config()->has_service_management_config()) {
    if (!global_context->server_config()
             ->service_management_config()
             .url()
             .empty()) {
      host_ =
          global_context->server_config()->service_management_config().url();
    }
  }

  if (global_context_->service_account_token()) {
    // register auth token for servicemanagement services
    global_context_->service_account_token()->SetAudience(
        auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES,
        host_ + kServiceManagementPath);
  }
}

void ServiceManagementFetch::GetConfig(const std::string& config_id,
                                       HttpCallbackFunction on_done) {
  const std::string url = host_ + "/v1/services/" +
                          global_context_->service_name() + "/configs/" +
                          config_id;
  Call(url, on_done);
}

void ServiceManagementFetch::GetRollouts(HttpCallbackFunction on_done) {
  const std::string url = host_ + "/v1/services/" +
                          global_context_->service_name() +
                          "/rollouts?filter=status=SUCCESS";
  Call(url, on_done);
}

void ServiceManagementFetch::Call(const std::string& url,
                                  HttpCallbackFunction on_done) {
  std::unique_ptr<HTTPRequest> http_request(new HTTPRequest([this, url,
                                                             on_done](
      utils::Status status, std::map<std::string, std::string>&& headers,
      std::string&& body) {

    if (!status.ok()) {
      global_context_->env()->LogError(std::string("Failed to call ") + url +
                                       ", Error: " + status.ToString() +
                                       ", Response body: " + body);

      // Handle NGX error as opposed to pass-through error code
      if (status.code() < 0) {
        status = utils::Status(Code::UNAVAILABLE,
                               "Failed to connect to the service management");
      } else {
        status = utils::Status(Code::UNAVAILABLE,
                               "Service management request was failed with "
                               "HTTP response code " +
                                   std::to_string(status.code()));
      }
    }

    on_done(status, std::move(body));
  }));

  http_request->set_url(url)
      .set_method("GET")
      .set_auth_token(GetAuthToken())
      .set_timeout_ms(kHttpRequestTimeout)
      .set_max_retries(kHttpRequestRetries);

  global_context_->env()->RunHTTPRequest(std::move(http_request));
}

const std::string& ServiceManagementFetch::GetAuthToken() {
  if (global_context_->service_account_token()) {
    return global_context_->service_account_token()->GetAuthToken(
        auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES);
  } else {
    static std::string empty;
    return empty;
  }
}

}  // namespace api_manager
}  // namespace google
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by FThauer FHammer   *
 *   f.thauer@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 "game.h"

#include <enginefactory.h>
#include <guiinterface.h>

#include <iostream>
#include <sstream>

using namespace std;

Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
		   const PlayerDataList &playerDataList, const GameData &gameData,
		   const StartData &startData, int gameId)
: myFactory(factory), myGui(gui), actualHand(0), actualBoard(0),
  startQuantityPlayers(startData.numberOfPlayers),
  startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind),
  startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise),
  myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0), lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData)
{
	if(DEBUG_MODE) {
		startSmallBlind = 20;
		actualSmallBlind = startSmallBlind;
	}

// 	cout << "Create Game Object" << "\n";
	int i;

	actualHandID = 0;

// 	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// 		playerArray[i] = 0;
// 	}

	// Dealer Position bestimmen
	PlayerDataList::const_iterator player_i = playerDataList.begin();
	PlayerDataList::const_iterator player_end = playerDataList.end();

	while (player_i != player_end)
	{
		if ((*player_i)->GetUniqueId() == startData.startDealerPlayerId)
			break;
		++player_i;
	}
	assert(player_i != player_end);
	dealerPosition = startData.startDealerPlayerId;

	// Board erstellen
	actualBoard = myFactory->createBoard();

	seatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);
	activePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);
	runningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);

	// Player erstellen

	player_i = playerDataList.begin();
	player_end = playerDataList.end();
	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {

		string myName;
		string myAvatarFile;
		unsigned uniqueId = 0;
		PlayerType type = PLAYER_TYPE_COMPUTER;
		boost::shared_ptr<SessionData> myNetSession;

		if (player_i != player_end)
		{
			uniqueId = (*player_i)->GetUniqueId();
			type = (*player_i)->GetType();
			myName = (*player_i)->GetName();
			myAvatarFile = (*player_i)->GetAvatarFile();
			myNetSession = (*player_i)->GetNetSessionData();
			// TODO: set player type
			++player_i;
		}

		// create Player Objects
		boost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0);

		tmpPlayer->setNetSessionData(myNetSession);

		// fill player lists
		playerArray.push_back(tmpPlayer); // delete
		seatsList->push_back(tmpPlayer);
		if(startQuantityPlayers > i) {
			activePlayerList->push_back(tmpPlayer);
		}

		(*runningPlayerList) = (*activePlayerList);

		playerArray[i]->setNetSessionData(myNetSession); // delete

	}
	actualBoard->setPlayerLists(playerArray, seatsList, activePlayerList, runningPlayerList); // delete playerArray

	//start timer
	blindsTimer.reset();
	blindsTimer.start();
}

Game::~Game()
{
// 	cout << "Delete Game Object" << "\n";

	delete actualBoard;
	actualBoard = 0;
	delete actualHand;
	actualHand = 0;

}

HandInterface *Game::getCurrentHand()
{
	return actualHand;
}

const HandInterface *Game::getCurrentHand() const
{
	return actualHand;
}

void Game::initHand()
{

	size_t i;
	PlayerListConstIterator it_c;
	PlayerListIterator it, it_2;

	// eventuell vorhandene Hand löschen
	if(actualHand) {
		delete actualHand;
		actualHand = 0;
	}

	actualHandID++;

	// calculate smallBlind
	raiseBlinds();

	//Spieler Action auf 0 setzen
// 	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// 		playerArray[i]->setMyAction(0);
// 	}

	//Spieler Action auf 0 setzen
	for(it_c=seatsList->begin(); it_c!=seatsList->end(); it_c++) {
		(*it_c)->setMyAction(PLAYER_ACTION_NONE);
	}

	// Spieler mit leerem Cash auf inactive setzen
	it = activePlayerList->begin();

	while( it!=activePlayerList->end() ) {

		if((*it)->getMyCash() == 0) {
// 			cout << "playerID: " << (*it)->getMyID() << endl;
			(*it)->setMyActiveStatus(0);
			it = activePlayerList->erase(it);
		} else {
			it++;
		}
	}

// TODO HACK
	for(it=runningPlayerList->begin(); it!=runningPlayerList->end(); it++) {
		if (!(*it)->getMyActiveStatus())
		{
			if ((*it)->getMyUniqueID() == getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId())
			{
				it_2 = it;
				it_2++;
				if (it_2 == runningPlayerList->end())
					it_2 = runningPlayerList->begin();
				getCurrentHand()->getCurrentBeRo()->setCurrentPlayersTurnId((*it_2)->getMyUniqueID());
			}
		}
	}

	runningPlayerList->clear();
	(*runningPlayerList) = (*activePlayerList);

	// Hand erstellen
	actualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, seatsList, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); // delete playerArray

	// Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!! DELETE
// 	for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) {
//
// 		dealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS);
// 	}

	// Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!!
	bool nextDealerFound = false;
	PlayerListConstIterator dealerPositionIt = actualHand->getSeatIt(dealerPosition);
	assert( dealerPositionIt != seatsList->end() );

	for(i=0; i<seatsList->size(); i++) {

		dealerPositionIt++;
		if(dealerPositionIt == seatsList->end()) dealerPositionIt = seatsList->begin();

		it = actualHand->getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() );
		if(it != activePlayerList->end() ) {
			nextDealerFound = true;
			dealerPosition = (*it)->getMyUniqueID();
			break;
		}

	}
	assert(nextDealerFound);

}

void Game::startHand()
{
	assert(actualHand);

	//GUI bereinigen
	myGui->nextRoundCleanGui();

	myGui->logNewGameHandMsg(myGameID, actualHandID);

	actualHand->start();
}

boost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id)
{
	boost::shared_ptr<PlayerInterface> tmpPlayer;
	PlayerListIterator i = getSeatsList()->begin();
	PlayerListIterator end = getSeatsList()->end();
	while (i != end)
	{
		if ((*i)->getMyUniqueID() == id)
		{
			tmpPlayer = *i;
			break;
		}
		++i;
	}
	return tmpPlayer;
}

boost::shared_ptr<PlayerInterface> Game::getCurrentPlayer()
{
	boost::shared_ptr<PlayerInterface> tmpPlayer = getPlayerByUniqueId(getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId());
	assert(tmpPlayer.get());
	return tmpPlayer;
}

void Game::raiseBlinds() {

// 	cout << "timer minutes " << blindsTimer.elapsed().total_seconds()/60 << "\n";
// 	cout << "gameData.RaiseIntervalMode " << myGameData.RaiseIntervalMode << "\n";
// 	cout << "gameData.raiseMode " << myGameData.raiseMode << "\n";
// 	cout << "gameData.afterManualBlindsMode " << myGameData.afterManualBlindsMode << "\n";

	bool raiseBlinds = false;

	if (myGameData.raiseIntervalMode == RAISE_ON_HANDNUMBER) {

		if (lastHandBlindsRaised + myGameData.raiseSmallBlindEveryHandsValue <= actualHandID) {
			raiseBlinds = true;
			lastHandBlindsRaised = actualHandID;

// 			cout << "raise now on hands \n";
		}
	}
	else {
		if (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()/60) {
			raiseBlinds = true;
			lastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()/60;

// 			cout << "raise now on minutes \n";
		}
	}

	if (raiseBlinds) {

		// At this point, the blinds must be raised
		// Now we check how the blinds should be raised

		if (myGameData.raiseMode == DOUBLE_BLINDS) {
			actualSmallBlind *= 2;
// 			cout << "double small blind \n";
		}
		else {
			// Increase the position of the list
			list<int> blindsList = myGameData.manualBlindsList;
			list<int>::iterator it;

			if(!blindsList.empty()) {
				it = find(blindsList.begin(), blindsList.end(), actualSmallBlind);
				if(it !=  blindsList.end()) {
					it++;
// 					cout << "increase position in blindslist \n";
				}
				else {
// 					cout << "blindslist exceeds\n";
					if(actualSmallBlind == myGameData.firstSmallBlind) {
						it = blindsList.begin();
					}
				}
			}
// 			else {	cout << "blindslist is empty \n"; }
			// Check if we can get an element of the list or the position exceeds the lis
			if (blindsList.empty() || it ==  blindsList.end()) {

				// The position exceeds the list
				if (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) {
					actualSmallBlind *= 2;
// 					cout << "after blindslist double blind\n";
				}
				else {
					if(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) {
						actualSmallBlind += myGameData.afterMBAlwaysRaiseValue;
// 						cout << "after blindslist increase about x \n";
					}
// 					else { /* Stay at last blind */ cout << "after blindslist stay at last blind \n"; }
				}
			} else {
				// Grab the blinds amount from the list
				actualSmallBlind = *it;
// 				cout << "set new small blind from blindslist \n";
			}
		}
	}
}
<commit_msg>Fixed assertion fix.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by FThauer FHammer   *
 *   f.thauer@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 "game.h"

#include <enginefactory.h>
#include <guiinterface.h>

#include <iostream>
#include <sstream>

using namespace std;

Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,
		   const PlayerDataList &playerDataList, const GameData &gameData,
		   const StartData &startData, int gameId)
: myFactory(factory), myGui(gui), actualHand(0), actualBoard(0),
  startQuantityPlayers(startData.numberOfPlayers),
  startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind),
  startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise),
  myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0), lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData)
{
	if(DEBUG_MODE) {
		startSmallBlind = 20;
		actualSmallBlind = startSmallBlind;
	}

// 	cout << "Create Game Object" << "\n";
	int i;

	actualHandID = 0;

// 	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// 		playerArray[i] = 0;
// 	}

	// Dealer Position bestimmen
	PlayerDataList::const_iterator player_i = playerDataList.begin();
	PlayerDataList::const_iterator player_end = playerDataList.end();

	while (player_i != player_end)
	{
		if ((*player_i)->GetUniqueId() == startData.startDealerPlayerId)
			break;
		++player_i;
	}
	assert(player_i != player_end);
	dealerPosition = startData.startDealerPlayerId;

	// Board erstellen
	actualBoard = myFactory->createBoard();

	seatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);
	activePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);
	runningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);

	// Player erstellen

	player_i = playerDataList.begin();
	player_end = playerDataList.end();
	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {

		string myName;
		string myAvatarFile;
		unsigned uniqueId = 0;
		PlayerType type = PLAYER_TYPE_COMPUTER;
		boost::shared_ptr<SessionData> myNetSession;

		if (player_i != player_end)
		{
			uniqueId = (*player_i)->GetUniqueId();
			type = (*player_i)->GetType();
			myName = (*player_i)->GetName();
			myAvatarFile = (*player_i)->GetAvatarFile();
			myNetSession = (*player_i)->GetNetSessionData();
			// TODO: set player type
			++player_i;
		}

		// create Player Objects
		boost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0);

		tmpPlayer->setNetSessionData(myNetSession);

		// fill player lists
		playerArray.push_back(tmpPlayer); // delete
		seatsList->push_back(tmpPlayer);
		if(startQuantityPlayers > i) {
			activePlayerList->push_back(tmpPlayer);
		}

		(*runningPlayerList) = (*activePlayerList);

		playerArray[i]->setNetSessionData(myNetSession); // delete

	}
	actualBoard->setPlayerLists(playerArray, seatsList, activePlayerList, runningPlayerList); // delete playerArray

	//start timer
	blindsTimer.reset();
	blindsTimer.start();
}

Game::~Game()
{
// 	cout << "Delete Game Object" << "\n";

	delete actualBoard;
	actualBoard = 0;
	delete actualHand;
	actualHand = 0;

}

HandInterface *Game::getCurrentHand()
{
	return actualHand;
}

const HandInterface *Game::getCurrentHand() const
{
	return actualHand;
}

void Game::initHand()
{

	size_t i;
	PlayerListConstIterator it_c;
	PlayerListIterator it, it_2;

	// eventuell vorhandene Hand löschen
	if(actualHand) {
		delete actualHand;
		actualHand = 0;
	}

	actualHandID++;

	// calculate smallBlind
	raiseBlinds();

	//Spieler Action auf 0 setzen
// 	for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// 		playerArray[i]->setMyAction(0);
// 	}

	//Spieler Action auf 0 setzen
	for(it_c=seatsList->begin(); it_c!=seatsList->end(); it_c++) {
		(*it_c)->setMyAction(PLAYER_ACTION_NONE);
	}

	// Spieler mit leerem Cash auf inactive setzen
	it = activePlayerList->begin();

	while( it!=activePlayerList->end() ) {

		if((*it)->getMyCash() == 0) {
// 			cout << "playerID: " << (*it)->getMyID() << endl;
			(*it)->setMyActiveStatus(0);
			it = activePlayerList->erase(it);
		} else {
			it++;
		}
	}

// TODO HACK
	for(it=seatsList->begin(); it!=seatsList->end(); it++) {
		if (!(*it)->getMyActiveStatus())
		{
			if ((*it)->getMyUniqueID() == getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId())
			{
				it_2 = it;
				it_2++;
				if (it_2 == seatsList->end())
					it_2 = seatsList->begin();
				getCurrentHand()->getCurrentBeRo()->setCurrentPlayersTurnId((*it_2)->getMyUniqueID());
			}
		}
	}

	runningPlayerList->clear();
	(*runningPlayerList) = (*activePlayerList);

	// Hand erstellen
	actualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, seatsList, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); // delete playerArray

	// Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!! DELETE
// 	for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) {
//
// 		dealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS);
// 	}

	// Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!!
	bool nextDealerFound = false;
	PlayerListConstIterator dealerPositionIt = actualHand->getSeatIt(dealerPosition);
	assert( dealerPositionIt != seatsList->end() );

	for(i=0; i<seatsList->size(); i++) {

		dealerPositionIt++;
		if(dealerPositionIt == seatsList->end()) dealerPositionIt = seatsList->begin();

		it = actualHand->getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() );
		if(it != activePlayerList->end() ) {
			nextDealerFound = true;
			dealerPosition = (*it)->getMyUniqueID();
			break;
		}

	}
	assert(nextDealerFound);

}

void Game::startHand()
{
	assert(actualHand);

	//GUI bereinigen
	myGui->nextRoundCleanGui();

	myGui->logNewGameHandMsg(myGameID, actualHandID);

	actualHand->start();
}

boost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id)
{
	boost::shared_ptr<PlayerInterface> tmpPlayer;
	PlayerListIterator i = getSeatsList()->begin();
	PlayerListIterator end = getSeatsList()->end();
	while (i != end)
	{
		if ((*i)->getMyUniqueID() == id)
		{
			tmpPlayer = *i;
			break;
		}
		++i;
	}
	return tmpPlayer;
}

boost::shared_ptr<PlayerInterface> Game::getCurrentPlayer()
{
	boost::shared_ptr<PlayerInterface> tmpPlayer = getPlayerByUniqueId(getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId());
	assert(tmpPlayer.get());
	return tmpPlayer;
}

void Game::raiseBlinds() {

// 	cout << "timer minutes " << blindsTimer.elapsed().total_seconds()/60 << "\n";
// 	cout << "gameData.RaiseIntervalMode " << myGameData.RaiseIntervalMode << "\n";
// 	cout << "gameData.raiseMode " << myGameData.raiseMode << "\n";
// 	cout << "gameData.afterManualBlindsMode " << myGameData.afterManualBlindsMode << "\n";

	bool raiseBlinds = false;

	if (myGameData.raiseIntervalMode == RAISE_ON_HANDNUMBER) {

		if (lastHandBlindsRaised + myGameData.raiseSmallBlindEveryHandsValue <= actualHandID) {
			raiseBlinds = true;
			lastHandBlindsRaised = actualHandID;

// 			cout << "raise now on hands \n";
		}
	}
	else {
		if (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()/60) {
			raiseBlinds = true;
			lastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()/60;

// 			cout << "raise now on minutes \n";
		}
	}

	if (raiseBlinds) {

		// At this point, the blinds must be raised
		// Now we check how the blinds should be raised

		if (myGameData.raiseMode == DOUBLE_BLINDS) {
			actualSmallBlind *= 2;
// 			cout << "double small blind \n";
		}
		else {
			// Increase the position of the list
			list<int> blindsList = myGameData.manualBlindsList;
			list<int>::iterator it;

			if(!blindsList.empty()) {
				it = find(blindsList.begin(), blindsList.end(), actualSmallBlind);
				if(it !=  blindsList.end()) {
					it++;
// 					cout << "increase position in blindslist \n";
				}
				else {
// 					cout << "blindslist exceeds\n";
					if(actualSmallBlind == myGameData.firstSmallBlind) {
						it = blindsList.begin();
					}
				}
			}
// 			else {	cout << "blindslist is empty \n"; }
			// Check if we can get an element of the list or the position exceeds the lis
			if (blindsList.empty() || it ==  blindsList.end()) {

				// The position exceeds the list
				if (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) {
					actualSmallBlind *= 2;
// 					cout << "after blindslist double blind\n";
				}
				else {
					if(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) {
						actualSmallBlind += myGameData.afterMBAlwaysRaiseValue;
// 						cout << "after blindslist increase about x \n";
					}
// 					else { /* Stay at last blind */ cout << "after blindslist stay at last blind \n"; }
				}
			} else {
				// Grab the blinds amount from the list
				actualSmallBlind = *it;
// 				cout << "set new small blind from blindslist \n";
			}
		}
	}
}
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <time.h>
#include <stdio.h>

#include <string>

#include "game.h"
#include "menu.h"
#include "classes/Player.h"
#include "classes/Enemy.h"
#include "classes/Coin.h"
#include "classes/InfoPanel.h"

using namespace std;

const int numCoins = 10;

int startGame() {

    // Declared internally, to prevent ctors from running before main
    InfoPanel *infoPanel_game = new InfoPanel();
    Player player;
    Enemy  enemy;
    Coin   coins[numCoins];

    WINDOW *wgame = newwin(game_area.height(), game_area.width(), 1, 1);

    initscr();
    start_color();
    use_default_colors();
    init_pair(1, COLOR_RED, -1);
    init_pair(2, COLOR_YELLOW, -1);
    box(wgame, 0, 0);
    keypad(wgame, true);

    /*
     * Check if Player & Enemy are too near each other.
     * `42' here is the maximum allowable value, given
     * that Player may spawn in the middle (39, 19) of
     * the game_area.
     */
    while (player.getDistance(enemy.getPos()) <= 42) {
        // Reroll ctor for new random start
        enemy = Enemy();
    }

    // Init placement of Player, Enemy, and Coins
    wmove(wgame, player.getPos().y, player.getPos().x);
    waddch(wgame, player.getDispChar());

    wmove(wgame, enemy.getPos().y, enemy.getPos().x);
    waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));

    for (auto &coin : coins) {
        wmove(wgame, coin.getPos().y, coin.getPos().x);
        waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));
    }

    int ch, steps = 0, difficulty = 1;
    string infoKey, infoMsg = "";
    bool gameover = false;
    while (( ch = wgetch(wgame)) != 'q') {

        infoKey = to_string(ch);

        steps++;

        werase(wgame);
        box(wgame, 0, 0);

        int px = player.getPos().x;
        int py = player.getPos().y;

        switch (ch) {
            case KEY_UP:
            case 'k':
                if (py > (int) game_area.top()) player.moveUp();
                infoMsg = "up(" + to_string(py) + " > " + to_string(game_area.top()) + ")";
                break;
            case KEY_DOWN:
            case 'j':
                if (py < (int) game_area.bot()) player.moveDown(); // want bot:40
                infoMsg = "down(" + to_string(py) + " < " + to_string(game_area.bot()) + ")";
                break;
            case KEY_LEFT:
            case 'h':
                if (px > (int) game_area.left()) player.moveLeft();
                infoMsg = "left(" + to_string(px) + " > " + to_string(game_area.left()) + ")";
                break;
            case KEY_RIGHT:
            case 'l':
                if (px < (int) game_area.right()) player.moveRight(); // want right:80
                infoMsg = "right(" + to_string(px) + " < " + to_string(game_area.right()) + ")";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                break;
            default:
                player.wait();
                infoMsg = "waiting...";

        }

        // Draw Coins again, and check if player has landed on
        for (auto &coin : coins) {
            wmove(wgame, coin.getPos().y, coin.getPos().x);
            waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));
            if (player.atop(coin.getPos())) {
                player.addScore(coin.getValue());

                // Just zero out coin value and display for now
                coin.setValue(0);
                coin.setChar(' ');
            }
        }

        // Move Player to indicated position
        wmove(wgame, player.getPos().y, player.getPos().x);
        waddch(wgame, player.getDispChar());

        // Enemy, seek out player
        enemy.seek(player);  // Discard return (updated pos)
        wmove(wgame, enemy.getPos().y, enemy.getPos().x);
        waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));

        string proximityAlert = "";
        if (enemy.isAdjacent(player.getPos())) {
            proximityAlert = "!";
        }
        infoPanel_game->push('{'
            + std::to_string(player.getPos().x) + ','
            + std::to_string(player.getPos().y) + '}'
            + '{'
            + std::to_string(enemy.getPos().x) + ','
            + std::to_string(enemy.getPos().y) + '}'
            + " dist: "
            + std::to_string(player.getDistance(enemy.getPos()))
            + " steps: "
            + std::to_string(player.getSteps())
            + " ticks: "
            + std::to_string(player.getTicks())
            + " score: "
            + std::to_string(player.getScore())
            + " info: " + infoMsg
            + " " + proximityAlert
        );

        wrefresh(wgame);

        if (enemy.atop(player.getPos())) {
            // Game Over
            gameover = true;
            infoPanel_game->push("GAME OVER!");
            infoPanel_game->push("Press `q' to quit.");
            while (wgetch(wgame) != 'q');  // TODO prompt restart or quit
            break;
        }
    }

    delwin(wgame);
    return player.getScore() + steps * difficulty;  // TODO eventually return more information
}

<commit_msg>Add diagonal movement to Actor (for Player).<commit_after>#include <ncurses.h>
#include <time.h>
#include <stdio.h>

#include <string>

#include "game.h"
#include "menu.h"
#include "classes/Player.h"
#include "classes/Enemy.h"
#include "classes/Coin.h"
#include "classes/InfoPanel.h"

using namespace std;

const int numCoins = 10;

int startGame() {

    // Declared internally, to prevent ctors from running before main
    InfoPanel *infoPanel_game = new InfoPanel();
    Player player;
    Enemy  enemy;
    Coin   coins[numCoins];

    WINDOW *wgame = newwin(game_area.height(), game_area.width(), 1, 1);

    initscr();
    start_color();
    use_default_colors();
    init_pair(1, COLOR_RED, -1);
    init_pair(2, COLOR_YELLOW, -1);
    box(wgame, 0, 0);
    keypad(wgame, true);

    /*
     * Check if Player & Enemy are too near each other.
     * `42' here is the maximum allowable value, given
     * that Player may spawn in the middle (39, 19) of
     * the game_area.
     */
    while (player.getDistance(enemy.getPos()) <= 42) {
        // Reroll ctor for new random start
        enemy = Enemy();
    }

    // Init placement of Player, Enemy, and Coins
    wmove(wgame, player.getPos().y, player.getPos().x);
    waddch(wgame, player.getDispChar());

    wmove(wgame, enemy.getPos().y, enemy.getPos().x);
    waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));

    for (auto &coin : coins) {
        wmove(wgame, coin.getPos().y, coin.getPos().x);
        waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));
    }

    int ch, steps = 0, difficulty = 1;
    string infoKey, infoMsg = "";
    bool gameover = false;
    while (( ch = wgetch(wgame)) != 'q') {

        infoKey = to_string(ch);
        infoMsg = "";

        steps++;

        werase(wgame);
        box(wgame, 0, 0);

        int px = player.getPos().x;
        int py = player.getPos().y;

        switch (ch) {
            case 55:  // Key up-left
                if (py > (int) game_area.top() && px > (int) game_area.left()) {
                    player.moveUp();
                    player.moveLeft();
                }
                break;
            case 57:  // Key up-right
                if (py > (int) game_area.top() && px < (int) game_area.right()) {
                    player.moveUp();
                    player.moveRight();
                }
                break;
            case 51:  // Key down-right
                if (py < (int) game_area.bot() && px < (int) game_area.right()) {
                    player.moveDown();
                    player.moveRight();
                }
                break;
            case 49:  // Key down-left
                if (py < (int) game_area.bot() && px > (int) game_area.left()) {
                    player.moveDown();
                    player.moveLeft();
                }
                break;
            case KEY_UP:
            case 56:
            case 'k':
                if (py > (int) game_area.top()) player.moveUp();
                infoMsg = "up(" + to_string(py) + " > " + to_string(game_area.top()) + ")";
                break;
            case KEY_DOWN:
            case 50:
            case 'j':
                if (py < (int) game_area.bot()) player.moveDown();
                infoMsg = "down(" + to_string(py) + " < " + to_string(game_area.bot()) + ")";
                break;
            case KEY_LEFT:
            case 52:
            case 'h':
                if (px > (int) game_area.left()) player.moveLeft();
                infoMsg = "left(" + to_string(px) + " > " + to_string(game_area.left()) + ")";
                break;
            case KEY_RIGHT:
            case 54:
            case 'l':
                if (px < (int) game_area.right()) player.moveRight();
                infoMsg = "right(" + to_string(px) + " < " + to_string(game_area.right()) + ")";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                break;
            default:
                player.wait();
                infoMsg = "waiting...";

        }

        // Draw Coins again, and check if player has landed on
        for (auto &coin : coins) {
            wmove(wgame, coin.getPos().y, coin.getPos().x);
            waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));
            if (player.atop(coin.getPos())) {
                player.addScore(coin.getValue());

                // Just zero out coin value and display for now
                coin.setValue(0);
                coin.setChar(' ');
            }
        }

        // Move Player to indicated position
        wmove(wgame, player.getPos().y, player.getPos().x);
        waddch(wgame, player.getDispChar());

        // Enemy, seek out player
        enemy.seek(player);  // Discard return (updated pos)
        wmove(wgame, enemy.getPos().y, enemy.getPos().x);
        waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));

        string proximityAlert = "";
        if (enemy.isAdjacent(player.getPos())) {
            proximityAlert = "!";
        }
        infoPanel_game->push('{'
            + std::to_string(player.getPos().x) + ','
            + std::to_string(player.getPos().y) + '}'
            + '{'
            + std::to_string(enemy.getPos().x) + ','
            + std::to_string(enemy.getPos().y) + '}'
            + " dist: "
            + std::to_string(player.getDistance(enemy.getPos()))
            + " steps: "
            + std::to_string(player.getSteps())
            + " ticks: "
            + std::to_string(player.getTicks())
            + " score: "
            + std::to_string(player.getScore())
            + " info: " + infoMsg
            + " " + proximityAlert
        );

        wrefresh(wgame);

        if (enemy.atop(player.getPos())) {
            // Game Over
            gameover = true;
            infoPanel_game->push("GAME OVER!");
            infoPanel_game->push("Press `q' to quit.");
            while (wgetch(wgame) != 'q');  // TODO prompt restart or quit
            break;
        }
    }

    delwin(wgame);
    return player.getScore() + steps * difficulty;  // TODO eventually return more information
}

<|endoftext|>


<commit_before>#include "toplayer.h"
#include "domain.h"
#include <iostream>

using namespace std;

toplayer::toplayer()
{

}
void toplayer::run()
{
    help();
    cout << "\n Enter -help to display the command list again " << endl;
    while(selection())
    {

    }
}
void toplayer::help()
{
    cout << "*********************************************************" << endl;
    cout << "**        Notable Computer Scientists In History       **" << endl;
    cout << "**                                                     **" << endl;
    cout << "**     Enter -new to add a new person                  **" << endl;
    cout << "**     Enter -list for a full list                     **" << endl;
    cout << "**     Enter -search to search the list                **" << endl;
    cout << "**     Enter -remove to remove element from the list   **" << endl;
    cout << "**     Enter -sort to sort the list                    **" << endl;
    cout << "**     Enter -exit to exit the program                 **" << endl;
    cout << "**                                                     **" << endl;
    cout << "*********************************************************" << endl;
}

void toplayer::print(vector<Person>& pers) {

    for(unsigned int i = 0; i < pers.size(); i++) {
        cout.width(12);
        cout<<left;
        cout << pers[i].getFirstname();
        cout.width(12);
        cout<<left;
        cout << pers[i].getLastname();
        cout.width(10);
        cout<<left;
        cout << pers[i].getSex();
        cout.width(10);
        cout<<left;
        cout << pers[i].getBirth();
        cout.width(10);
        cout<<left;
        cout << pers[i].getDeath()<<endl;
    }
    cout << "================================================" << endl;
}

bool toplayer::selection()
{
    string input;
    cin >> input;
    if (input == "-list")
    {
        vector<Person> p;
        domain d;
        p = d.list();
        cout << "===================== List =====================" << endl;
        print(p);
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-search")
    {
        vector<Person> p;
        domain d;
        string whattype, input;
        cout << "What do you want to search for?" << endl;
        cout << "-firstname" << endl << "-lastname" << endl << "-sex"
             << endl << "-birth" << endl << "-death" << endl;
        cout << "Enter your choice: ";
        do {
            cin >> whattype;
            if (whattype != "-firstname" && whattype != "-lastname" && whattype != "-sex" &&
                whattype != "-birth" && whattype != "-death") {
                cout << whattype << " is not valid input! Try again: ";
            }
        } while (whattype != "-firstname" && whattype != "-lastname" && whattype != "-sex" &&
                 whattype != "-birth" && whattype != "-death");

        cout << "What is the word you want to search for? ";
        cin >> input;
        p = d.search(whattype, input);
        if (p.size() == 0){
            cout << "Sorry, no results!" << endl;
        } else {
            cout << "===== Search results =====" << endl;
            print(p);
        }
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-new")
    {
        string firstname, lastname, sex, birth, death;

        cout << "Enter first name: ";
        do {
            cin >> firstname;
            if (contains_number(firstname)) {
                cout << "First name can not contain numbers try again: ";
            }
        } while (contains_number(firstname));

        cout << "Enter last name: ";
        do {
            cin >> lastname;
            if (contains_number(lastname)) {
                cout << "Last name can not contain numbers try again: ";
            }
        } while (contains_number(lastname));

        cout << "Enter sex: ";
        do {
            cin >> sex;
            if (sex != "male" && sex != "female"){
                cout << sex << " is not a gender, please choose male or female: ";
            }
        } while (sex != "male" && sex != "female");

        cout << "Enter year of birth: ";
        do {
            cin >> birth;
            if (contains_letters(birth)){
                cout << "Year of death can not contain letters, try again: ";
            }
        } while (contains_letters(birth));

        cout << "Enter year of death, if the person has not died please type \"-\": ";
        do {
            cin >> death;
            if (contains_letters(death)){
                cout << "Year of death can not contain letters, try again: ";
            }
        } while (contains_letters(death));
        domain d;
        d.add(firstname, lastname, sex, birth, death);
        cout << "You successfully added a new person!" << endl << endl;
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-sort")
    {
        vector<Person> p;
        string input;
        cout << "What do you want to sort by?" << endl;
        cout << "-firstname" << endl << "-lastname" << endl << "-sex" << endl
             << "-birth" << endl << "-death" << endl;
        do {
            cin >> input;
            if (input != "-firstname" && input != "-lastname" && input != "-sex" &&
                input != "-birth" && input != "-death") {
                cout << input << " is not valid command! Try again: ";
            }
        } while (input != "-firstname" && input != "-lastname" && input != "-sex" &&
                 input != "-birth" && input != "-death");
        domain d;
        p = d.sort(input);

        cout << "===== Sorted list =====" << endl;
        print(p);
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-remove")
    {
        unsigned int lineNumber = 1;
        vector<Person> p;
        domain d;
        p = d.list();
        cout << "=========================== List ===========================" << endl;
        for(unsigned int i = 0; i < p.size(); i++){
            cout.width(10);
            cout << left;
            cout << i+1;
            cout.width(12);
            cout << left;
            cout << p[i].getFirstname();
            cout.width(12);
            cout << left;
            cout << p[i].getLastname();
            cout.width(10);
            cout << left;
            cout << p[i].getSex();
            cout.width(10);
            cout << left;
            cout << p[i].getBirth();
            cout.width(10);
            cout << left;
            cout << p[i].getDeath() << endl;

        }
        cout << "Which entry do you want to remove?" << endl;
        cout << "Type the line number: ";
        do {
            if (lineNumber <= 0 || lineNumber > p.size()) {
                cout << "Sorry this isn't a valid line, try again: ";
            }
            while (!(cin >> lineNumber)) {
               cin.clear();
               cin.ignore();
               cout << "Invalid input, try again: ";
            }

        } while (lineNumber <= 0 || lineNumber > p.size());
        p.erase (p.begin()+(lineNumber-1));
        d.remove(p);
        cout << "You successfully removed a line " << lineNumber << endl << endl;
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-help")
    {
        clearScreen();
        help();
    }
    else if (input == "-exit")
    {
        return false;
    }
    else
    {
        cout << "This command does not exist" << endl;
    }
    return true;
}

// Villutjekk, athugar hvort thad se tolustafur i strengnum
bool toplayer::contains_number(const string &c)
{
    return (c.find_first_of("0123456789") != string::npos);
}

bool toplayer::contains_letters(const string &c)
{
    return (c.find_first_of("qwertyuioplkjhgfdsazxcvbnm") != string::npos);
}

void toplayer::clearScreen()
{
    system("cls");
}
<commit_msg>sorted<commit_after>#include "toplayer.h"
#include "domain.h"
#include <iostream>

using namespace std;

toplayer::toplayer()
{

}
void toplayer::run()
{
    help();
    cout << "\n Enter -help to display the command list again " << endl;
    while(selection())
    {

    }
}
void toplayer::help()
{
    cout << "*********************************************************" << endl;
    cout << "**        Notable Computer Scientists In History       **" << endl;
    cout << "**                                                     **" << endl;
    cout << "**     Enter -new to add a new person                  **" << endl;
    cout << "**     Enter -list for a full list                     **" << endl;
    cout << "**     Enter -search to search the list                **" << endl;
    cout << "**     Enter -remove to remove element from the list   **" << endl;
    cout << "**     Enter -sort to sort the list                    **" << endl;
    cout << "**     Enter -exit to exit the program                 **" << endl;
    cout << "**                                                     **" << endl;
    cout << "*********************************************************" << endl;
}

void toplayer::print(vector<Person>& pers) {

    for(unsigned int i = 0; i < pers.size(); i++) {
        cout.width(12);
        cout<<left;
        cout << pers[i].getFirstname();
        cout.width(12);
        cout<<left;
        cout << pers[i].getLastname();
        cout.width(10);
        cout<<left;
        cout << pers[i].getSex();
        cout.width(10);
        cout<<left;
        cout << pers[i].getBirth();
        cout.width(10);
        cout<<left;
        cout << pers[i].getDeath()<<endl;
    }
    cout << "================================================" << endl;
}

bool toplayer::selection()
{
    string input;
    cin >> input;
    if (input == "-list")
    {
        vector<Person> p;
        domain d;
        p = d.list();
        cout << "===================== List =====================" << endl;
        print(p);
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-search")
    {
        vector<Person> p;
        domain d;
        string whattype, input;
        cout << "What do you want to search for?" << endl;
        cout << "-firstname" << endl << "-lastname" << endl << "-sex"
             << endl << "-birth" << endl << "-death" << endl;
        cout << "Enter your choice: ";
        do {
            cin >> whattype;
            if (whattype != "-firstname" && whattype != "-lastname" && whattype != "-sex" &&
                whattype != "-birth" && whattype != "-death") {
                cout << whattype << " is not valid input! Try again: ";
            }
        } while (whattype != "-firstname" && whattype != "-lastname" && whattype != "-sex" &&
                 whattype != "-birth" && whattype != "-death");

        cout << "What is the word you want to search for? ";
        cin >> input;
        p = d.search(whattype, input);
        if (p.size() == 0){
            cout << "Sorry, no results!" << endl;
        } else {
            cout << "===== Search results =====" << endl;
            print(p);
        }
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-new")
    {
        string firstname, lastname, sex, birth, death;

        cout << "Enter first name: ";
        do {
            cin >> firstname;
            if (contains_number(firstname)) {
                cout << "First name can not contain numbers try again: ";
            }
        } while (contains_number(firstname));

        cout << "Enter last name: ";
        do {
            cin >> lastname;
            if (contains_number(lastname)) {
                cout << "Last name can not contain numbers try again: ";
            }
        } while (contains_number(lastname));

        cout << "Enter sex: ";
        do {
            cin >> sex;
            if (sex != "male" && sex != "female"){
                cout << sex << " is not a gender, please choose male or female: ";
            }
        } while (sex != "male" && sex != "female");

        cout << "Enter year of birth: ";
        do {
            cin >> birth;
            if (contains_letters(birth)){
                cout << "Year of death can not contain letters, try again: ";
            }
        } while (contains_letters(birth));

        cout << "Enter year of death, if the person has not died please type \"-\": ";
        do {
            cin >> death;
            if (contains_letters(death)){
                cout << "Year of death can not contain letters, try again: ";
            }
        } while (contains_letters(death));
        domain d;
        d.add(firstname, lastname, sex, birth, death);
        cout << "You successfully added a new person!" << endl << endl;
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-sort")
    {
        vector<Person> p;
        string input;
        cout << "What do you want to sort by?" << endl;
        cout << "-firstname" << endl << "-lastname" << endl << "-sex" << endl
             << "-birth" << endl << "-death" << endl;
        do {
            cin >> input;
            if (input != "-firstname" && input != "-lastname" && input != "-sex" &&
                input != "-birth" && input != "-death") {
                cout << input << " is not valid command! Try again: ";
            }
        } while (input != "-firstname" && input != "-lastname" && input != "-sex" &&
                 input != "-birth" && input != "-death");
        domain d;
        p = d.sort(input);

        cout << "================== Sorted list =================" << endl;
        print(p);
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-remove")
    {
        unsigned int lineNumber = 1;
        vector<Person> p;
        domain d;
        p = d.list();
        cout << "=========================== List ===========================" << endl;
        for(unsigned int i = 0; i < p.size(); i++){
            cout.width(10);
            cout << left;
            cout << i+1;
            cout.width(12);
            cout << left;
            cout << p[i].getFirstname();
            cout.width(12);
            cout << left;
            cout << p[i].getLastname();
            cout.width(10);
            cout << left;
            cout << p[i].getSex();
            cout.width(10);
            cout << left;
            cout << p[i].getBirth();
            cout.width(10);
            cout << left;
            cout << p[i].getDeath() << endl;

        }
        cout << "Which entry do you want to remove?" << endl;
        cout << "Type the line number: ";
        do {
            if (lineNumber <= 0 || lineNumber > p.size()) {
                cout << "Sorry this isn't a valid line, try again: ";
            }
            while (!(cin >> lineNumber)) {
               cin.clear();
               cin.ignore();
               cout << "Invalid input, try again: ";
            }

        } while (lineNumber <= 0 || lineNumber > p.size());
        p.erase (p.begin()+(lineNumber-1));
        d.remove(p);
        cout << "You successfully removed a line " << lineNumber << endl << endl;
        system("pause");
        clearScreen();
        help();
    }
    else if (input == "-help")
    {
        clearScreen();
        help();
    }
    else if (input == "-exit")
    {
        return false;
    }
    else
    {
        cout << "This command does not exist" << endl;
    }
    return true;
}

// Villutjekk, athugar hvort thad se tolustafur i strengnum
bool toplayer::contains_number(const string &c)
{
    return (c.find_first_of("0123456789") != string::npos);
}

bool toplayer::contains_letters(const string &c)
{
    return (c.find_first_of("qwertyuioplkjhgfdsazxcvbnm") != string::npos);
}

void toplayer::clearScreen()
{
    system("cls");
}
<|endoftext|>


<commit_before>//http://keccak.noekeon.org/specs_summary.html

#include "hash.hpp"

#include <cstdint>
#include <stdexcept>

static const uint64_t round_constants[24]=
{
	0x0000000000000001,
	0x0000000000008082,
	0x800000000000808a,
	0x8000000080008000,
	0x000000000000808b,
	0x0000000080000001,
	0x8000000080008081,
	0x8000000000008009,
	0x000000000000008a,
	0x0000000000000088,
	0x0000000080008009,
	0x000000008000000a,
	0x000000008000808b,
	0x800000000000008b,
	0x8000000000008089,
	0x8000000000008003,
	0x8000000000008002,
	0x8000000000000080,
	0x000000000000800a,
	0x800000008000000a,
	0x8000000080008081,
	0x8000000000008080,
	0x0000000080000001,
	0x8000000080008008
};

static const uint64_t rotation_offsets[5][5]=
{
	{0,36,3,41,18},
	{1,44,10,45,2},
	{62,6,43,15,61},
	{28,55,25,21,56},
	{27,20,39,8,14}
};

static uint64_t rotl(const uint64_t xx,const size_t shift)
{
	return (xx<<(shift))|(xx>>(64-shift));
}

std::string hash_sha3_512(std::string message)
{
	size_t padding_length=72-((message.size())%72);

	for(size_t ii=0;ii<padding_length;++ii)
		message+=(char)0x00;

	if(padding_length>0)
	{
		message[message.size()-padding_length]|=0x01;
		message[message.size()-1]|=0x80;
	}

	uint64_t states[5][5];

	for(size_t yy=0;yy<5;++yy)
		for(size_t xx=0;xx<5;++xx)
			states[xx][yy]=0;

	for(size_t ii=0;ii<message.size()/72;++ii)
	{
		std::string block=message.substr(ii*72,72);

		for(size_t yy=0;yy<5;++yy)
			for(size_t xx=0;xx<5;++xx)
				if(xx+5*yy<9)
					states[xx][yy]^=*(uint64_t*)block.substr((xx+5*yy)*8,8).data();

		for(size_t round=0;round<24;++round)
		{
			uint64_t C[5];
			uint64_t D[5];
			for(size_t ii=0;ii<5;++ii)
				C[ii]=states[ii][0]^states[ii][1]^states[ii][2]^states[ii][3]^states[ii][4];
			for(size_t ii=0;ii<5;++ii)
				D[ii]=C[(ii+4)%5]^rotl(C[(ii+1)%5],1);
			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					states[ii][jj]^=D[ii];

			uint64_t B[5][5];
			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					B[jj][(2*ii+3*jj)%5]=rotl(states[ii][jj],rotation_offsets[ii][jj]);

			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					states[ii][jj]=B[ii][jj]^((~B[(ii+1)%5][jj])&B[(ii+2)%5][jj]);

			states[0][0]^=round_constants[round];
		}
	}

	std::string digest;

	for(size_t yy=0;yy<5;++yy)
	{
		for(size_t xx=0;xx<5;++xx)
		{
			if(xx+5*yy<9)
			{
				digest+=std::string((char*)&states[xx][yy],8);

				if(digest.size()>=64)
					return digest;
			}
		}
	}

	throw std::runtime_error("Error calculating SHA3-512 hash.");
}<commit_msg>Cleaned up theta step a bit...<commit_after>//http://keccak.noekeon.org/specs_summary.html

#include "hash.hpp"

#include <cstdint>
#include <stdexcept>

static const uint64_t round_constants[24]=
{
	0x0000000000000001,
	0x0000000000008082,
	0x800000000000808a,
	0x8000000080008000,
	0x000000000000808b,
	0x0000000080000001,
	0x8000000080008081,
	0x8000000000008009,
	0x000000000000008a,
	0x0000000000000088,
	0x0000000080008009,
	0x000000008000000a,
	0x000000008000808b,
	0x800000000000008b,
	0x8000000000008089,
	0x8000000000008003,
	0x8000000000008002,
	0x8000000000000080,
	0x000000000000800a,
	0x800000008000000a,
	0x8000000080008081,
	0x8000000000008080,
	0x0000000080000001,
	0x8000000080008008
};

static const uint64_t rotation_offsets[5][5]=
{
	{0,36,3,41,18},
	{1,44,10,45,2},
	{62,6,43,15,61},
	{28,55,25,21,56},
	{27,20,39,8,14}
};

static uint64_t rotl(const uint64_t xx,const size_t shift)
{
	return (xx<<(shift))|(xx>>(64-shift));
}

std::string hash_sha3_512(std::string message)
{
	size_t padding_length=72-((message.size())%72);

	for(size_t ii=0;ii<padding_length;++ii)
		message+=(char)0x00;

	if(padding_length>0)
	{
		message[message.size()-padding_length]|=0x01;
		message[message.size()-1]|=0x80;
	}

	uint64_t states[5][5];

	for(size_t yy=0;yy<5;++yy)
		for(size_t xx=0;xx<5;++xx)
			states[xx][yy]=0;

	for(size_t ii=0;ii<message.size()/72;++ii)
	{
		std::string block=message.substr(ii*72,72);

		for(size_t yy=0;yy<5;++yy)
			for(size_t xx=0;xx<5;++xx)
				if(xx+5*yy<9)
					states[xx][yy]^=*(uint64_t*)block.substr((xx+5*yy)*8,8).data();

		for(size_t round=0;round<24;++round)
		{
			uint64_t C[5];
			for(size_t ii=0;ii<5;++ii)
				C[ii]=states[ii][0]^states[ii][1]^states[ii][2]^states[ii][3]^states[ii][4];
			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					states[ii][jj]^=C[(ii+4)%5]^rotl(C[(ii+1)%5],1);

			uint64_t B[5][5];
			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					B[jj][(2*ii+3*jj)%5]=rotl(states[ii][jj],rotation_offsets[ii][jj]);

			for(size_t ii=0;ii<5;++ii)
				for(size_t jj=0;jj<5;++jj)
					states[ii][jj]=B[ii][jj]^((~B[(ii+1)%5][jj])&B[(ii+2)%5][jj]);

			states[0][0]^=round_constants[round];
		}
	}

	std::string digest;

	for(size_t yy=0;yy<5;++yy)
	{
		for(size_t xx=0;xx<5;++xx)
		{
			if(xx+5*yy<9)
			{
				digest+=std::string((char*)&states[xx][yy],8);

				if(digest.size()>=64)
					return digest;
			}
		}
	}

	throw std::runtime_error("Error calculating SHA3-512 hash.");
}<|endoftext|>


<commit_before>#include"ics3/ics3.hpp"

#include"core.hpp"
#include"ics3/eeprom.hpp"
#include"ics3/parameter.hpp"
#include"ics3/id.hpp"

static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept {
  return (rx[4] << 7) | rx[5];
}

static inline ics::Core::value getCmd(const int head, const ics::ID& id) {
  return head | id.get();
}

ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)
: core {Core::getCore(path, baudrate.getSpeed())}
{}

ics::Angle ics::ICS3::move(const ID& id, Angle angle) {
  static Core::Container tx(3), rx(6); // cache for runtime speed
  const auto send = angle.getRaw();
  tx[0] = getCmd(0x80, id);
  tx[1] = 0x7F & (send >> 7);
  tx[2] = 0x7F & send;
  core->communicate(tx, rx); // throw std::runtime_error
  angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend
  return angle;
}

ics::Angle ics::ICS3::free(const ID& id, Angle unit) {
  static Core::Container tx(3), rx(6); // cache for runtime speed
  tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0
  core->communicate(tx, rx); // throw std::runtime_error
  unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend
  return unit;
}

ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) {
  const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()};
  Core::Container rx(5);
  core->communicate(tx, rx); // throw std::runtime_error
  return Parameter::newParameter(type, rx[4]);
}

void ics::ICS3::set(const ID& id, const Parameter& param) {
  const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()};
  Core::Container rx(6);
  core->communicate(tx, rx); // throw std::runtime_error
}

ics::EepRom ics::ICS3::getRom(const ID& id) {
  const Core::Container tx {getCmd(0xA0, id), 0};
  Core::Container rx(68);
  core->communicate(tx, rx); // throw std::runtime_error
  EepRom::Container romData;
  std::copy(rx.cbegin() + 4, rx.cend(), romData.begin());
  return EepRom {romData}; // need friend
}

void ics::ICS3::setRom(const ID& id, const EepRom& rom) {
  Core::Container tx(66), rx(68);
  tx[0] = getCmd(0xC0, id); // tx[1] == 0
  rom.write(tx.begin() + 2);
  core->communicate(tx, rx); // throw std::runtime_error
}

ics::ID ics::ICS3::getID() {
  constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00};
  Core::IDContainerRx rx;
  core->communicateID(tx, rx);
  return ID {static_cast<ID::type>(0x1F & rx[4])};
}

void ics::ICS3::setID(const ID& id) {
  const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1};
  Core::IDContainerRx rx;
  core->communicateID(tx, rx);
}
<commit_msg>Update non explicit return object<commit_after>#include"ics3/ics3.hpp"

#include"core.hpp"
#include"ics3/eeprom.hpp"
#include"ics3/parameter.hpp"
#include"ics3/id.hpp"

static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept {
  return (rx[4] << 7) | rx[5];
}

static inline ics::Core::value getCmd(const int head, const ics::ID& id) {
  return head | id.get();
}

ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)
: core {Core::getCore(path, baudrate.getSpeed())}
{}

ics::Angle ics::ICS3::move(const ID& id, Angle angle) {
  static Core::Container tx(3), rx(6); // cache for runtime speed
  const auto send = angle.getRaw();
  tx[0] = getCmd(0x80, id);
  tx[1] = 0x7F & (send >> 7);
  tx[2] = 0x7F & send;
  core->communicate(tx, rx); // throw std::runtime_error
  angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend
  return angle;
}

ics::Angle ics::ICS3::free(const ID& id, Angle unit) {
  static Core::Container tx(3), rx(6); // cache for runtime speed
  tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0
  core->communicate(tx, rx); // throw std::runtime_error
  unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend
  return unit;
}

ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) {
  const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()};
  Core::Container rx(5);
  core->communicate(tx, rx); // throw std::runtime_error
  return Parameter::newParameter(type, rx[4]);
}

void ics::ICS3::set(const ID& id, const Parameter& param) {
  const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()};
  Core::Container rx(6);
  core->communicate(tx, rx); // throw std::runtime_error
}

ics::EepRom ics::ICS3::getRom(const ID& id) {
  const Core::Container tx {getCmd(0xA0, id), 0};
  Core::Container rx(68);
  core->communicate(tx, rx); // throw std::runtime_error
  EepRom::Container romData;
  std::copy(rx.cbegin() + 4, rx.cend(), romData.begin());
  return EepRom {romData}; // need friend
}

void ics::ICS3::setRom(const ID& id, const EepRom& rom) {
  Core::Container tx(66), rx(68);
  tx[0] = getCmd(0xC0, id); // tx[1] == 0
  rom.write(tx.begin() + 2);
  core->communicate(tx, rx); // throw std::runtime_error
}

ics::ID ics::ICS3::getID() {
  constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00};
  Core::IDContainerRx rx;
  core->communicateID(tx, rx);
  return {static_cast<ID::type>(0x1F & rx[4])};
}

void ics::ICS3::setID(const ID& id) {
  const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1};
  Core::IDContainerRx rx;
  core->communicateID(tx, rx);
}
<|endoftext|>


<commit_before>#include <merlin.h>

namespace merlin {

void
Merlin::Initialize(Handle<Object> target) {
    HandleScope scope;

    Handle<ObjectTemplate> merlin = ObjectTemplate::New();
    merlin->Set(String::NewSymbol("version"),
                String::New(MERLIN_VERSION));

    MagickWandGenesis();

    target->Set(String::NewSymbol("merlin"), merlin->NewInstance());
}

} // namespace

extern "C" void
init(Handle<Object> target)
{
    HandleScope scope;

    merlin::Merlin::Initialize(target);
}

<commit_msg>added constructors and initialized IM<commit_after>#include <merlin.h>

namespace merlin {

Merlin::Merlin() {
    // MagickWandGenesis();
}

Merlin::~Merlin() {
    MagickWandTerminus();
}

void
Merlin::Initialize(Handle<Object> target) {
    HandleScope scope;

    Handle<ObjectTemplate> merlin = ObjectTemplate::New();
    merlin->Set(String::NewSymbol("version"),
                String::New(MERLIN_VERSION));

    MagickWandGenesis();

    target->Set(String::NewSymbol("merlin"), merlin->NewInstance());
}

} // namespace

extern "C" void
init(Handle<Object> target)
{
    HandleScope scope;

    merlin::Merlin::Initialize(target);
}
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

bool is_unique() {
  return true;
}

TEST(is_unique_test, Dummy) {
  EXPECT_EQ(is_unique(), true);
}
<commit_msg>Solve IsUnique<commit_after>// Is Unique: Implement an algorithm to determine if a string has all unique
// characters. What if you cannot use additional data structures?

#include "gtest/gtest.h"

#include <algorithm>

bool is_unique(const std::string &s) {
  auto sorted = s;
  std::sort(sorted.begin(), sorted.end());
  for (int i = 1; i < sorted.size(); ++i) {
    if (sorted[i-1] == sorted[i]) {
      return false;
    }
  }
  return true;
}

TEST(is_unique_test, EmptyString) {
  EXPECT_EQ(is_unique(""), true);
}

TEST(is_unique_test, 2Chars_Duplicated) {
  EXPECT_EQ(is_unique("aa"), false);
}

TEST(is_unique_test, 2Chars_Unique) {
  EXPECT_EQ(is_unique("ab"), true);
}

TEST(is_unique_test, 4Chars_Duplicated) {
  EXPECT_EQ(is_unique("aaaa"), false);
}

TEST(is_unique_test, 4Chars_Unique) {
  EXPECT_EQ(is_unique("syen"), true);
}

TEST(is_unique_test, 4Chars_Duplicated_Start_End) {
  EXPECT_EQ(is_unique("abca"), false);
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 the ETH Zurich nor the names of its 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 "TypeAlias.h"
#include "../types/SymbolProviderType.h"

#include "ModelBase/src/nodes/TypedList.hpp"
template class Model::TypedList<OOModel::TypeAlias>;

namespace OOModel {

COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(TypeAlias)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(TypeAlias)

REGISTER_ATTRIBUTE(TypeAlias, typeExpression, Expression, false, false, true)
REGISTER_ATTRIBUTE(TypeAlias, typeArguments, TypedListOfFormalTypeArgument, false, false, true)

TypeAlias::TypeAlias(const QString &name, Expression *typeExpression)
: Super(nullptr, TypeAlias::getMetaData())
{
	setName(name);
	if (typeExpression) setTypeExpression(typeExpression);
}

Model::Node* TypeAlias::target() const
{
	Model::Node* ret{};

	auto type = this->typeExpression()->type();
	if (auto sp = dynamic_cast<SymbolProviderType*>(type))
		ret = sp->symbolProvider();

	SAFE_DELETE(type);

	return ret;
}

TypeAlias::SymbolTypes TypeAlias::symbolType() const
{
	if (auto t = target()) return t->symbolType();
	else return UNSPECIFIED;
}

bool TypeAlias::findSymbols(QSet<Node*>& result, const Model::SymbolMatcher& matcher, const Model::Node* source,
		FindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) const
{
	// TODO: Search type arguments

	if (direction == SEARCH_HERE)
	{
		if (symbolMatches(matcher, symbolTypes))
		{
			result.insert(const_cast<TypeAlias*>(this));
			return true;
		}
	}
	else if (direction == SEARCH_DOWN)
	{
		if (auto t = target())
			return t->findSymbols(result, matcher, t, SEARCH_DOWN, symbolTypes, false);
	}
	else if (direction == SEARCH_UP)
	{
		if (parent())
			return parent()->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes);
	}

	return false;
}

}
<commit_msg>Resolve type arguments in TypeAlias<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 the ETH Zurich nor the names of its 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 "TypeAlias.h"
#include "../types/SymbolProviderType.h"

#include "ModelBase/src/nodes/TypedList.hpp"
template class Model::TypedList<OOModel::TypeAlias>;

namespace OOModel {

COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(TypeAlias)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(TypeAlias)

REGISTER_ATTRIBUTE(TypeAlias, typeExpression, Expression, false, false, true)
REGISTER_ATTRIBUTE(TypeAlias, typeArguments, TypedListOfFormalTypeArgument, false, false, true)

TypeAlias::TypeAlias(const QString &name, Expression *typeExpression)
: Super(nullptr, TypeAlias::getMetaData())
{
	setName(name);
	if (typeExpression) setTypeExpression(typeExpression);
}

Model::Node* TypeAlias::target() const
{
	Model::Node* ret{};

	auto type = this->typeExpression()->type();
	if (auto sp = dynamic_cast<SymbolProviderType*>(type))
		ret = sp->symbolProvider();

	SAFE_DELETE(type);

	return ret;
}

TypeAlias::SymbolTypes TypeAlias::symbolType() const
{
	if (auto t = target()) return t->symbolType();
	else return UNSPECIFIED;
}

bool TypeAlias::findSymbols(QSet<Node*>& result, const Model::SymbolMatcher& matcher, const Model::Node* source,
		FindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) const
{
	bool found{};

	if (direction == SEARCH_HERE)
	{
		if (symbolMatches(matcher, symbolTypes))
		{
			result.insert(const_cast<TypeAlias*>(this));
			found = true;
		}
	}
	else if (direction == SEARCH_DOWN)
	{
		if (auto t = target())
			found = t->findSymbols(result, matcher, t, SEARCH_DOWN, symbolTypes, false);
	}
	else if (direction == SEARCH_UP)
	{
		auto ignore = childToSubnode(source);
		Q_ASSERT(ignore);
		if (typeArguments() != ignore)
		{
			found = typeArguments()->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found;
			qDebug() << typeArguments()->size() << found << matcher.matchPattern();
		}

		if ((exhaustAllScopes || !found) && parent())
			found = parent()->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes);
	}

	return found;
}

}
<|endoftext|>