<commit_before>#include <fstream>
#include <iostream>
#include <Windows.h>

#include "..\include\Common.h"
#include "..\include\Player.h"
#include "..\include\Enemy.h"

using namespace std;
using namespace Common;

#define GREY 7
#define DARK_GREY 7
#define RED 12
#define RED_BACKGROUND 207
#define GREY_BACKGROUND 127

void Player::SaveGame(){
    ofstream WriteData;
    WriteData.open("data.dat");
    WriteData << name << endl
              << level << endl
              << experience << endl
              << health << endl
              << arrows << endl
              << bombs << endl
              << potions << endl
              << whetstones << endl
              << weaponstrength << endl
              << queens;
    WriteData.close();
}

string Player::ReturnName(){
    ClearScreen();
    cout << " What is your name?"
         << endl << endl
         << " > ";
    cin >> name;
    return name;
}
void Player::SetPlayerData(){
    // Primarily initializes default values at the beginning of the game.

    /*
    // Sets health to maximum.
    health=100;

    // Sets level to 1, lowest level.
    level = 1;

    // Sets experience points to 0.
    experience = 0;

    // Gives player 10 arrows.
    arrows = 10;

    // Gives player 1 bomb.
    bombs = 1;

    // Sets weapon strength to maximum.
    weaponstrength=100;

    // Gives player 1 whetstone.
    whetstones=1;

    //Gives player 1 potion.
    potions=1;

    // Initializes player name to Player, in case player does not initialize a name.
    name = "Player";*/

    // Handle for SetConsoleTextAttribute()'s first argument.
    /// To be honest, don't know what this does.

    ifstream ReadData;
    ReadData.open("data.dat");

    if (!ReadData){
        ReadData.close();
        ofstream WriteData;
        WriteData.open("data.dat");
        WriteData << ReturnName() << endl
                  << 1 << endl
                  << 0 << endl
                  << 100 << endl
                  << 10 << endl
                  << 1 << endl
                  << 1 << endl
                  << 1 << endl
                  << 100 << endl
                  << 0;
        WriteData.close();
        ReadData.open("data.dat");
    }
    else
        ReadData.clear();

    ReadData >> name;
    ReadData >> level;
    ReadData >> experience;
    ReadData >> health;
    ReadData >> arrows;
    ReadData >> bombs;
    ReadData >> potions;
    ReadData >> whetstones;
    ReadData >> weaponstrength;
    ReadData >> queens;

    ReadData.close();
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
}

int Player::Attack(){
    // Returns the amount of attack points the player gives.
    // Also the main battle screen.

    int choice = 0;

    // Displays the inventory.
    DisplayInventory();

    // Gives player a list of moves to choose from.
    cout << "Choose your move:" << endl
         << "1) Attack" << endl
         << "2) Risk Attack" << endl
         << "3) Bow and Arrow" << endl
         << "4) Heal" << endl << endl
         << "5) Use Bomb" << endl
         << "6) Use Potion" << endl
         << "7) Use Whetstone" << endl
         << "0) Get me out of here!" << endl << endl
         << "> ";
    //cin >> choice;
    choice = input();
    cout << endl;

    // Evaluates player's choice.
    switch(choice){
        case 0:
            return Flee();
        case 1:
            // Player generically attacks.
            return GenericAttack();
        case 2:
            // Player takes a risk and attacks.
            return RiskAttack();
        case 3:
            // Player shoots their bow.
            if (arrows > 0) return BowAndArrow();
            else cout << "None in inventory!" << endl;
            break;
        case 4:
            // Player heals, no damage is done to enemy.
            Heal();
            break;
        case 5:
            // Player throws a bomb.
            // Does not execute if there are no bombs in the inventory.
            if (bombs>0) return UseBomb();
            else cout << "None in inventory!" << endl;
            break;
        case 6:
            // Player drinks a potion.
            // Does not execute if there are no potions in the inventory.
            // No damage is done to the enemy.
            if (potions>0) UsePotion();
            else cout << "None in inventory!" << endl;
            break;
        case 7:
            // Player sharpens their weapon with a whetstone.
            // Does not execute if there are no whetstones in inventory.
            // No damage is done to the enemy.
            if (whetstones>0) UseWhetstone();
            else cout << "None in inventory!" << endl;
            break;
        default:
            // Generically attacks by default if player's choice does not equal above cases.
            return GenericAttack();
    }
    // No damage is done. This line is called when the player heals, uses a potion, or uses a whetstone.
    return 0;
}

void Player::TakeDamage(int damage){
    // Simply deducts damage points from total health.
    health -= damage;
}

void Player::AddToInventory(int _arrows, int _whetstones, int _potions, int _bombs, int _queens){
    // Adds items to inventory and prints out what the player received.

    // Adds items received to total items.
    arrows+=_arrows;
    whetstones+=_whetstones;
    potions+=_potions;
    bombs += _bombs;
    queens += _queens;

    // Prints number of items received.
    cout << "You have gained: " << endl
         << "[" << _arrows << "] arrows + " << endl
         << "[" << _bombs << "] bombs + " << endl
         << "[" << _potions << "] potions +" << endl
         << "[" << _whetstones << "] whetstones" << endl
         << "[" << _queens << "] Queens" << endl << endl;
}

void Player::DisplayHealthBar(Enemy *_Enemy){
    // Displays player's name and health bar. Enemy object is used to print name on the same line as player name for aesthetics.

    // Prints player's name.
    cout << endl;
    DisplayName();
    // Tabs to make room for enemy's name.
    if (name.length() > 5){
        cout << "\t";
    }
    else {
        cout <<" \t\t";
    }
    // Prints enemy name.
    _Enemy->DisplayName();

    /// The following lines contain the code for the health bar.
    /// Being difficult to explain, no comments will explain why
    /// SetConsoleTextAttribute() is used, why it evaluates the health, why it prints blank spaces, etc.
    /// Intuition will be enough to understand what is going on in the following lines.

    string healthBar = "    " + std::to_string(health);

    for (int i = healthBar.length(); i < 10; i++)
        healthBar += " ";

    cout << endl;
    for (int i = 0; i < healthBar.length(); i++){
        if ((i+1)*10 <= health){
            SetConsoleTextAttribute(hConsole, RED_BACKGROUND);
            cout << healthBar.at(i);
        }
        else {
            SetConsoleTextAttribute(hConsole, GREY_BACKGROUND);
            cout << healthBar.at(i);
        }
    }

    SetConsoleTextAttribute(hConsole, GREY);
}

void Player::ReplenishHealth(){
    // Adds 30 health points after player has defeated an enemy.
    health+=30;
    if (health>100) health=100;
}

bool Player::IsDead(){
    // Returns a bool value, if the player's health is equal or below 0.
    if (health <= 0) {
        cout << "You're dead!" << endl << endl;
        Sleep(SLEEP_MS);
        return true;
    }
    return false;
}

void Player::DisplayName(){
    // Prints the player's name is dark gray for aesthetic purposes.

    // Sets text to dark grey.
    SetConsoleTextAttribute(hConsole, DARK_GREY);

    // Prints the player's name.
    cout << name;

    // Sets text back to normal gray.
    SetConsoleTextAttribute(hConsole, GREY);
}

void Player::AddExperience(int xp){
    // Adds points to the player's experience and levels player up.

    // Adds experience from passed in integer to local class variable experience.
    experience += xp;

    // Evaluates if experience is higher than 99, which means a level up is in order.
    if (experience>99) {
        // Experience is set to 0.
        experience = 0;

        // Player is leveled up.
        level+=1;

        // Sets level cap to 50, player cannot level higher than that.
        if (level >= 50) level = 50;

        // Alerts player that they have leveled up.
        cout << "You leveled up! Now you are level " << level << "!" << endl;
        Sleep(SLEEP_MS);
    }
}

void Player::LoseExperience(int xp){
    // Deducts points from the player's experience and de-levels player.

    // Deducts experience from passed in integer to local class variable experience.
    experience -= xp;

    // Evaluates if experience is less than 0.
    if (experience<0){
        // Experience is deducted continuing from the experience which de-leveled the player (hard to explain...)
        experience = 100-(0-experience);

        // De-levels player.
        level-=1;

        // Checks any glitches and sets player level to 1 if level is below 1 or above 50.
        // Also resets experience points.
        if (level<1 || level>50){
            level=1;
            experience = 0;
        }

        // Alerts the player that they have de-leveled.
        else {
            cout << "You de-leveled back to level " << level << "..." << endl;
            Sleep(SLEEP_MS);
        }
    }
}

void Player::AddQueens(int q){
    queens += q;
}

void Player::LoseQueens(int q){
    queens -= q;
    if (queens < 0) queens = 0;
}

void Player::DisplayInventory(){
    // Checks valid weapon strength.
    if (weaponstrength < 0){
        weaponstrength = 0;
    }
    // Simply prints the player's inventory.

    cout << "*------- INVENTORY -------* " << endl;
    cout << "Level " << level << "\t\t" << experience << "/100 xp" << endl;
    cout << "| Arrows: [" << arrows << "]" << endl;
    cout << "| Potions: [" << potions << "]" << endl;
    cout << "| Bombs: [" << bombs << "]" << endl;
    cout << "| Whetstones: [" << whetstones << "]" << endl;
    cout << "| Weapon strength: [" << weaponstrength << "%]" << endl;
    cout << "| Wealth: [" << queens << "] Queens" << endl;
    cout << "--------------------------- " << endl << endl;
}

int Player::GenericAttack(){
    int damage = ReturnDamage();
    DeductDamage(damage);
    DisplayName();
    cout << " attacks! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    if (damage>0) weaponstrength-= 2+rand()%5;
    return damage;
}

int Player::RiskAttack(){
    int damage = ReturnRiskAttackDamage();
    DeductDamage(damage);
    DisplayName();
    cout << " takes a risk and attack! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    if (damage>0) weaponstrength-= 4+rand()%5;
    return damage;
}

int Player::BowAndArrow(){
    int damage = ReturnBowDamage();
    DisplayName();
    cout << " shoots his bow! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    return damage;
}

void Player::UseWhetstone(){
    weaponstrength=100;
    DisplayName();
    cout << " sharpened his weapon!" << endl;
    whetstones--;
}

void Player::UsePotion(){
    health=100;
    DisplayName();
    cout << " drank a healing potion!" << endl;
    potions--;
}

int Player::UseBomb(){
    DisplayName();
    cout << " hurls a bomb! ";
    DisplayName();
    cout << " deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << "50";
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    bombs--;
    return 50;
}

void Player::DeductDamage(int &damage){
    if (weaponstrength<=75&&weaponstrength>50)
        damage-=1;
    else if (weaponstrength<=50&&weaponstrength>30)
        damage-=4;
    else if (weaponstrength<=30&&weaponstrength>20)
        damage-=5;
    else if (weaponstrength<=20&&weaponstrength>10)
        damage-=6;
    else if (weaponstrength<=10)
        damage-=7;
    if (damage<0)
        damage=0;
}

int Player::ReturnBowDamage(){
    if (arrows < 1)
        return 0;
    arrows--;
    return 10+rand()%6; // 10 - 15
}

void Player::Heal(){
    int heal = ReturnHealAmount();
    health += heal;
    if (health > 100) health = 100;
    DisplayName();
    cout << " gains ";
    SetConsoleTextAttribute(hConsole, 10);
    cout << heal;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " HP! ";
    DisplayName();
    cout << " now has " << health << "HP!" << endl;
}

int Player::Flee(){
    DisplayName();
    cout << " chooses to flee!" << endl;
    return -1;
}

<commit_msg>Changed savefile name to data.txt<commit_after>#include <fstream>
#include <iostream>
#include <Windows.h>

#include "..\include\Common.h"
#include "..\include\Player.h"
#include "..\include\Enemy.h"

using namespace std;
using namespace Common;

#define GREY 7
#define DARK_GREY 7
#define RED 12
#define RED_BACKGROUND 207
#define GREY_BACKGROUND 127

void Player::SaveGame(){
    ofstream WriteData;
    WriteData.open("data.txt");
    WriteData << name << endl
              << level << endl
              << experience << endl
              << health << endl
              << arrows << endl
              << bombs << endl
              << potions << endl
              << whetstones << endl
              << weaponstrength << endl
              << queens;
    WriteData.close();
}

string Player::ReturnName(){
    ClearScreen();
    cout << " What is your name?"
         << endl << endl
         << " > ";
    cin >> name;
    return name;
}
void Player::SetPlayerData(){
    // Primarily initializes default values at the beginning of the game.

    /*
    // Sets health to maximum.
    health=100;

    // Sets level to 1, lowest level.
    level = 1;

    // Sets experience points to 0.
    experience = 0;

    // Gives player 10 arrows.
    arrows = 10;

    // Gives player 1 bomb.
    bombs = 1;

    // Sets weapon strength to maximum.
    weaponstrength=100;

    // Gives player 1 whetstone.
    whetstones=1;

    //Gives player 1 potion.
    potions=1;

    // Initializes player name to Player, in case player does not initialize a name.
    name = "Player";*/

    // Handle for SetConsoleTextAttribute()'s first argument.
    /// To be honest, don't know what this does.

    ifstream ReadData;
    ReadData.open("data.txt");

    if (!ReadData){
        ReadData.close();
        ofstream WriteData;
        WriteData.open("data.txt");
        WriteData << ReturnName() << endl
                  << 1 << endl
                  << 0 << endl
                  << 100 << endl
                  << 10 << endl
                  << 1 << endl
                  << 1 << endl
                  << 1 << endl
                  << 100 << endl
                  << 0;
        WriteData.close();
        ReadData.open("data.txt");
    }
    else
        ReadData.clear();

    ReadData >> name;
    ReadData >> level;
    ReadData >> experience;
    ReadData >> health;
    ReadData >> arrows;
    ReadData >> bombs;
    ReadData >> potions;
    ReadData >> whetstones;
    ReadData >> weaponstrength;
    ReadData >> queens;

    ReadData.close();
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
}

int Player::Attack(){
    // Returns the amount of attack points the player gives.
    // Also the main battle screen.

    int choice = 0;

    // Displays the inventory.
    DisplayInventory();

    // Gives player a list of moves to choose from.
    cout << "Choose your move:" << endl
         << "1) Attack" << endl
         << "2) Risk Attack" << endl
         << "3) Bow and Arrow" << endl
         << "4) Heal" << endl << endl
         << "5) Use Bomb" << endl
         << "6) Use Potion" << endl
         << "7) Use Whetstone" << endl
         << "0) Get me out of here!" << endl << endl
         << "> ";
    //cin >> choice;
    choice = input();
    cout << endl;

    // Evaluates player's choice.
    switch(choice){
        case 0:
            return Flee();
        case 1:
            // Player generically attacks.
            return GenericAttack();
        case 2:
            // Player takes a risk and attacks.
            return RiskAttack();
        case 3:
            // Player shoots their bow.
            if (arrows > 0) return BowAndArrow();
            else cout << "None in inventory!" << endl;
            break;
        case 4:
            // Player heals, no damage is done to enemy.
            Heal();
            break;
        case 5:
            // Player throws a bomb.
            // Does not execute if there are no bombs in the inventory.
            if (bombs>0) return UseBomb();
            else cout << "None in inventory!" << endl;
            break;
        case 6:
            // Player drinks a potion.
            // Does not execute if there are no potions in the inventory.
            // No damage is done to the enemy.
            if (potions>0) UsePotion();
            else cout << "None in inventory!" << endl;
            break;
        case 7:
            // Player sharpens their weapon with a whetstone.
            // Does not execute if there are no whetstones in inventory.
            // No damage is done to the enemy.
            if (whetstones>0) UseWhetstone();
            else cout << "None in inventory!" << endl;
            break;
        default:
            // Generically attacks by default if player's choice does not equal above cases.
            return GenericAttack();
    }
    // No damage is done. This line is called when the player heals, uses a potion, or uses a whetstone.
    return 0;
}

void Player::TakeDamage(int damage){
    // Simply deducts damage points from total health.
    health -= damage;
}

void Player::AddToInventory(int _arrows, int _whetstones, int _potions, int _bombs, int _queens){
    // Adds items to inventory and prints out what the player received.

    // Adds items received to total items.
    arrows+=_arrows;
    whetstones+=_whetstones;
    potions+=_potions;
    bombs += _bombs;
    queens += _queens;

    // Prints number of items received.
    cout << "You have gained: " << endl
         << "[" << _arrows << "] arrows + " << endl
         << "[" << _bombs << "] bombs + " << endl
         << "[" << _potions << "] potions +" << endl
         << "[" << _whetstones << "] whetstones" << endl
         << "[" << _queens << "] Queens" << endl << endl;
}

void Player::DisplayHealthBar(Enemy *_Enemy){
    // Displays player's name and health bar. Enemy object is used to print name on the same line as player name for aesthetics.

    // Prints player's name.
    cout << endl;
    DisplayName();
    // Tabs to make room for enemy's name.
    if (name.length() > 5){
        cout << "\t";
    }
    else {
        cout <<" \t\t";
    }
    // Prints enemy name.
    _Enemy->DisplayName();

    /// The following lines contain the code for the health bar.
    /// Being difficult to explain, no comments will explain why
    /// SetConsoleTextAttribute() is used, why it evaluates the health, why it prints blank spaces, etc.
    /// Intuition will be enough to understand what is going on in the following lines.

    string healthBar = "    " + std::to_string(health);

    for (int i = healthBar.length(); i < 10; i++)
        healthBar += " ";

    cout << endl;
    for (int i = 0; i < healthBar.length(); i++){
        if ((i+1)*10 <= health){
            SetConsoleTextAttribute(hConsole, RED_BACKGROUND);
            cout << healthBar.at(i);
        }
        else {
            SetConsoleTextAttribute(hConsole, GREY_BACKGROUND);
            cout << healthBar.at(i);
        }
    }

    SetConsoleTextAttribute(hConsole, GREY);
}

void Player::ReplenishHealth(){
    // Adds 30 health points after player has defeated an enemy.
    health+=30;
    if (health>100) health=100;
}

bool Player::IsDead(){
    // Returns a bool value, if the player's health is equal or below 0.
    if (health <= 0) {
        cout << "You're dead!" << endl << endl;
        Sleep(SLEEP_MS);
        return true;
    }
    return false;
}

void Player::DisplayName(){
    // Prints the player's name is dark gray for aesthetic purposes.

    // Sets text to dark grey.
    SetConsoleTextAttribute(hConsole, DARK_GREY);

    // Prints the player's name.
    cout << name;

    // Sets text back to normal gray.
    SetConsoleTextAttribute(hConsole, GREY);
}

void Player::AddExperience(int xp){
    // Adds points to the player's experience and levels player up.

    // Adds experience from passed in integer to local class variable experience.
    experience += xp;

    // Evaluates if experience is higher than 99, which means a level up is in order.
    if (experience>99) {
        // Experience is set to 0.
        experience = 0;

        // Player is leveled up.
        level+=1;

        // Sets level cap to 50, player cannot level higher than that.
        if (level >= 50) level = 50;

        // Alerts player that they have leveled up.
        cout << "You leveled up! Now you are level " << level << "!" << endl;
        Sleep(SLEEP_MS);
    }
}

void Player::LoseExperience(int xp){
    // Deducts points from the player's experience and de-levels player.

    // Deducts experience from passed in integer to local class variable experience.
    experience -= xp;

    // Evaluates if experience is less than 0.
    if (experience<0){
        // Experience is deducted continuing from the experience which de-leveled the player (hard to explain...)
        experience = 100-(0-experience);

        // De-levels player.
        level-=1;

        // Checks any glitches and sets player level to 1 if level is below 1 or above 50.
        // Also resets experience points.
        if (level<1 || level>50){
            level=1;
            experience = 0;
        }

        // Alerts the player that they have de-leveled.
        else {
            cout << "You de-leveled back to level " << level << "..." << endl;
            Sleep(SLEEP_MS);
        }
    }
}

void Player::AddQueens(int q){
    queens += q;
}

void Player::LoseQueens(int q){
    queens -= q;
    if (queens < 0) queens = 0;
}

void Player::DisplayInventory(){
    // Checks valid weapon strength.
    if (weaponstrength < 0){
        weaponstrength = 0;
    }
    // Simply prints the player's inventory.

    cout << "*------- INVENTORY -------* " << endl;
    cout << "Level " << level << "\t\t" << experience << "/100 xp" << endl;
    cout << "| Arrows: [" << arrows << "]" << endl;
    cout << "| Potions: [" << potions << "]" << endl;
    cout << "| Bombs: [" << bombs << "]" << endl;
    cout << "| Whetstones: [" << whetstones << "]" << endl;
    cout << "| Weapon strength: [" << weaponstrength << "%]" << endl;
    cout << "| Wealth: [" << queens << "] Queens" << endl;
    cout << "--------------------------- " << endl << endl;
}

int Player::GenericAttack(){
    int damage = ReturnDamage();
    DeductDamage(damage);
    DisplayName();
    cout << " attacks! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    if (damage>0) weaponstrength-= 2+rand()%5;
    return damage;
}

int Player::RiskAttack(){
    int damage = ReturnRiskAttackDamage();
    DeductDamage(damage);
    DisplayName();
    cout << " takes a risk and attack! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    if (damage>0) weaponstrength-= 4+rand()%5;
    return damage;
}

int Player::BowAndArrow(){
    int damage = ReturnBowDamage();
    DisplayName();
    cout << " shoots his bow! He deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << damage;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    return damage;
}

void Player::UseWhetstone(){
    weaponstrength=100;
    DisplayName();
    cout << " sharpened his weapon!" << endl;
    whetstones--;
}

void Player::UsePotion(){
    health=100;
    DisplayName();
    cout << " drank a healing potion!" << endl;
    potions--;
}

int Player::UseBomb(){
    DisplayName();
    cout << " hurls a bomb! ";
    DisplayName();
    cout << " deals ";
    SetConsoleTextAttribute(hConsole, RED);
    cout << "50";
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " damage points!" << endl;
    bombs--;
    return 50;
}

void Player::DeductDamage(int &damage){
    if (weaponstrength<=75&&weaponstrength>50)
        damage-=1;
    else if (weaponstrength<=50&&weaponstrength>30)
        damage-=4;
    else if (weaponstrength<=30&&weaponstrength>20)
        damage-=5;
    else if (weaponstrength<=20&&weaponstrength>10)
        damage-=6;
    else if (weaponstrength<=10)
        damage-=7;
    if (damage<0)
        damage=0;
}

int Player::ReturnBowDamage(){
    if (arrows < 1)
        return 0;
    arrows--;
    return 10+rand()%6; // 10 - 15
}

void Player::Heal(){
    int heal = ReturnHealAmount();
    health += heal;
    if (health > 100) health = 100;
    DisplayName();
    cout << " gains ";
    SetConsoleTextAttribute(hConsole, 10);
    cout << heal;
    SetConsoleTextAttribute(hConsole, GREY);
    cout << " HP! ";
    DisplayName();
    cout << " now has " << health << "HP!" << endl;
}

int Player::Flee(){
    DisplayName();
    cout << " chooses to flee!" << endl;
    return -1;
}

<|endoftext|>


<commit_before>#include <StdAfx.h>
#include <UI/FileDialogEx.h>
#include <core/utility/strings.h>

namespace file
{
	std::wstring CFileDialogExW::OpenFile(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet =
			EC_D_DIALOG(dlgFilePicker.DisplayDialog(true, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileName();
		}

		return std::wstring();
	}

	std::vector<std::wstring> CFileDialogExW::OpenFiles(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet = EC_D_DIALOG(dlgFilePicker.DisplayDialog(
			true, lpszDefExt, lpszFileName, dwFlags | OFN_ALLOWMULTISELECT, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileNames();
		}

		return std::vector<std::wstring>();
	}

	std::wstring CFileDialogExW::SaveAs(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet =
			EC_D_DIALOG(dlgFilePicker.DisplayDialog(false, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileName();
		}

		return std::wstring();
	}

	// Make sure OPENFILENAMEEX is the same size regardless of how _WIN32_WINNT is defined
#if (_WIN32_WINNT >= 0x0500)
	struct OPENFILENAMEEXW : public OPENFILENAMEW
	{
	};
#else
	struct OPENFILENAMEEXW : public OPENFILENAMEW
	{
		void* pvReserved;
		DWORD dwReserved;
		DWORD FlagsEx;
	};
#endif

#define CCHBIGBUFF 8192

	std::vector<std::wstring> UnpackFileNames(OPENFILENAMEEXW ofn)
	{
		auto paths = std::vector<std::wstring>();

		if ((ofn.Flags & OFN_ALLOWMULTISELECT) == 0)
		{
			paths.push_back(ofn.lpstrFile);
			return paths;
		}

		auto strBasePath = std::wstring(ofn.lpstrFile) + L"\\";
		auto lpsz = ofn.lpstrFile;
		// find char pos after first Delimiter
		while (*lpsz != L'\0')
			lpsz = CharNextW(lpsz);
		lpsz++;

		// if single selection then return only selection
		if (*lpsz == L'\0')
		{
			paths.push_back(ofn.lpstrFile);
			return paths;
		}

		while (lpsz != nullptr)
		{
			WCHAR strPath[_MAX_PATH] = {};
			WCHAR strDrive[_MAX_DRIVE] = {};
			WCHAR strDir[_MAX_DIR] = {};
			WCHAR strName[_MAX_FNAME] = {};
			WCHAR strExt[_MAX_EXT] = {};
			_wsplitpath_s(lpsz, strDrive, _MAX_DRIVE, strDir, _MAX_DIR, strName, _MAX_FNAME, strExt, _MAX_EXT);
			if (*strDrive || *strDir)
			{
				wcscpy_s(strPath, _countof(strPath), lpsz);
			}
			else
			{
				_wsplitpath_s(
					strBasePath.c_str(), strDrive, _MAX_DRIVE, strDir, _MAX_DIR, nullptr, 0, nullptr, 0); // STRING_OK
				_wmakepath_s(strPath, _MAX_PATH, strDrive, strDir, strName, strExt);
			}

			paths.push_back(strPath);

			// find char pos at next Delimiter
			while (*lpsz != L'\0')
				lpsz = CharNextW(lpsz);
			lpsz++;

			if (*lpsz == L'\0') // if double terminated then done
				lpsz = nullptr;
		}

		return paths;
	}

	_Check_return_ INT_PTR CFileDialogExW::DisplayDialog(
		bool bOpenFileDialog, // true for open, false for FileSaveAs
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		auto szFileName = std::wstring(_MAX_PATH, '\0'); // contains full path name after return
		if (dwFlags & OFN_ALLOWMULTISELECT)
		{
			szFileName.resize(CCHBIGBUFF);
		}

		// initialize structure
		auto ofn = OPENFILENAMEEXW{};
		ofn.lStructSize = sizeof(OPENFILENAMEEXW);
		ofn.lpstrFile = const_cast<wchar_t*>(szFileName.c_str());
		ofn.nMaxFile = static_cast<DWORD>(szFileName.length());

		ofn.lpstrDefExt = lpszDefExt.c_str();
		ofn.Flags = dwFlags | OFN_ENABLEHOOK | OFN_EXPLORER;
		ofn.hwndOwner = pParentWnd ? pParentWnd->m_hWnd : nullptr;

		// setup initial file name
		if (!lpszFileName.empty()) wcsncpy_s(ofn.lpstrFile, ofn.nMaxFile, lpszFileName.c_str(), _TRUNCATE);

		// Translate filter into commdlg format (lots of \0)
		auto strFilter = lpszFilter; // filter string
		if (!strFilter.empty())
		{
			replace(strFilter.begin(), strFilter.end(), L'|', L'\0');
			ofn.lpstrFilter = strFilter.c_str();
		}

		BOOL bResult = false;
		if (bOpenFileDialog)
			bResult = GetOpenFileNameW(&ofn);
		else
			bResult = GetSaveFileNameW(&ofn);

		if (bResult)
		{
			m_paths = UnpackFileNames(ofn);
		}

		return bResult ? bResult : IDCANCEL;
	}

	std::wstring CFileDialogExW::GetFileName() const
	{
		if (m_paths.size() >= 1) return m_paths[0];
		return strings::emptystring;
	}

	std::vector<std::wstring> CFileDialogExW::GetFileNames() const { return m_paths; }
} // namespace file<commit_msg>add resize<commit_after>#include <StdAfx.h>
#include <UI/FileDialogEx.h>
#include <core/utility/strings.h>

namespace file
{
	std::wstring CFileDialogExW::OpenFile(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet =
			EC_D_DIALOG(dlgFilePicker.DisplayDialog(true, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileName();
		}

		return std::wstring();
	}

	std::vector<std::wstring> CFileDialogExW::OpenFiles(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet = EC_D_DIALOG(dlgFilePicker.DisplayDialog(
			true, lpszDefExt, lpszFileName, dwFlags | OFN_ALLOWMULTISELECT, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileNames();
		}

		return std::vector<std::wstring>();
	}

	std::wstring CFileDialogExW::SaveAs(
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		CFileDialogExW dlgFilePicker;
		const auto iDlgRet =
			EC_D_DIALOG(dlgFilePicker.DisplayDialog(false, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd));
		if (iDlgRet == IDOK)
		{
			return dlgFilePicker.GetFileName();
		}

		return std::wstring();
	}

	// Make sure OPENFILENAMEEX is the same size regardless of how _WIN32_WINNT is defined
#if (_WIN32_WINNT >= 0x0500)
	struct OPENFILENAMEEXW : public OPENFILENAMEW
	{
	};
#else
	struct OPENFILENAMEEXW : public OPENFILENAMEW
	{
		void* pvReserved;
		DWORD dwReserved;
		DWORD FlagsEx;
	};
#endif

#define CCHBIGBUFF 8192

	std::vector<std::wstring> UnpackFileNames(OPENFILENAMEEXW ofn)
	{
		auto paths = std::vector<std::wstring>();

		if ((ofn.Flags & OFN_ALLOWMULTISELECT) == 0)
		{
			paths.push_back(ofn.lpstrFile);
			return paths;
		}

		auto strBasePath = std::wstring(ofn.lpstrFile) + L"\\";
		auto lpsz = ofn.lpstrFile;
		// find char pos after first Delimiter
		while (*lpsz != L'\0')
			lpsz = CharNextW(lpsz);
		lpsz++;

		// if single selection then return only selection
		if (*lpsz == L'\0')
		{
			paths.push_back(ofn.lpstrFile);
			return paths;
		}

		while (lpsz != nullptr)
		{
			WCHAR strPath[_MAX_PATH] = {};
			WCHAR strDrive[_MAX_DRIVE] = {};
			WCHAR strDir[_MAX_DIR] = {};
			WCHAR strName[_MAX_FNAME] = {};
			WCHAR strExt[_MAX_EXT] = {};
			_wsplitpath_s(lpsz, strDrive, _MAX_DRIVE, strDir, _MAX_DIR, strName, _MAX_FNAME, strExt, _MAX_EXT);
			if (*strDrive || *strDir)
			{
				wcscpy_s(strPath, _countof(strPath), lpsz);
			}
			else
			{
				_wsplitpath_s(
					strBasePath.c_str(), strDrive, _MAX_DRIVE, strDir, _MAX_DIR, nullptr, 0, nullptr, 0); // STRING_OK
				_wmakepath_s(strPath, _MAX_PATH, strDrive, strDir, strName, strExt);
			}

			paths.push_back(strPath);

			// find char pos at next Delimiter
			while (*lpsz != L'\0')
				lpsz = CharNextW(lpsz);
			lpsz++;

			if (*lpsz == L'\0') // if double terminated then done
				lpsz = nullptr;
		}

		return paths;
	}

	_Check_return_ INT_PTR CFileDialogExW::DisplayDialog(
		bool bOpenFileDialog, // true for open, false for FileSaveAs
		_In_ const std::wstring& lpszDefExt,
		_In_ const std::wstring& lpszFileName,
		DWORD dwFlags,
		_In_ const std::wstring& lpszFilter,
		_In_opt_ CWnd* pParentWnd)
	{
		auto szFileName = std::wstring(_MAX_PATH, '\0'); // contains full path name after return
		if (dwFlags & OFN_ALLOWMULTISELECT)
		{
			szFileName.resize(CCHBIGBUFF);
		}

		// initialize structure
		auto ofn = OPENFILENAMEEXW{};
		ofn.lStructSize = sizeof(OPENFILENAMEEXW);
		ofn.lpstrFile = const_cast<wchar_t*>(szFileName.c_str());
		ofn.nMaxFile = static_cast<DWORD>(szFileName.length());

		ofn.lpstrDefExt = lpszDefExt.c_str();
		ofn.Flags = dwFlags | OFN_ENABLEHOOK | OFN_EXPLORER | OFN_ENABLESIZING;
		ofn.hwndOwner = pParentWnd ? pParentWnd->m_hWnd : nullptr;

		// setup initial file name
		if (!lpszFileName.empty()) wcsncpy_s(ofn.lpstrFile, ofn.nMaxFile, lpszFileName.c_str(), _TRUNCATE);

		// Translate filter into commdlg format (lots of \0)
		auto strFilter = lpszFilter; // filter string
		if (!strFilter.empty())
		{
			replace(strFilter.begin(), strFilter.end(), L'|', L'\0');
			ofn.lpstrFilter = strFilter.c_str();
		}

		BOOL bResult = false;
		if (bOpenFileDialog)
			bResult = GetOpenFileNameW(&ofn);
		else
			bResult = GetSaveFileNameW(&ofn);

		if (bResult)
		{
			m_paths = UnpackFileNames(ofn);
		}

		return bResult ? bResult : IDCANCEL;
	}

	std::wstring CFileDialogExW::GetFileName() const
	{
		if (m_paths.size() >= 1) return m_paths[0];
		return strings::emptystring;
	}

	std::vector<std::wstring> CFileDialogExW::GetFileNames() const { return m_paths; }
} // namespace file<|endoftext|>


<commit_before>/*

  exec.cpp

  This is an example of GL_EXT_blend_color, described
  on page 86 of the NVidia OpenGL Extension Specifications.

  Christopher Niederauer, ccn@graphics.stanford.edu, 6/27/2001

*/

/* --- Preprocessor --------------------------------------------------------- */

#include "exec.h"
#include "../common/logo.h"

#ifndef WIN32
#include <GL/glxext.h>
#endif

/* --- Global Variables ----------------------------------------------------- */

GLuint	currentWidth, currentHeight;

static GLuint	texture[1];
static GLfloat	bgColor[4] = { 0.2, 0.3, 0.8, 0.0 };

/* --- Extension Declarations ---------------------------------------------- */

//typedef void (APIENTRY *PFNGLBLENDCOLOREXTPROC)( GLclampf, GLclampf, GLclampf, GLclampf );

PFNGLBLENDCOLOREXTPROC BlendColorEXTptr = NULL;

inline void glBlendColorEXT ( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
inline void glBlendColorEXT ( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )
{
	(*BlendColorEXTptr)( red, green, blue, alpha );
}

/* --- Function Definitions ------------------------------------------------- */

void	InitGL	( void )
{
	currentWidth = 320;
	currentHeight = 240;

#ifdef MULTIPLE_VIEWPORTS
	currentWidth <<= 1;
#endif

	glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
	glutInitWindowPosition( 5, 25 );
	glutInitWindowSize( currentWidth, currentHeight );
	glutCreateWindow( TEST_EXTENSION_STRING );

	glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3] );
	glClear( GL_COLOR_BUFFER_BIT );

	glutIdleFunc( Idle );
	glutDisplayFunc( Display );
	glutReshapeFunc( Reshape );
	glutKeyboardFunc( Keyboard );
	glutMouseFunc( NULL );
	glutMotionFunc( NULL );
	glutSpecialFunc( NULL );
}

void	InitSpecial	( void )
{
	GLubyte	textureData[ 32*32 ];

	for( int x=0; x<32; x++ )
	{
		for( int y=0; y<32; y++ )
		{
			if(( x < 16 && y < 16 ) || ( x >= 16 && y >= 16 ))
				textureData[ y*32+x ] = 0;
			else
				textureData[ y*32+x ] = 255;
		}
	}

	// Create the tile texture.
	glGenTextures( 1, texture );

	// Create Trilinear MipMapped Texture
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST );
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR );
	gluBuild2DMipmaps( GL_TEXTURE_2D, GL_LUMINANCE, 32, 32, GL_LUMINANCE, GL_UNSIGNED_BYTE, textureData );

#ifdef WIN32
	BlendColorEXTptr = (PFNGLBLENDCOLOREXTPROC)wglGetProcAddress( "glBlendColorEXT" );
#else
	BlendColorEXTptr = (PFNGLBLENDCOLOREXTPROC)glXGetProcAddressARB( "glBlendColorEXT" );
#endif
	if ( BlendColorEXTptr == NULL )
	{
		cout << "Error linking to extensions!" << endl;
		exit( 0 );
	}

	return;
}

void	Idle		( void )
{
	glutPostRedisplay();
	return;
}

void	Display		( void )
{
	const float		size = 50.0;
	static double	theta = 0.0;

	glClear( GL_COLOR_BUFFER_BIT );

	theta += 0.005;

	glLoadIdentity();
	glTranslatef( 0.0, -2.0, 0.0 );
	glRotated( 30.0, 1.0, 0.0, 0.0 );
	glRotated( theta, 0.0, 1.0, 0.0 );
	glColor3f( 1.0, 1.0, 1.0 );

#ifdef MULTIPLE_VIEWPORTS

	// Left Viewport
	glViewport( 0, 0, currentWidth >> 1, currentHeight );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glBegin( GL_QUADS );
		glTexCoord2f( -size/2, size/2 );
		glVertex3f( -size, 0.0,  size );
		glTexCoord2f( size/2, size/2 );
		glVertex3f(  size, 0.0,  size );
		glTexCoord2f( size/2, -size/2 );
		glVertex3f(  size, 0.0, -size );
		glTexCoord2f( -size/2, -size/2 );
		glVertex3f( -size, 0.0, -size );
	glEnd();
	glDisable( GL_TEXTURE_2D );
	glPushMatrix();glLoadIdentity();
	RenderString( -1.1, 1, "Constant Color Blending Off" );
	glPopMatrix();

	// Upper Right Viewport
	glViewport( currentWidth >> 1, 0, currentWidth >> 1, currentHeight );
#endif
	glEnable( GL_BLEND );
	glBlendColorEXT( 1.0, 1.0, 0.0, 0.0 );
	glBlendFunc( GL_CONSTANT_COLOR_EXT, GL_ZERO );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glBegin( GL_QUADS );
		glTexCoord2f( -size/2, size/2 );
		glVertex3f( -size, 0.0,  size );
		glTexCoord2f( size/2, size/2 );
		glVertex3f(  size, 0.0,  size );
		glTexCoord2f( size/2, -size/2 );
		glVertex3f(  size, 0.0, -size );
		glTexCoord2f( -size/2, -size/2 );
		glVertex3f( -size, 0.0, -size );
	glEnd();
	glDisable( GL_TEXTURE_2D );
	glDisable( GL_BLEND );
	glPushMatrix();glLoadIdentity();
	RenderString( -1.1, 1, "Constant Color Blending On" );
	glViewport( 0, 0, currentWidth, currentHeight );
	crExtensionsDrawLogo( currentWidth, currentHeight );
	glPopMatrix();

	glutSwapBuffers();
}

void	Reshape		( int width, int height )
{
	currentWidth = width;
	currentHeight = height;

	glViewport( 0, 0, currentWidth, currentHeight );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glFrustum( -1.0, 1.0, -1.0, 1.0, 1.0, 30.0 );
	glMatrixMode( GL_MODELVIEW );
}

void	Keyboard	( unsigned char key, int x, int y )
{
	static	GLboolean	wireframe = false;

	switch( key )
	{
		case 'Q':
		case 'q':
			cout << "User has quit. Exiting." << endl;
			exit( 0 );
		default:
			break;
	}
	return;
}

void	Mouse		( int button, int state, int x, int y )
{
	return;
}

void	Motion		( int x, int y )
{
	return;
}

void	Special		( int key, int x, int y )
{
	return;
}
<commit_msg>Fixed it.<commit_after>/*

  exec.cpp

  This is an example of GL_EXT_blend_color, described
  on page 86 of the NVidia OpenGL Extension Specifications.

  Christopher Niederauer, ccn@graphics.stanford.edu, 6/27/2001

*/

/* --- Preprocessor --------------------------------------------------------- */

#include "exec.h"
#include "../common/logo.h"

#ifndef WIN32
#include <GL/glxext.h>
#endif

/* --- Global Variables ----------------------------------------------------- */

GLuint	currentWidth, currentHeight;

static GLuint	texture[1];
static GLfloat	bgColor[4] = { 0.2, 0.3, 0.8, 0.0 };

/* --- Extension Declarations ---------------------------------------------- */

//typedef void (APIENTRY *PFNGLBLENDCOLOREXTPROC)( GLclampf, GLclampf, GLclampf, GLclampf );

PFNGLBLENDCOLOREXTPROC glBlendColorEXT;

/* --- Function Definitions ------------------------------------------------- */

void	InitGL	( void )
{
	currentWidth = 320;
	currentHeight = 240;

#ifdef MULTIPLE_VIEWPORTS
	currentWidth <<= 1;
#endif

	glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
	glutInitWindowPosition( 5, 25 );
	glutInitWindowSize( currentWidth, currentHeight );
	glutCreateWindow( TEST_EXTENSION_STRING );

	glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3] );
	glClear( GL_COLOR_BUFFER_BIT );

	glutIdleFunc( Idle );
	glutDisplayFunc( Display );
	glutReshapeFunc( Reshape );
	glutKeyboardFunc( Keyboard );
	glutMouseFunc( NULL );
	glutMotionFunc( NULL );
	glutSpecialFunc( NULL );
}

void	InitSpecial	( void )
{
	GLubyte	textureData[ 32*32 ];

	for( int x=0; x<32; x++ )
	{
		for( int y=0; y<32; y++ )
		{
			if(( x < 16 && y < 16 ) || ( x >= 16 && y >= 16 ))
				textureData[ y*32+x ] = 0;
			else
				textureData[ y*32+x ] = 255;
		}
	}

	// Create the tile texture.
	glGenTextures( 1, texture );

	// Create Trilinear MipMapped Texture
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST );
	glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR );
	gluBuild2DMipmaps( GL_TEXTURE_2D, GL_LUMINANCE, 32, 32, GL_LUMINANCE, GL_UNSIGNED_BYTE, textureData );

#ifdef WIN32
	glBlendColorEXT = (PFNGLBLENDCOLOREXTPROC)wglGetProcAddress( "glBlendColorEXT" );
#else
	glBlendColorEXT = (PFNGLBLENDCOLOREXTPROC)glXGetProcAddressARB( "glBlendColorEXT" );
#endif
	if ( glBlendColorEXT == NULL )
	{
		cout << "Error linking to extensions!" << endl;
		exit( 0 );
	}

	return;
}

void	Idle		( void )
{
	glutPostRedisplay();
	return;
}

void	Display		( void )
{
	const float		size = 50.0;
	static double	theta = 0.0;

	glClear( GL_COLOR_BUFFER_BIT );

	theta += 0.005;

	glLoadIdentity();
	glTranslatef( 0.0, -2.0, 0.0 );
	glRotated( 30.0, 1.0, 0.0, 0.0 );
	glRotated( theta, 0.0, 1.0, 0.0 );
	glColor3f( 1.0, 1.0, 1.0 );

#ifdef MULTIPLE_VIEWPORTS

	// Left Viewport
	glViewport( 0, 0, currentWidth >> 1, currentHeight );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glBegin( GL_QUADS );
		glTexCoord2f( -size/2, size/2 );
		glVertex3f( -size, 0.0,  size );
		glTexCoord2f( size/2, size/2 );
		glVertex3f(  size, 0.0,  size );
		glTexCoord2f( size/2, -size/2 );
		glVertex3f(  size, 0.0, -size );
		glTexCoord2f( -size/2, -size/2 );
		glVertex3f( -size, 0.0, -size );
	glEnd();
	glDisable( GL_TEXTURE_2D );
	glPushMatrix();glLoadIdentity();
	RenderString( -1.1, 1, "Constant Color Blending Off" );
	glPopMatrix();

	// Upper Right Viewport
	glViewport( currentWidth >> 1, 0, currentWidth >> 1, currentHeight );
#endif
	glEnable( GL_BLEND );
	glBlendColorEXT( 1.0, 1.0, 0.0, 0.0 );
	glBlendFunc( GL_CONSTANT_COLOR_EXT, GL_ZERO );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture[0] );
	glBegin( GL_QUADS );
		glTexCoord2f( -size/2, size/2 );
		glVertex3f( -size, 0.0,  size );
		glTexCoord2f( size/2, size/2 );
		glVertex3f(  size, 0.0,  size );
		glTexCoord2f( size/2, -size/2 );
		glVertex3f(  size, 0.0, -size );
		glTexCoord2f( -size/2, -size/2 );
		glVertex3f( -size, 0.0, -size );
	glEnd();
	glDisable( GL_TEXTURE_2D );
	glDisable( GL_BLEND );
	glPushMatrix();glLoadIdentity();
	RenderString( -1.1, 1, "Constant Color Blending On" );
	glViewport( 0, 0, currentWidth, currentHeight );
	crExtensionsDrawLogo( currentWidth, currentHeight );
	glPopMatrix();

	glutSwapBuffers();
}

void	Reshape		( int width, int height )
{
	currentWidth = width;
	currentHeight = height;

	glViewport( 0, 0, currentWidth, currentHeight );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glFrustum( -1.0, 1.0, -1.0, 1.0, 1.0, 30.0 );
	glMatrixMode( GL_MODELVIEW );
}

void	Keyboard	( unsigned char key, int x, int y )
{
	static	GLboolean	wireframe = false;

	switch( key )
	{
		case 'Q':
		case 'q':
			cout << "User has quit. Exiting." << endl;
			exit( 0 );
		default:
			break;
	}
	return;
}

void	Mouse		( int button, int state, int x, int y )
{
	return;
}

void	Motion		( int x, int y )
{
	return;
}

void	Special		( int key, int x, int y )
{
	return;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_INV_PHI_LOG_HPP
#define STAN_MATH_REV_FUN_INV_PHI_LOG_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/inv_Phi_log.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * The inverse of unit normal cumulative density function.
 *
 * The derivative is the reciprocal of unit normal density function,
 *
 * @param log_p log probability
 * @return the unit normal inverse cdf evaluated at log_p
 */
template <typename T, require_all_stan_scalar_t<T>* = nullptr,
          require_any_var_t<T>* = nullptr>
inline var inv_Phi_log(const T& log_p) {
  double log_p_val = value_of(log_p);
  double z = inv_Phi_log(log_p_val);

  return make_callback_var(z, [log_p, log_p_val](auto& vi) mutable {
    log_p.adj() += log_p_val * vi.adj() * SQRT_TWO_PI
                       / std::exp(-0.5 * vi.val() * vi.val())
                   + vi.val() / exp(log_p_val);
  });
}

/**
 * Return the elementwise inverse of unit normal cumulative density function.
 *
 * @tparam T a `var_value` with inner Eigen type
 * @param p Probability vector
 * @return Elementwise unit normal inverse cdf
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
inline auto inv_Phi_log(const T& log_p) {
  auto log_p_val = value_of(log_p);
  auto z = inv_Phi_log(log_p_val);
  return make_callback_var(inv_Phi_log(log_p.val()), [log_p](auto& vi) mutable {
    as_array_or_scalar(log_p.adj())
        += log_p_val.array() * vi.val().array().exp() * vi.adj().array()
               * SQRT_TWO_PI / (-0.5 * vi.val().array().square()).exp()
           + vi.val().array() / log_p_val.array().exp();
  });
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Update inv_Phi_log.hpp<commit_after>#ifndef STAN_MATH_REV_FUN_INV_PHI_LOG_HPP
#define STAN_MATH_REV_FUN_INV_PHI_LOG_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/inv_Phi_log.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * The inverse of unit normal cumulative density function.
 *
 * The derivative is the reciprocal of unit normal density function,
 *
 * @param log_p log probability
 * @return the unit normal inverse cdf evaluated at log_p
 */
template <typename T, require_all_stan_scalar_t<T>* = nullptr,
          require_any_var_t<T>* = nullptr>
inline var inv_Phi_log(const T& log_p) {
  double log_p_val = value_of(log_p);
  double z = inv_Phi_log(log_p_val);

  return make_callback_var(z, [log_p, log_p_val](auto& vi) mutable {
    log_p.adj() += log_p_val * vi.adj() * SQRT_TWO_PI
                       / std::exp(-0.5 * vi.val() * vi.val())
                   + vi.val() / exp(log_p_val);
  });
}

/**
 * Return the elementwise inverse of unit normal cumulative density function.
 *
 * @tparam T a `var_value` with inner Eigen type
 * @param p Probability vector
 * @return Elementwise unit normal inverse cdf
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
inline auto inv_Phi_log(const T& log_p) {
  auto log_p_val = value_of(log_p);
  auto z = inv_Phi_log(log_p_val);
  return make_callback_var(inv_Phi_log(log_p.val()), [log_p, log_p_val](auto& vi) mutable {
    as_array_or_scalar(log_p.adj())
        += log_p_val.array() * vi.val().array().exp() * vi.adj().array()
               * SQRT_TWO_PI / (-0.5 * vi.val().array().square()).exp()
           + vi.val().array() / log_p_val.array().exp();
  });
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 3 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, see <https://www.gnu.org/licenses/>.
//

#include "base/guid.h"
#include "base/strings/string_util.h"

#include <gtest/gtest.h>

#include <cstdint>
#include <limits>

namespace base {

namespace {

bool isGUIDv4(const std::string& guid)
{
    // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
    // where y is one of [8, 9, A, B].
    return Guid::isValidGuidString(guid) && guid[14] == '4' &&
        (guid[19] == '8' || guid[19] == '9' || guid[19] == 'A' ||
         guid[19] == 'a' || guid[19] == 'B' || guid[19] == 'b');
}

} // namespace

TEST(guid_test, guid_generates_all_zeroes)
{
    uint64_t bytes[] = { 0, 0 };
    std::string clientid = Guid::randomDataToGUIDString(bytes);
    EXPECT_EQ("00000000-0000-0000-0000-000000000000", clientid);
}

TEST(guid_test, guid_generates_correctly)
{
    uint64_t bytes[] = { 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL };
    std::string clientid = Guid::randomDataToGUIDString(bytes);
    EXPECT_EQ("01234567-89ab-cdef-fedc-ba9876543210", clientid);
}

TEST(guid_test, guid_correctly_formatted)
{
    const int kIterations = 10;
    for (int it = 0; it < kIterations; ++it)
    {
        std::string guid = Guid::create().toStdString();
        EXPECT_TRUE(Guid::isValidGuidString(guid));
        EXPECT_TRUE(Guid::isStrictValidGuidString(guid));
        EXPECT_TRUE(Guid::isValidGuidString(toLowerASCII(guid)));
        EXPECT_TRUE(Guid::isValidGuidString(toUpperASCII(guid)));
    }
}

TEST(guid_test, guid_basic_uniqueness)
{
    const int kIterations = 500000;
    for (int it = 0; it < kIterations; ++it)
    {
        std::string guid1 = Guid::create().toStdString();
        std::string guid2 = Guid::create().toStdString();
        EXPECT_EQ(36U, guid1.length());
        EXPECT_EQ(36U, guid2.length());
        EXPECT_NE(guid1, guid2);
    }
}

} // namespace base
<commit_msg>- Added missed tests.<commit_after>//
// Aspia Project
// Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 3 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, see <https://www.gnu.org/licenses/>.
//

#include "base/guid.h"
#include "base/strings/string_util.h"

#include <gtest/gtest.h>

#include <cstdint>
#include <limits>

namespace base {

namespace {

bool isGUIDv4(const std::string& guid)
{
    // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
    // where y is one of [8, 9, A, B].
    return Guid::isValidGuidString(guid) && guid[14] == '4' &&
        (guid[19] == '8' || guid[19] == '9' || guid[19] == 'A' ||
         guid[19] == 'a' || guid[19] == 'B' || guid[19] == 'b');
}

} // namespace

TEST(guid_test, guid_generates_all_zeroes)
{
    uint64_t bytes[] = { 0, 0 };
    std::string clientid = Guid::randomDataToGUIDString(bytes);
    EXPECT_EQ("00000000-0000-0000-0000-000000000000", clientid);
}

TEST(guid_test, guid_generates_correctly)
{
    uint64_t bytes[] = { 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL };
    std::string clientid = Guid::randomDataToGUIDString(bytes);
    EXPECT_EQ("01234567-89ab-cdef-fedc-ba9876543210", clientid);
}

TEST(guid_test, guid_correctly_formatted)
{
    const int kIterations = 10;
    for (int it = 0; it < kIterations; ++it)
    {
        std::string guid = Guid::create().toStdString();
        EXPECT_TRUE(Guid::isValidGuidString(guid));
        EXPECT_TRUE(Guid::isStrictValidGuidString(guid));
        EXPECT_TRUE(Guid::isValidGuidString(toLowerASCII(guid)));
        EXPECT_TRUE(Guid::isValidGuidString(toUpperASCII(guid)));
    }
}

TEST(guid_test, guid_basic_uniqueness)
{
    const int kIterations = 10;
    for (int it = 0; it < kIterations; ++it)
    {
        std::string guid1 = Guid::create().toStdString();
        std::string guid2 = Guid::create().toStdString();
        EXPECT_EQ(36U, guid1.length());
        EXPECT_EQ(36U, guid2.length());
        EXPECT_NE(guid1, guid2);
        EXPECT_TRUE(isGUIDv4(guid1));
        EXPECT_TRUE(isGUIDv4(guid2));
    }
}

} // namespace base
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_SOFTMAX_HPP
#define STAN_MATH_REV_MAT_FUN_SOFTMAX_HPP

#include <stan/math/prim/arr/err/check_nonzero_size.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/softmax.hpp>
#include <stan/math/rev/mat.hpp>
#include <vector>

namespace stan {
namespace math {

namespace {
class SoftmaxOp {
  int N_;
  double* y_mem_;  // Holds the results of the softmax
 public:
  SoftmaxOp() : N_(0), y_mem_(NULL) {}

  /*
   * Compute the softmax of the unconstrained input vector
   *
   * @param alpha Unconstrained input vector.
   * @return Softmax of the input.
   */
  Eigen::VectorXd operator()(const Eigen::VectorXd& alpha) {
    N_ = alpha.size();
    y_mem_ = ChainableStack::instance().memalloc_.alloc_array<double>(N_);

    auto y = softmax(alpha);
    for (int n = 0; n < N_; ++n)
      y_mem_[n] = y(n);
    return y;
  }

  /*
   * Compute the result of multiply the transpose of the adjoint vector times
   * the Jacobian of the softmax operator. It is more efficient to do this
   * without actually computing the Jacobian and doing the vector-matrix
   * product.
   *
   * @param adj Eigen::VectorXd of adjoints at the output of the softmax
   * @return Eigen::VectorXd of adjoints propagated through softmax operation
   */
  Eigen::VectorXd multiply_adjoint_jacobian(const Eigen::VectorXd& adj) const {
    Eigen::VectorXd adj_times_jac(N_);
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1> > y(y_mem_, N_);

    double adj_dot_y = adj.dot(y);
    for (int n = 0; n < N_; ++n) {
      adj_times_jac(n) = -y(n) * adj_dot_y + y(n) * adj(n);
    }

    return adj_times_jac;
  }
};
}  // namespace

/**
 * Return the softmax of the specified Eigen vector.  Softmax is
 * guaranteed to return a simplex.
 *
 * @param alpha Unconstrained input vector.
 * @return Softmax of the input.
 * @throw std::domain_error If the input vector is size 0.
 */
Eigen::Matrix<var, Eigen::Dynamic, 1> softmax(
    const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) {
  check_nonzero_size("softmax", "alpha", alpha);

  return adj_jac_apply<SoftmaxOp>(alpha);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Fixing cpplint issue (Issue 876)<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_SOFTMAX_HPP
#define STAN_MATH_REV_MAT_FUN_SOFTMAX_HPP

#include <stan/math/prim/arr/err/check_nonzero_size.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/softmax.hpp>
#include <stan/math/rev/mat.hpp>
#include <vector>

namespace stan {
namespace math {

namespace {
class SoftmaxOp {
  int N_;
  double* y_mem_;  // Holds the results of the softmax

 public:
  SoftmaxOp() : N_(0), y_mem_(NULL) {}

  /*
   * Compute the softmax of the unconstrained input vector
   *
   * @param alpha Unconstrained input vector.
   * @return Softmax of the input.
   */
  Eigen::VectorXd operator()(const Eigen::VectorXd& alpha) {
    N_ = alpha.size();
    y_mem_ = ChainableStack::instance().memalloc_.alloc_array<double>(N_);

    auto y = softmax(alpha);
    for (int n = 0; n < N_; ++n)
      y_mem_[n] = y(n);
    return y;
  }

  /*
   * Compute the result of multiply the transpose of the adjoint vector times
   * the Jacobian of the softmax operator. It is more efficient to do this
   * without actually computing the Jacobian and doing the vector-matrix
   * product.
   *
   * @param adj Eigen::VectorXd of adjoints at the output of the softmax
   * @return Eigen::VectorXd of adjoints propagated through softmax operation
   */
  Eigen::VectorXd multiply_adjoint_jacobian(const Eigen::VectorXd& adj) const {
    Eigen::VectorXd adj_times_jac(N_);
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1> > y(y_mem_, N_);

    double adj_dot_y = adj.dot(y);
    for (int n = 0; n < N_; ++n) {
      adj_times_jac(n) = -y(n) * adj_dot_y + y(n) * adj(n);
    }

    return adj_times_jac;
  }
};
}  // namespace

/**
 * Return the softmax of the specified Eigen vector.  Softmax is
 * guaranteed to return a simplex.
 *
 * @param alpha Unconstrained input vector.
 * @return Softmax of the input.
 * @throw std::domain_error If the input vector is size 0.
 */
Eigen::Matrix<var, Eigen::Dynamic, 1> softmax(
    const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) {
  check_nonzero_size("softmax", "alpha", alpha);

  return adj_jac_apply<SoftmaxOp>(alpha);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>//-----------------------------------------------------------
//
//    Copyright (C) 2015 - 2016 by the deal2lkit authors
//
//    This file is part of the deal2lkit library.
//
//    The deal2lkit library is free software; you can use it, redistribute
//    it, and/or modify it under the terms of the GNU Lesser General
//    Public License as published by the Free Software Foundation; either
//    version 2.1 of the License, or (at your option) any later version.
//    The full text of the license can be found in the file LICENSE at
//    the top level of the deal2lkit distribution.
//
//-----------------------------------------------------------

#include <deal2lkit/parameter_acceptor.h>
#include <deal2lkit/utilities.h>
#include <deal.II/base/point.h>
#include <deal.II/base/revision.h>
#include <deal2lkit/revision.h>
#include <fstream>

D2K_NAMESPACE_OPEN

// Static empty class list
std::vector<SmartPointer<ParameterAcceptor> > ParameterAcceptor::class_list;
// Static parameter handler
ParameterHandler ParameterAcceptor::prm;

ParameterAcceptor::ParameterAcceptor(const std::string name) :
  acceptor_id(class_list.size()),
  section_name(name)
{
  SmartPointer<ParameterAcceptor> pt(this, type(*this).c_str());
  class_list.push_back(pt);
}

ParameterAcceptor::~ParameterAcceptor()
{
  class_list[acceptor_id] = 0;
}

std::string ParameterAcceptor::get_section_name() const
{
  return (section_name != "" ? section_name : type(*this));
}

void
ParameterAcceptor::initialize(const std::string filename,
                              const std::string out_filename)
{
  prm.clear();
  declare_all_parameters(prm);
  if (filename != "")
    {
      // check the extension of input file
      if (filename.substr(filename.find_last_of(".") + 1) == "prm")
        prm.parse_input(filename);
      else if (filename.substr(filename.find_last_of(".") + 1) == "xml")
        {
          std::ifstream is(filename);
          prm.parse_input_from_xml(is);
        }
      else
        AssertThrow(false, ExcMessage("Invalid extension of parameter file. Please use .prm or .xml"));
    }
  parse_all_parameters(prm);
  if (out_filename != "")
    {
      std::ofstream outfile(out_filename.c_str());
      Assert(outfile, ExcIO());
      std::string extension = out_filename.substr(out_filename.find_last_of(".") + 1);

      if ( extension == "prm")
        {
          outfile << "# Parameter file generated with " << std::endl
                  << "# D2K_GIT_BRANCH=       " << D2K_GIT_BRANCH << std::endl
                  << "# D2K_GIT_SHORTREV=     " << D2K_GIT_SHORTREV << std::endl
                  << "# DEAL_II_GIT_BRANCH=   " << DEAL_II_GIT_BRANCH  << std::endl
                  << "# DEAL_II_GIT_SHORTREV= " << DEAL_II_GIT_SHORTREV << std::endl;
          prm.print_parameters(outfile, ParameterHandler::ShortText);
        }
      else if (extension == "xml")
        prm.print_parameters(outfile, ParameterHandler::XML);
      else if (extension == "latex" || extension == "tex")
        prm.print_parameters(outfile, ParameterHandler::LaTeX);
      else
        AssertThrow(false,ExcNotImplemented());
    }
}

void
ParameterAcceptor::clear()
{
  class_list.clear();
}

void
ParameterAcceptor::log_info()
{
  deallog.push("ParameterAcceptor");
  for (unsigned int i=0; i<class_list.size(); ++i)
    {
      deallog << "Class " << i << ":";
      if (class_list[i])
        deallog << class_list[i]->get_section_name() << std::endl;
      else
        deallog << " NULL" << std::endl;
    }
  deallog.pop();
}

void ParameterAcceptor::parse_all_parameters(ParameterHandler &prm)
{
  std::vector<std::string> old_secs;
  for (unsigned int i=0; i< class_list.size(); ++i)
    if (class_list[i] != NULL)
      {
        std::vector<std::string> secs;
        secs = Utilities::split_string_list(class_list[i]->get_section_name(), sep);
        const unsigned int secs_size = secs.size();

        if (secs_size == 1) // add a subsection with relative path
          {
            // enter the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.enter_subsection(old_secs[s]);

            // enter current subsection
            prm.enter_subsection(secs[0]);

            class_list[i]->parse_parameters(prm);
            class_list[i]->parse_parameters_call_back();

            // leave current subsection
            prm.leave_subsection();

            // leave the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.leave_subsection();

            // the old path is unchanged
          }

        else // we have at least one separator "/"
          {
            if (secs[0]=="") // the section name begins with "/"
              {
                // first of all remove the "empty" section
                secs.erase(secs.begin());

                // this means absolute path so we do not enter
                // the old path
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.enter_subsection(secs[s]);

                class_list[i]->parse_parameters(prm);
                class_list[i]->parse_parameters_call_back();

                // leave all the current sections
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.leave_subsection();

                // since we have started from the root section i.e. "/"
                // we need to set the old path to the current one
                // without the last subsection

                // remove the last subsection
                secs.pop_back();

                // update the old path
                old_secs.swap(secs);

              }
            else // append the path to the old path
              {
                // enter the old path
                for (unsigned int s=0; s<old_secs.size(); ++s)
                  prm.enter_subsection(old_secs[s]);

                // new path
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.enter_subsection(secs[s]);

                class_list[i]->parse_parameters(prm);
                class_list[i]->parse_parameters_call_back();

                // leave all subsections
                for (unsigned int s=0; s<(secs.size()+old_secs.size()); ++s)
                  prm.leave_subsection();

                // we need now to append the secs path (without the last subsection)
                // to the old path

                // remove last subsection
                secs.pop_back();

                // append secs to old_secs
                old_secs.insert(old_secs.begin(), secs.begin(), secs.end());

              }
          }
      }
}

void ParameterAcceptor::declare_all_parameters(ParameterHandler &prm)
{
  std::vector<std::string> old_secs;
  for (unsigned int i=0; i< class_list.size(); ++i)
    if (class_list[i] != NULL)
      {
        std::vector<std::string> secs;
        secs = Utilities::split_string_list(class_list[i]->get_section_name(), sep);
        const unsigned int secs_size = secs.size();

        if (secs_size == 1) // add a subsection with relative path
          {
            // enter the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.enter_subsection(old_secs[s]);

            // enter current subsection
            prm.enter_subsection(secs[0]);

            class_list[i]->declare_parameters(prm);

            // leave current subsection
            prm.leave_subsection();

            // leave the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.leave_subsection();

            // the old path is unchanged
          }

        else // we have at least one separator "/"
          {
            for (unsigned int s=0; s <secs.size(); ++s)
              if (secs[0]=="") // the section name begins with "/"
                {
                  // first of all remove the "empty" section
                  secs.erase(secs.begin());

                  // this means absolute path so we do not enter
                  // the old path
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.enter_subsection(secs[s]);

                  class_list[i]->declare_parameters(prm);

                  // leave all the current sections
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.leave_subsection();

                  // since we have started from the root section i.e. "/"
                  // we need to set the old path to the current one
                  // without the last subsection

                  // remove the last subsection
                  secs.pop_back();

                  // update the old path
                  old_secs.swap(secs);

                }
              else // append the path to the old path
                {
                  // enter the old path
                  for (unsigned int s=0; s<old_secs.size(); ++s)
                    prm.enter_subsection(old_secs[s]);

                  // new path
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.enter_subsection(secs[s]);

                  class_list[i]->declare_parameters(prm);

                  // leave all subsections
                  for (unsigned int s=0; s<(secs.size()+old_secs.size()); ++s)
                    prm.leave_subsection();

                  // we need now to append the secs path (without the last subsection)
                  // to the old path

                  // remove last subsection
                  secs.pop_back();

                  // append secs to old_secs
                  old_secs.insert(old_secs.begin(), secs.begin(), secs.end());

                }
          }
      }
}

void ParameterAcceptor::parse_parameters(ParameterHandler &prm)
{
  for (auto it = parameters.begin(); it != parameters.end(); ++it)
    {
      if (it->second.type() == typeid(std::string *))
        {
          *(boost::any_cast<std::string *>(it->second)) = prm.get(it->first);
        }
      else if (it->second.type() == typeid(double *))
        {
          *(boost::any_cast<double *>(it->second)) = prm.get_double(it->first);
        }
      else if (it->second.type() == typeid(int *))
        {
          *(boost::any_cast<int *>(it->second)) = prm.get_integer(it->first);
        }
      else if (it->second.type() == typeid(unsigned int *))
        {
          *(boost::any_cast<unsigned int *>(it->second)) = prm.get_integer(it->first);
        }
      else if (it->second.type() == typeid(bool *))
        {
          *(boost::any_cast<bool *>(it->second)) = prm.get_bool(it->first);
        }
      // Here we have the difficult types...
      // First all point types.
      else if (it->second.type() == typeid(Point<1> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 1);

          Point<1> &pp = *(boost::any_cast<Point<1>*>(it->second));
          pp[0] = p[0];
        }
      else if (it->second.type() == typeid(Point<2> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 2);

          Point<2> &pp = *(boost::any_cast<Point<2>*>(it->second));
          pp[0] = p[0];
          pp[1] = p[1];
        }
      else if (it->second.type() == typeid(Point<3> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 3);

          Point<3> &pp = *(boost::any_cast<Point<3>*>(it->second));
          pp[0] = p[0];
          pp[1] = p[1];
          pp[2] = p[2];
        }
      else if (it->second.type() == typeid(std::vector<std::string> *))
        {
          std::vector<std::string> &string_list = *(boost::any_cast<std::vector<std::string>*>(it->second));
          string_list = Utilities::split_string_list(prm.get(it->first));
        }
      else if (it->second.type() == typeid(std::vector<unsigned int> *))
        {
          std::vector<unsigned int> &int_list = *(boost::any_cast<std::vector<unsigned int>*>(it->second));
          std::vector<std::string> string_list = Utilities::split_string_list(prm.get(it->first));
          int_list.resize(string_list.size());
          for (unsigned int i=0; i<string_list.size(); ++i)
            {
              std::istringstream reader(string_list[i]);
              reader >> int_list[i];// = std::stoul(string_list[i]);
            }
        }
      else if (it->second.type() == typeid(std::vector<double> *))
        {
          std::vector<double> &double_list = *(boost::any_cast<std::vector<double>*>(it->second));
          double_list = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
        }
      else if (it->second.type() == typeid(std::vector<std::vector<unsigned int> > *))
        {
          std::vector<std::vector<unsigned int> > &int_table =
            *(boost::any_cast<std::vector<std::vector<unsigned int> >*>(it->second));

          std::vector<std::string> string_list_of_lists = Utilities::split_string_list(prm.get(it->first), ';');
          int_table.resize(string_list_of_lists.size());
          for (unsigned int i=0; i<int_table.size(); ++i)
            {
              std::vector<std::string> string_list = Utilities::split_string_list(string_list_of_lists[i], ',');
              int_table[i].resize(string_list.size());
              for (unsigned int j=0; j<int_table[i].size(); ++j)
                {
                  std::istringstream reader(string_list[j]);
                  reader >> int_table[i][j];
                }
            }
        }
      else
        {
          AssertThrow(false, ExcNotImplemented());
        }
    }
}

void ParameterAcceptor::parse_parameters_call_back() {}

D2K_NAMESPACE_CLOSE

<commit_msg>Restored compatibility with 8.4.2.<commit_after>//-----------------------------------------------------------
//
//    Copyright (C) 2015 - 2016 by the deal2lkit authors
//
//    This file is part of the deal2lkit library.
//
//    The deal2lkit library is free software; you can use it, redistribute
//    it, and/or modify it under the terms of the GNU Lesser General
//    Public License as published by the Free Software Foundation; either
//    version 2.1 of the License, or (at your option) any later version.
//    The full text of the license can be found in the file LICENSE at
//    the top level of the deal2lkit distribution.
//
//-----------------------------------------------------------

#include <deal2lkit/parameter_acceptor.h>
#include <deal2lkit/utilities.h>
#include <deal.II/base/point.h>
#include <deal.II/base/revision.h>
#include <deal2lkit/revision.h>
#include <fstream>

D2K_NAMESPACE_OPEN

// Static empty class list
std::vector<SmartPointer<ParameterAcceptor> > ParameterAcceptor::class_list;
// Static parameter handler
ParameterHandler ParameterAcceptor::prm;

ParameterAcceptor::ParameterAcceptor(const std::string name) :
  acceptor_id(class_list.size()),
  section_name(name)
{
  SmartPointer<ParameterAcceptor> pt(this, type(*this).c_str());
  class_list.push_back(pt);
}

ParameterAcceptor::~ParameterAcceptor()
{
  class_list[acceptor_id] = 0;
}

std::string ParameterAcceptor::get_section_name() const
{
  return (section_name != "" ? section_name : type(*this));
}

void
ParameterAcceptor::initialize(const std::string filename,
                              const std::string out_filename)
{
  prm.clear();
  declare_all_parameters(prm);
  if (filename != "")
    {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
      // check the extension of input file
      if (filename.substr(filename.find_last_of(".") + 1) == "prm")
        prm.read_input(filename);
      else if (filename.substr(filename.find_last_of(".") + 1) == "xml")
        {
          std::ifstream is(filename);
          prm.read_input_from_xml(is);
#pragma GCC diagnostic pop
        }
      else
        AssertThrow(false, ExcMessage("Invalid extension of parameter file. Please use .prm or .xml"));
    }
  parse_all_parameters(prm);
  if (out_filename != "")
    {
      std::ofstream outfile(out_filename.c_str());
      Assert(outfile, ExcIO());
      std::string extension = out_filename.substr(out_filename.find_last_of(".") + 1);

      if ( extension == "prm")
        {
          outfile << "# Parameter file generated with " << std::endl
                  << "# D2K_GIT_BRANCH=       " << D2K_GIT_BRANCH << std::endl
                  << "# D2K_GIT_SHORTREV=     " << D2K_GIT_SHORTREV << std::endl
                  << "# DEAL_II_GIT_BRANCH=   " << DEAL_II_GIT_BRANCH  << std::endl
                  << "# DEAL_II_GIT_SHORTREV= " << DEAL_II_GIT_SHORTREV << std::endl;
          prm.print_parameters(outfile, ParameterHandler::ShortText);
        }
      else if (extension == "xml")
        prm.print_parameters(outfile, ParameterHandler::XML);
      else if (extension == "latex" || extension == "tex")
        prm.print_parameters(outfile, ParameterHandler::LaTeX);
      else
        AssertThrow(false,ExcNotImplemented());
    }
}

void
ParameterAcceptor::clear()
{
  class_list.clear();
}

void
ParameterAcceptor::log_info()
{
  deallog.push("ParameterAcceptor");
  for (unsigned int i=0; i<class_list.size(); ++i)
    {
      deallog << "Class " << i << ":";
      if (class_list[i])
        deallog << class_list[i]->get_section_name() << std::endl;
      else
        deallog << " NULL" << std::endl;
    }
  deallog.pop();
}

void ParameterAcceptor::parse_all_parameters(ParameterHandler &prm)
{
  std::vector<std::string> old_secs;
  for (unsigned int i=0; i< class_list.size(); ++i)
    if (class_list[i] != NULL)
      {
        std::vector<std::string> secs;
        secs = Utilities::split_string_list(class_list[i]->get_section_name(), sep);
        const unsigned int secs_size = secs.size();

        if (secs_size == 1) // add a subsection with relative path
          {
            // enter the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.enter_subsection(old_secs[s]);

            // enter current subsection
            prm.enter_subsection(secs[0]);

            class_list[i]->parse_parameters(prm);
            class_list[i]->parse_parameters_call_back();

            // leave current subsection
            prm.leave_subsection();

            // leave the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.leave_subsection();

            // the old path is unchanged
          }

        else // we have at least one separator "/"
          {
            if (secs[0]=="") // the section name begins with "/"
              {
                // first of all remove the "empty" section
                secs.erase(secs.begin());

                // this means absolute path so we do not enter
                // the old path
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.enter_subsection(secs[s]);

                class_list[i]->parse_parameters(prm);
                class_list[i]->parse_parameters_call_back();

                // leave all the current sections
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.leave_subsection();

                // since we have started from the root section i.e. "/"
                // we need to set the old path to the current one
                // without the last subsection

                // remove the last subsection
                secs.pop_back();

                // update the old path
                old_secs.swap(secs);

              }
            else // append the path to the old path
              {
                // enter the old path
                for (unsigned int s=0; s<old_secs.size(); ++s)
                  prm.enter_subsection(old_secs[s]);

                // new path
                for (unsigned int s=0; s<secs.size(); ++s)
                  prm.enter_subsection(secs[s]);

                class_list[i]->parse_parameters(prm);
                class_list[i]->parse_parameters_call_back();

                // leave all subsections
                for (unsigned int s=0; s<(secs.size()+old_secs.size()); ++s)
                  prm.leave_subsection();

                // we need now to append the secs path (without the last subsection)
                // to the old path

                // remove last subsection
                secs.pop_back();

                // append secs to old_secs
                old_secs.insert(old_secs.begin(), secs.begin(), secs.end());

              }
          }
      }
}

void ParameterAcceptor::declare_all_parameters(ParameterHandler &prm)
{
  std::vector<std::string> old_secs;
  for (unsigned int i=0; i< class_list.size(); ++i)
    if (class_list[i] != NULL)
      {
        std::vector<std::string> secs;
        secs = Utilities::split_string_list(class_list[i]->get_section_name(), sep);
        const unsigned int secs_size = secs.size();

        if (secs_size == 1) // add a subsection with relative path
          {
            // enter the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.enter_subsection(old_secs[s]);

            // enter current subsection
            prm.enter_subsection(secs[0]);

            class_list[i]->declare_parameters(prm);

            // leave current subsection
            prm.leave_subsection();

            // leave the old path
            for (unsigned int s=0; s<old_secs.size(); ++s)
              prm.leave_subsection();

            // the old path is unchanged
          }

        else // we have at least one separator "/"
          {
            for (unsigned int s=0; s <secs.size(); ++s)
              if (secs[0]=="") // the section name begins with "/"
                {
                  // first of all remove the "empty" section
                  secs.erase(secs.begin());

                  // this means absolute path so we do not enter
                  // the old path
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.enter_subsection(secs[s]);

                  class_list[i]->declare_parameters(prm);

                  // leave all the current sections
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.leave_subsection();

                  // since we have started from the root section i.e. "/"
                  // we need to set the old path to the current one
                  // without the last subsection

                  // remove the last subsection
                  secs.pop_back();

                  // update the old path
                  old_secs.swap(secs);

                }
              else // append the path to the old path
                {
                  // enter the old path
                  for (unsigned int s=0; s<old_secs.size(); ++s)
                    prm.enter_subsection(old_secs[s]);

                  // new path
                  for (unsigned int s=0; s<secs.size(); ++s)
                    prm.enter_subsection(secs[s]);

                  class_list[i]->declare_parameters(prm);

                  // leave all subsections
                  for (unsigned int s=0; s<(secs.size()+old_secs.size()); ++s)
                    prm.leave_subsection();

                  // we need now to append the secs path (without the last subsection)
                  // to the old path

                  // remove last subsection
                  secs.pop_back();

                  // append secs to old_secs
                  old_secs.insert(old_secs.begin(), secs.begin(), secs.end());

                }
          }
      }
}

void ParameterAcceptor::parse_parameters(ParameterHandler &prm)
{
  for (auto it = parameters.begin(); it != parameters.end(); ++it)
    {
      if (it->second.type() == typeid(std::string *))
        {
          *(boost::any_cast<std::string *>(it->second)) = prm.get(it->first);
        }
      else if (it->second.type() == typeid(double *))
        {
          *(boost::any_cast<double *>(it->second)) = prm.get_double(it->first);
        }
      else if (it->second.type() == typeid(int *))
        {
          *(boost::any_cast<int *>(it->second)) = prm.get_integer(it->first);
        }
      else if (it->second.type() == typeid(unsigned int *))
        {
          *(boost::any_cast<unsigned int *>(it->second)) = prm.get_integer(it->first);
        }
      else if (it->second.type() == typeid(bool *))
        {
          *(boost::any_cast<bool *>(it->second)) = prm.get_bool(it->first);
        }
      // Here we have the difficult types...
      // First all point types.
      else if (it->second.type() == typeid(Point<1> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 1);

          Point<1> &pp = *(boost::any_cast<Point<1>*>(it->second));
          pp[0] = p[0];
        }
      else if (it->second.type() == typeid(Point<2> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 2);

          Point<2> &pp = *(boost::any_cast<Point<2>*>(it->second));
          pp[0] = p[0];
          pp[1] = p[1];
        }
      else if (it->second.type() == typeid(Point<3> *))
        {
          std::vector<double> p =
            Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
          AssertDimension(p.size(), 3);

          Point<3> &pp = *(boost::any_cast<Point<3>*>(it->second));
          pp[0] = p[0];
          pp[1] = p[1];
          pp[2] = p[2];
        }
      else if (it->second.type() == typeid(std::vector<std::string> *))
        {
          std::vector<std::string> &string_list = *(boost::any_cast<std::vector<std::string>*>(it->second));
          string_list = Utilities::split_string_list(prm.get(it->first));
        }
      else if (it->second.type() == typeid(std::vector<unsigned int> *))
        {
          std::vector<unsigned int> &int_list = *(boost::any_cast<std::vector<unsigned int>*>(it->second));
          std::vector<std::string> string_list = Utilities::split_string_list(prm.get(it->first));
          int_list.resize(string_list.size());
          for (unsigned int i=0; i<string_list.size(); ++i)
            {
              std::istringstream reader(string_list[i]);
              reader >> int_list[i];// = std::stoul(string_list[i]);
            }
        }
      else if (it->second.type() == typeid(std::vector<double> *))
        {
          std::vector<double> &double_list = *(boost::any_cast<std::vector<double>*>(it->second));
          double_list = Utilities::string_to_double(Utilities::split_string_list(prm.get(it->first)));
        }
      else if (it->second.type() == typeid(std::vector<std::vector<unsigned int> > *))
        {
          std::vector<std::vector<unsigned int> > &int_table =
            *(boost::any_cast<std::vector<std::vector<unsigned int> >*>(it->second));

          std::vector<std::string> string_list_of_lists = Utilities::split_string_list(prm.get(it->first), ';');
          int_table.resize(string_list_of_lists.size());
          for (unsigned int i=0; i<int_table.size(); ++i)
            {
              std::vector<std::string> string_list = Utilities::split_string_list(string_list_of_lists[i], ',');
              int_table[i].resize(string_list.size());
              for (unsigned int j=0; j<int_table[i].size(); ++j)
                {
                  std::istringstream reader(string_list[j]);
                  reader >> int_table[i][j];
                }
            }
        }
      else
        {
          AssertThrow(false, ExcNotImplemented());
        }
    }
}

void ParameterAcceptor::parse_parameters_call_back() {}

D2K_NAMESPACE_CLOSE

<|endoftext|>


<commit_before>
#include <iostream>
#include <algorithm>
#include <set>
#include <iomanip>

#include <glbinding/Version.h>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/extension.h>

#include <glbinding-aux/Meta.h>
#include <glbinding-aux/ValidVersions.h>
#include <glbinding-aux/types_to_string.h>

using namespace gl;
using namespace glbinding;

int main(int, char * [])
{
    // enlist all versions

    std::cout << std::endl << std::endl << "[VERSIONS]" << std::endl << std::endl;

    std::cout << "# Versions: " << aux::Meta::versions().size() << std::endl << std::endl;

    for (Version v : aux::Meta::versions())
        std::cout << v.toString() << std::endl;

    // enlist all enums

    std::cout << std::endl << std::endl << "[ENUMS]" << std::endl << std::endl;

    std::cout << "# Enums: " << aux::Meta::enums().size() << std::endl << std::endl;

    for (GLenum e : aux::Meta::enums()) { // c++ 14 ...
        const auto strings = aux::Meta::getString(e);
        std::cout << " (" << std::hex << std::showbase << std::internal << std::setfill('0') << std::setw(8)
            << static_cast<std::underlying_type<GLenum>::type>(e) << ") ";

        std::cout << e;
        /*for (auto i = 0; i < strings.size(); ++i)
            std::cout << strings[i] << (strings.size() > 1 && i < (strings.size() - 1) ? " | " : "");*/

        std::cout << std::dec << std::endl;
    }

    //for (auto i = 0; i < aux::Meta::enums().size(); ++i) {
    //    const auto e = aux::Meta::enums()[i];
    //    std::cout << " (" << std::hex << std::showbase << std::internal << std::setfill('0') << std::setw(8)
    //        << static_cast<std::underlying_type<GLenum>::type>(e) << ") " << aux::Meta::getString(e) << std::dec << std::endl;
    //}

    std::cout << std::dec;

    // enlist all extensions

    std::cout << std::endl << std::endl << "[EXTENSIONS]" << std::endl << std::endl;

    std::cout << " # Extensions: " << aux::Meta::extensions().size() << std::endl << std::endl;

    for (GLextension extension : aux::Meta::extensions())
    {
        const Version v = aux::Meta::version(extension);
        std::cout << " " << aux::Meta::getString(extension) << " " << (v.isNull() ? "" : v.toString()) << std::endl;
    }

    return 0;
}
<commit_msg>add revision info to meta output<commit_after>
#include <iostream>
#include <algorithm>
#include <set>
#include <iomanip>

#include <glbinding/Version.h>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/extension.h>

#include <glbinding-aux/Meta.h>
#include <glbinding-aux/ValidVersions.h>
#include <glbinding-aux/types_to_string.h>

using namespace gl;
using namespace glbinding;

int main(int, char * [])
{
    // enlist all versions

    std::cout << std::endl << std::endl << "[VERSIONS]" << std::endl << std::endl;

    std::cout << "# Versions: " << aux::Meta::versions().size() << std::endl << std::endl;

    for (Version v : aux::Meta::versions())
        std::cout << v.toString() << std::endl;

    // enlist all enums

    std::cout << std::endl << std::endl << "[ENUMS]" << std::endl << std::endl;

    std::cout << "# Enums: " << aux::Meta::enums().size() << std::endl << std::endl;

    for (GLenum e : aux::Meta::enums()) { // c++ 14 ...
        const auto strings = aux::Meta::getString(e);
        std::cout << " (" << std::hex << std::showbase << std::internal << std::setfill('0') << std::setw(8)
            << static_cast<std::underlying_type<GLenum>::type>(e) << ") ";

        std::cout << e;
        /*for (auto i = 0; i < strings.size(); ++i)
            std::cout << strings[i] << (strings.size() > 1 && i < (strings.size() - 1) ? " | " : "");*/

        std::cout << std::dec << std::endl;
    }

    //for (auto i = 0; i < aux::Meta::enums().size(); ++i) {
    //    const auto e = aux::Meta::enums()[i];
    //    std::cout << " (" << std::hex << std::showbase << std::internal << std::setfill('0') << std::setw(8)
    //        << static_cast<std::underlying_type<GLenum>::type>(e) << ") " << aux::Meta::getString(e) << std::dec << std::endl;
    //}

    std::cout << std::dec;

    // enlist all extensions

    std::cout << std::endl << std::endl << "[EXTENSIONS]" << std::endl << std::endl;

    std::cout << " # Extensions: " << aux::Meta::extensions().size() << std::endl << std::endl;

    for (GLextension extension : aux::Meta::extensions())
    {
        const Version v = aux::Meta::version(extension);
        std::cout << " " << aux::Meta::getString(extension) << " " << (v.isNull() ? "" : v.toString()) << std::endl;
    }

    std::cout << std::endl
        << "OpenGL Revision: " << aux::Meta::glRevision() << " (gl.xml)" << std::endl << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file 	ex5.cpp
 * @author 	Fabian Wegscheider
 * @date 	Jun 5, 2017
 */

#include <iostream>
#include <fstream>
#include <boost/timer/timer.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

/**
 * main function which reads a graph from a .gph file, then calculates shortest
 * paths from all vertices to the first vertex with the dijsktra algorithm
 * and prints the furthest vertex together with its distance
 * to the standard output
 * @param numargs number of inputs on command line
 * @param args array of inputs on command line
 * @return whether the function operated successfully
 */
int main(int numargs, char *args[]) {

	timer::cpu_timer t;

	if (numargs != 2) {
		cout << "Usage: " << args[0] << " filename" << endl;
		exit(EXIT_FAILURE);
	}

	ifstream inputFile;
	inputFile.open(args[1]);							//trying to read file
	if (inputFile.fail()) {
		cerr << "file could not be read" << endl;
		exit(EXIT_FAILURE);
	}

	typedef adjacency_list<vecS, vecS, undirectedS,
			no_property, property<edge_weight_t, double>> Graph;
	typedef pair<int,int> Edge;

	int numVertices;
	int numEdges;

	string line;
	getline(inputFile, line);					//first line is read
	vector<string> parts;
	split(parts, line, is_any_of(" "));

	if (parts.size() != 2) {
		cerr << "error in file: first line should consist of two integers!" << endl;
		exit(EXIT_FAILURE);
	}

	try {
		numVertices = stoi(parts[0]);		//information from the first line
		numEdges = stoi(parts[1]);			//are stored
	} catch (...) {
		cerr << "error in file: first line should consist of two integers!" << endl;
		exit(EXIT_FAILURE);
	}

	Edge *edges =  new Edge[numEdges];			//in these arrays all information about
	double *weights = new double[numEdges];		//the edges are stored

	int i = 0;

	//read line by line
	while (getline(inputFile, line)) {
		split(parts, line, is_any_of(" "));
		if (parts.size() != 3) {
			cerr << "error in line " << (i+2) << ": line should consists of "
					"two integers and a double!" << endl;
			exit(EXIT_FAILURE);
		}
		try {
			edges[i] = Edge(stoi(parts[0])-1, stoi(parts[1])-1);
			weights[i] = stod(parts[2]);
		} catch(...) {
			cerr << "error in line " << (i+2) << ": line should consists of "
					"two integers and a double!" << endl;
			exit(EXIT_FAILURE);
		}
		++i;
	}

	//undirected graph is constructed with all edges and their weights
	Graph g(edges, edges + numEdges , weights, numVertices);

	vector<double> distances(numVertices);

	//call of dijsktra
	dijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));

	property_map<Graph, vertex_index_t>::type index = get(vertex_index, g);

	double maxDist = 0;
	int maxIdx = 0;
	graph_traits<Graph>::vertex_iterator it;

	//search for furthest vertex
	for (it = vertices(g).first+1; it != vertices(g).second; ++it) {
		double tmp = distances[*it];
		if (tmp > maxDist) {
			maxDist = tmp;
			maxIdx = index(*it);
		}
	}

	cout << "RESULT VERTEX " << (maxIdx+1) << endl;
	cout << "RESULT DIST " << maxDist << endl;
	cout << endl << t.format() <<  endl;

	exit(EXIT_SUCCESS);
}
<commit_msg>Delete ex5.cpp<commit_after><|endoftext|>