<commit_before>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-2 21:08:42
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

ll N, D;
ll X[100010];
ll L[100010];
ll R[100010];
ll sumR[100010];
ll sumL[100010];
ll cnt[100010];

int main()
{
  cin >> N >> D;
  for (auto i = 0; i < N; i++)
  {
    cin >> X[i];
  }
  for (auto i = 0; i < N; i++)
  {
    R[i] = i;
    L[i] = i;
  }
  ll l = 0, r = 0;
  while (r < N)
  {
    if (X[r] - X[l] <= D)
    {
      R[l] = r;
      r++;
    }
    else
    {
      l++;
    }
  }
  r = N - 1;
  while (l < N)
  {
    if (X[r] - X[l] <= D)
    {
      R[l] = r;
      l++;
    }
    else
    {
      l++;
    }
  }
  l = N - 1;
  while (l >= 0)
  {
    if (X[r] - X[l] <= D)
    {
      L[r] = l;
      l--;
    }
    else
    {
      r--;
    }
  }
  l = 0;
  while (r >= 0)
  {
    if (X[r] - X[l] <= D)
    {
      L[r] = l;
      r--;
    }
    else
    {
      r--;
    }
  }
  sumR[0] = sumL[0] = 0;
  for (auto i = 1; i <= N; i++)
  {
    sumR[i] = sumR[i - 1] + (R[i - 1] - (i - 1));
    cerr << "sumR[" << i << "] = " << sumR[i] << endl;
  }
  for (auto i = 1; i <= N; i++)
  {
    sumL[i] = sumL[i - 1] + (i - 1 - L[i - 1]);
    cerr << "sumL[" << i << "] = " << sumL[i] << endl;
  }
  for (auto j = 0; j < N; j++)
  {
    ll n = R[j] - (L[j] - 1) - 1;
    cerr << "j = " << j << ", n = " << n << endl;
    cnt[j] = n * (n - 1) / 2;
    ll ext = sumR[R[j] + 1] - sumL[L[j]] - n;
    cerr << "ext = " << ext << endl;
    cnt[j] -= ext;
  }
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    ans += cnt[i];
  }
  cout << ans << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-2 21:08:42
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

ll N, D;
ll X[100010];
ll L[100010];
ll R[100010];
ll sumR[100010];
ll sumL[100010];
ll cnt[100010];

int main()
{
  cin >> N >> D;
  for (auto i = 0; i < N; i++)
  {
    cin >> X[i];
  }
  for (auto i = 0; i < N; i++)
  {
    R[i] = i;
    L[i] = i;
  }
  ll l = 0, r = 0;
  while (r < N)
  {
    if (X[r] - X[l] <= D)
    {
      R[l] = r;
      r++;
    }
    else
    {
      l++;
    }
  }
  r = N - 1;
  while (l < N)
  {
    if (X[r] - X[l] <= D)
    {
      R[l] = r;
      l++;
    }
    else
    {
      l++;
    }
  }
  l = N - 1;
  while (l >= 0)
  {
    if (X[r] - X[l] <= D)
    {
      L[r] = l;
      l--;
    }
    else
    {
      r--;
    }
  }
  l = 0;
  while (r >= 0)
  {
    if (X[r] - X[l] <= D)
    {
      L[r] = l;
      r--;
    }
    else
    {
      r--;
    }
  }
  sumR[0] = sumL[0] = 0;
  for (auto i = 1; i <= N; i++)
  {
    sumR[i] = sumR[i - 1] + (R[i - 1] - (i - 1));
    // cerr << "sumR[" << i << "] = " << sumR[i] << endl;
  }
  for (auto i = 1; i <= N; i++)
  {
    sumL[i] = sumL[i - 1] + (i - 1 - L[i - 1]);
    // cerr << "sumL[" << i << "] = " << sumL[i] << endl;
  }
  for (auto j = 0; j < N; j++)
  {
    ll n = R[j] - (L[j] - 1) - 1;
    // cerr << "j = " << j << ", n = " << n << endl;
    cnt[j] = n * (n - 1) / 2;
    ll ext = sumL[R[j] + 1] - sumR[L[j]] - n;
    // cerr << "ext = " << ext << endl;
    cnt[j] -= ext;
  }
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    ans += cnt[i];
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebScrollbarTheme.h"

#include "platform/scroll/ScrollbarThemeMacCommon.h"

using namespace WebCore;

namespace blink {

#if defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
COMPILE_ASSERT(ScrollerStyleLegacy == NSScrollerStyleLegacy, ScrollerStyle_Legacy_must_be_equal);
COMPILE_ASSERT(ScrollerStyleOverlay == NSScrollerStyleOverlay, ScrollerStyle_Overlay_must_be_equal);
#endif

void WebScrollbarTheme::updateScrollbars(
    float initialButtonDelay, float autoscrollButtonDelay,
    bool jumpOnTrackClick, bool redraw)
{
    ScrollbarTheme* theme = ScrollbarTheme::theme();
    if (theme->isMockTheme())
        return;

    static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged(
        initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}

void WebScrollbarTheme::updateScrollbars(
    float initialButtonDelay, float autoscrollButtonDelay,
    bool jumpOnTrackClick, ScrollerStyle preferredScrollerStyle, bool redraw)
{
    updateScrollbars(initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}

} // namespace blink
<commit_msg>mac: Fix build with 10.7+ sdk.<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebScrollbarTheme.h"

#include "platform/scroll/ScrollbarThemeMacCommon.h"

using namespace WebCore;

namespace blink {

#if defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
// TODO(rsesek): Reenable this after making sure it actually builds.
//COMPILE_ASSERT(ScrollerStyleLegacy == NSScrollerStyleLegacy, ScrollerStyle_Legacy_must_be_equal);
//COMPILE_ASSERT(ScrollerStyleOverlay == NSScrollerStyleOverlay, ScrollerStyle_Overlay_must_be_equal);
#endif

void WebScrollbarTheme::updateScrollbars(
    float initialButtonDelay, float autoscrollButtonDelay,
    bool jumpOnTrackClick, bool redraw)
{
    ScrollbarTheme* theme = ScrollbarTheme::theme();
    if (theme->isMockTheme())
        return;

    static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged(
        initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}

void WebScrollbarTheme::updateScrollbars(
    float initialButtonDelay, float autoscrollButtonDelay,
    bool jumpOnTrackClick, ScrollerStyle preferredScrollerStyle, bool redraw)
{
    updateScrollbars(initialButtonDelay, autoscrollButtonDelay, jumpOnTrackClick, redraw);
}

} // namespace blink
<|endoftext|>


<commit_before>#include <iostream>
#include <list>
#include <sstream>
#include <Ptakopysk/System/Assets.h>
#include <Ptakopysk/System/Events.h>
#include <Ptakopysk/System/GameManager.h>
#include <Ptakopysk/System/GameObject.h>
#include <Ptakopysk/Components/Transform.h>
#include <Ptakopysk/Components/SpriteRenderer.h>
#include <XeCore/Common/Logger.h>
#include <XeCore/Common/Concurrent/Thread.h>

using namespace Ptakopysk;

const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 574;
const sf::Color WINDOW_COLOR = sf::Color( 128, 128, 128, 255 );

void onEvent( Events::Event* ev )
{
}

int main()
{
    /// initialization
    LOG_SETUP( "log.log" );
    Events::use().setCallback( &onEvent );
    GameManager::initialize();

    /// scene
    sf::RenderWindow* window = xnew sf::RenderWindow(
        sf::VideoMode( WINDOW_WIDTH, WINDOW_HEIGHT ),
        "Floppy Disk",
        sf::Style::Titlebar | sf::Style::Close
    );

    /// game manager
    GameManager* gameManager = xnew GameManager();
    gameManager->jsonToScene( gameManager->loadJson( "assets/scenes/game.json" ) );
    gameManager->saveJson( "assets/scenes/_game.json", gameManager->sceneToJson() );

    /// main loop
    srand( time( 0 ) );
    sf::Clock timer;
    sf::Clock deltaTimer;
    while( window->isOpen() )
    {
        sf::Event event;
        while( window->pollEvent( event ) )
        {
            if( event.type == sf::Event::Closed )
            {
                window->close();
            }
            else if( event.type == sf::Event::KeyPressed )
            {
                if( event.key.code == sf::Keyboard::Escape )
                    window->close();
            }
        }
        /// timers update
        float dt = deltaTimer.getElapsedTime().asSeconds();
        deltaTimer.restart();

        /// process frame
        Events::use().dispatch();
        gameManager->processPhysics( dt );
        gameManager->processUpdate( dt );
        window->clear( WINDOW_COLOR );
        gameManager->processRender( window );
        window->display();
        XeCore::Common::Concurrent::Thread::sleep( 1000 / 30 );
    }

    DELETE_OBJECT( window );
    DELETE_OBJECT( gameManager );
    Assets::destroy();
    Events::destroy();

    return 0;
}
<commit_msg>main.cpp includes cleanup<commit_after>#include <iostream>
#include <Ptakopysk/System/Assets.h>
#include <Ptakopysk/System/Events.h>
#include <Ptakopysk/System/GameManager.h>
#include <XeCore/Common/Logger.h>
#include <XeCore/Common/Concurrent/Thread.h>

using namespace Ptakopysk;

const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 574;
const sf::Color WINDOW_COLOR = sf::Color( 128, 128, 128, 255 );

void onEvent( Events::Event* ev )
{
}

int main()
{
    /// initialization
    LOG_SETUP( "log.log" );
    Events::use().setCallback( &onEvent );
    GameManager::initialize();

    /// scene
    sf::RenderWindow* window = xnew sf::RenderWindow(
        sf::VideoMode( WINDOW_WIDTH, WINDOW_HEIGHT ),
        "Floppy Disk",
        sf::Style::Titlebar | sf::Style::Close
    );

    /// game manager
    GameManager* gameManager = xnew GameManager();
    gameManager->jsonToScene( gameManager->loadJson( "assets/scenes/game.json" ) );
    gameManager->saveJson( "assets/scenes/_game.json", gameManager->sceneToJson() );

    /// main loop
    srand( time( 0 ) );
    sf::Clock timer;
    sf::Clock deltaTimer;
    while( window->isOpen() )
    {
        sf::Event event;
        while( window->pollEvent( event ) )
        {
            if( event.type == sf::Event::Closed )
            {
                window->close();
            }
            else if( event.type == sf::Event::KeyPressed )
            {
                if( event.key.code == sf::Keyboard::Escape )
                    window->close();
            }
        }
        /// timers update
        float dt = deltaTimer.getElapsedTime().asSeconds();
        deltaTimer.restart();

        /// process frame
        Events::use().dispatch();
        gameManager->processPhysics( dt );
        gameManager->processUpdate( dt );
        window->clear( WINDOW_COLOR );
        gameManager->processRender( window );
        window->display();
        XeCore::Common::Concurrent::Thread::sleep( 1000 / 30 );
    }

    DELETE_OBJECT( window );
    DELETE_OBJECT( gameManager );
    Assets::destroy();
    Events::destroy();

    return 0;
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum 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.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Ethereum client.
 */

#include <fstream>
#include <iostream>
#include <liblll/Compiler.h>
#include <libethsupport/CommonIO.h>
#include <libethsupport/CommonData.h>
#include "BuildInfo.h"
using namespace std;
using namespace eth;

void help()
{
	cout
		<< "Usage lllc [OPTIONS] <file>" << endl
        << "Options:" << endl
        << "    -h,--help  Show this help message and exit." << endl
        << "    -V,--version  Show the version and exit." << endl;
        exit(0);
}

void version()
{
	cout << "LLLC, the Lovely Little Language Compiler " << ETH_QUOTED(ETH_VERSION) << endl;
	cout << "  By Gav Wood, (c) 2014." << endl;
	cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

enum Mode { Binary, Hex, ParseTree };

int main(int argc, char** argv)
{
	string infile;
	Mode mode = Hex;

	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-h" || arg == "--help")
			help();
		else if (arg == "-b" || arg == "--binary")
			mode = Binary;
		else if (arg == "-h" || arg == "--hex")
			mode = Hex;
		else if (arg == "-t" || arg == "--parse-tree")
			mode = ParseTree;
		else if (arg == "-V" || arg == "--version")
			version();
		else
			infile = argv[i];
	}

	string src;
	if (infile.empty())
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			src.append(s);
		}
	}
	else
		src = asString(contents(infile));

	if (src.empty())
		cerr << "Empty file." << endl;
	else if (mode == Binary || mode == Hex)
	{
		vector<string> errors;
		auto bs = compileLLL(src, &errors);
		if (mode == Hex)
			cout << toHex(bs) << endl;
		else if (mode == Binary)
			cout.write((char const*)bs.data(), bs.size());
		for (auto const& i: errors)
			cerr << i << endl;
	}
	else if (mode == ParseTree)
	{
		cout << parseLLL(src) << endl;
	}

	return 0;
}
<commit_msg>Ever more repotting.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum 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.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Ethereum client.
 */

#include <fstream>
#include <iostream>
#include <liblll/Compiler.h>
#include <libethsupport/CommonIO.h>
#include <libethsupport/CommonData.h>
#include "BuildInfo.h"
using namespace std;
using namespace eth;

void help()
{
	cout
		<< "Usage lllc [OPTIONS] <file>" << endl
        << "Options:" << endl
		<< "    -b,--binary  Parse, compile and assemble; output byte code in binary." << endl
		<< "    -x,--hex  Parse, compile and assemble; output byte code in hex." << endl
//		<< "    -a,--assembly  Only parse and compile; show assembly." << endl
		<< "    -t,--parse-tree  Only parse; show parse tree." << endl
		<< "    -h,--help  Show this help message and exit." << endl
		<< "    -V,--version  Show the version and exit." << endl;
        exit(0);
}

void version()
{
	cout << "LLLC, the Lovely Little Language Compiler " << ETH_QUOTED(ETH_VERSION) << endl;
	cout << "  By Gav Wood, (c) 2014." << endl;
	cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

enum Mode { Binary, Hex, ParseTree };

int main(int argc, char** argv)
{
	string infile;
	Mode mode = Hex;

	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-h" || arg == "--help")
			help();
		else if (arg == "-b" || arg == "--binary")
			mode = Binary;
		else if (arg == "-x" || arg == "--hex")
			mode = Hex;
		else if (arg == "-t" || arg == "--parse-tree")
			mode = ParseTree;
		else if (arg == "-V" || arg == "--version")
			version();
		else
			infile = argv[i];
	}

	string src;
	if (infile.empty())
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			src.append(s);
		}
	}
	else
		src = asString(contents(infile));

	if (src.empty())
		cerr << "Empty file." << endl;
	else if (mode == Binary || mode == Hex)
	{
		vector<string> errors;
		auto bs = compileLLL(src, &errors);
		if (mode == Hex)
			cout << toHex(bs) << endl;
		else if (mode == Binary)
			cout.write((char const*)bs.data(), bs.size());
		for (auto const& i: errors)
			cerr << i << endl;
	}
	else if (mode == ParseTree)
	{
		cout << parseLLL(src) << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>bae95bb0-4b02-11e5-a0b9-28cfe9171a43<commit_msg>Initial commit.13<commit_after>baf77d8c-4b02-11e5-a923-28cfe9171a43<|endoftext|>


<commit_before>a31ba507-4b02-11e5-8213-28cfe9171a43<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>a32d318a-4b02-11e5-a4c5-28cfe9171a43<|endoftext|>


<commit_before>53c2ed4a-ad5c-11e7-bac2-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>5453138f-ad5c-11e7-be2f-ac87a332f658<|endoftext|>


<commit_before>7ccf7b94-2749-11e6-bab1-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>7ce0528f-2749-11e6-9980-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>

#include "Coordinate.h"
#include "Maze.h"

using std::vector;
using std::string;

const Coordinate dirs[] = {
  Coordinate( -1,  0 ),
  Coordinate(  0,  1 ),
  Coordinate(  0, -1 ),
  Coordinate(  1,  0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };

bool isPartOf( const char arr[], char val ){
  return arr[0] == val || arr[1] == val;
}

int main(){

  std::cout << "program begin" << std::endl << std::endl;

  int w = 21, h = 21;
  string inputW, inputH;

  std::cout << "maze width (20): ";
  std::getline( std::cin, inputW );
  if( !inputW.empty() )
    w = std::stoi( inputW );

  std::cout << "maze height (20): ";
  std::getline( std::cin, inputH );
  if( !inputH.empty() )
    h = std::stoi( inputH );

  if( w % 2 == 0 )
    w += 1;
  if( h % 2 == 0 )
    h += 1;

  Maze maze( w, h );

  vector<vector<char>> map;
  Coordinate player( 1, 1 );
  string dir;

  int round = 0;

  int security = 1000;
  while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){

    std::cout << "start frame" << std::endl;

    maze.fillPrintMap( map );

    map[ player.x ][ player.y ] = 'o';

    std::system( "clear" );

    std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;

    for( int i = 0; i < h; ++i ){
      std::cout << " ";
      for( int j = 0; j < w; ++j ){
        std::cout << map[j][i];
      }
      std::cout << std::endl;
    }

    std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
    std::cin >> dir;

    unsigned int dirIndex = -1;
    while( ++dirIndex < dir.length() ){
      if( isPartOf( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
        player = player + dirs[ 0 ];
      }
      if( isPartOf( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
        player = player + dirs[ 1 ];
      }
      if( isPartOf( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
        player = player + dirs[ 2 ];
      }
      if( isPartOf( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
        player = player + dirs[ 3 ];
      }
    }

  }

  if( security == 0 )
    std::cout << "took too much, we were afraid the program broke" << std::endl;
  else
    std::cout << "YOU WIN!" << std::endl;

  std::cout << std::endl << "program end" << std::endl;

  return 0;
}
<commit_msg>changed `isPartOf` to `arrayContains`<commit_after>#include <iostream>
#include <vector>
#include <string>

#include "Coordinate.h"
#include "Maze.h"

using std::vector;
using std::string;

const Coordinate dirs[] = {
  Coordinate( -1,  0 ),
  Coordinate(  0,  1 ),
  Coordinate(  0, -1 ),
  Coordinate(  1,  0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };

bool arrayContains( const char arr[], char val ){
  return arr[0] == val || arr[1] == val;
}

int main(){

  std::cout << "program begin" << std::endl << std::endl;

  int w = 21, h = 21;
  string inputW, inputH;

  std::cout << "maze width (20): ";
  std::getline( std::cin, inputW );
  if( !inputW.empty() )
    w = std::stoi( inputW );

  std::cout << "maze height (20): ";
  std::getline( std::cin, inputH );
  if( !inputH.empty() )
    h = std::stoi( inputH );

  if( w % 2 == 0 )
    w += 1;
  if( h % 2 == 0 )
    h += 1;

  Maze maze( w, h );

  vector<vector<char>> map;
  Coordinate player( 1, 1 );
  string dir;

  int round = 0;

  int security = 1000;
  while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){

    std::cout << "start frame" << std::endl;

    maze.fillPrintMap( map );

    map[ player.x ][ player.y ] = 'o';

    std::system( "clear" );

    std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;

    for( int i = 0; i < h; ++i ){
      std::cout << " ";
      for( int j = 0; j < w; ++j ){
        std::cout << map[j][i];
      }
      std::cout << std::endl;
    }

    std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
    std::cin >> dir;

    unsigned int dirIndex = -1;
    while( ++dirIndex < dir.length() ){
      if( arrayContains( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
        player = player + dirs[ 0 ];
      }
      if( arrayContains( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
        player = player + dirs[ 1 ];
      }
      if( arrayContains( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
        player = player + dirs[ 2 ];
      }
      if( arrayContains( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
        player = player + dirs[ 3 ];
      }
    }

  }

  if( security == 0 )
    std::cout << "took too much, we were afraid the program broke" << std::endl;
  else
    std::cout << "YOU WIN!" << std::endl;

  std::cout << std::endl << "program end" << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "camera.h"
#include "scene.h"
#include "sphere.h"
#include "bsdf.h"
#include "integrator.h"

using std::cout;

int main(int argc, char** args)
{
  Scene scene;
  BRDF* b = new Diffuse{1.0};

  BRDF* light = new EmissiveBRDF{spectrum{4.0}};

  // scene.add_shape( new Shape( new Sphere{ Vec3{-1.0, -1.0, 0.5}, 0.5},
  //                             light,
  //                             new SolidColor(spectrum{1.0})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{2.0, -1.0, 0.0}, 1.0},
                              b,
                              new SolidColor(spectrum{1.0, 0.2, 0.3})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{1.0, 1.0, 0.5}, 0.05},
                              light,
                              new SolidColor(spectrum{1.0})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, 1.0, 0.0}, 1.0},
                              b,
                              new SolidColor(spectrum{0.2, 1.0, 0.3})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{0.0, -1000.0, 0.0}, 998.0},
                              b,
                              new SolidColor(spectrum{0.0, 0.0, 1.0})) );

  const uint WIDTH = 800;
  const uint HEIGHT = 600;

  Film f(WIDTH, HEIGHT);
  Camera cam {Vec3{0, 0, 5}, Vec3{0, 0, 0}, Vec3{0, 1, 0}, PI / 2.0, scalar(WIDTH)/HEIGHT};

  PathTracerIntegrator igr;

  igr.render(&cam, &scene, &f);
  //f.render_to_console(cout);
  f.render_to_ppm(cout, new BoxFilter, new LinearToneMapper);

  return 0;
}

<commit_msg>Default scene modification, to include mirrors<commit_after>#include <iostream>

#include "camera.h"
#include "scene.h"
#include "sphere.h"
#include "bsdf.h"
#include "integrator.h"

using std::cout;

void smallpt_scene(Scene& scene)
{
  BRDF* diffuse = new Diffuse{1.0};
  BRDF* light = new EmissiveBRDF{spectrum{12.0}};
  scene.add_shape(new Shape(new Sphere{ Vec3{1e5+1, 40.8, 81.6}, 1e5 },
                      diffuse,
                      new SolidColor(spectrum{0.75,0.25,0.25})));
  scene.add_shape(new Shape(new Sphere{ Vec3{-1e5+99, 40.8, 81.6}, 1e5 },
                      diffuse,
                      new SolidColor(spectrum{0.25, 0.25, 0.75})));
  scene.add_shape(new Shape(new Sphere{Vec3{50, 40.8, 1e5}, 1e5},
                      diffuse,
                      new SolidColor(spectrum{0.75})));
  scene.add_shape(new Shape(new Sphere{Vec3{50, 1e5, 81.6}, 1e5},
                      diffuse,
                      new SolidColor(spectrum{0.75})));
  scene.add_shape(new Shape(new Sphere{Vec3{50, -1e5+81.6, 81.6}, 1e5},
                      diffuse,
                      new SolidColor(spectrum{0.75})));

  scene.add_shape(new Shape(new Sphere{Vec3{50,681.6-.27,81.6}, 600},
                      light,
                      new SolidColor(spectrum{1.0})));
}

int main(int argc, char** args)
{
  Scene scene;
  BRDF* b = new Diffuse{1.0};

  BRDF* light = new EmissiveBRDF{spectrum{4.0}};
  BRDF* mirror = new PerfectMirrorBRDF{};

  //smallpt_scene(scene);

  scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, -1.0, 0.0}, 1.0},
                              mirror,
                              new SolidColor(spectrum{1.0})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{2.0, -1.0, 0.0}, 1.0},
                              b,
                              new SolidColor(spectrum{1.0, 0.2, 0.3})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{-2.0, 1.0, 0.0}, 1.0},
                              b,
                              new SolidColor(spectrum{0.2, 1.0, 0.3})) );

  scene.add_shape( new Shape( new Sphere{ Vec3{0.0, -1000.0, 0.0}, 998.0},
                              b,
                              new SolidColor(spectrum{0.1, 0.2, 0.9})));

  scene.add_shape( new Shape( new Sphere{ Vec3{0.0, 3.0, 1.0}, 0.05},
                              light,
                              new SolidColor(spectrum{1.0})) );

  const uint WIDTH = 800;
  const uint HEIGHT = 600;

  Film f(WIDTH, HEIGHT);
  Camera cam {Vec3{0, 0, 5}, Vec3{0, 0, 0}, Vec3{0, 1, 0}, PI / 2.0,
  scalar(WIDTH)/HEIGHT};
  // Vec3 pos{50, 52, 295.6};
  // Vec3 dir = Vec3{0, -0.042612, -1}.normal();
  // Camera cam{ pos, pos+dir, Vec3{0, 1, 0}, PI/2.0, scalar(WIDTH)/HEIGHT};

  PathTracerIntegrator igr;

  igr.render(&cam, &scene, &f);
  //f.render_to_console(cout);
  f.render_to_ppm(cout, new BoxFilter, new LinearToneMapper);

  return 0;
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <mpi.h>
#include <boost/regex.hpp>
#include <regex>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>

typedef std::map<std::string, std::set<std::string>> LinkMap;

int g_world_size;
int g_my_rank;
std::string g_filename = "enwiki-20160305-pages-articles.xml";

void parse_file(MPI_File *infile);
void regex_test();
void find_links(std::string section, std::string current_title, LinkMap &links);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  MPI_Init(NULL, NULL);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_my_rank);

  // Print off a hello world message
  printf("Hello world from rank %d out of %d processors\n", g_my_rank, g_world_size);

  // Open up the wikipedia xml file
  MPI_File infile;
  MPI_File_open(MPI_COMM_WORLD, (char *)g_filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);

  // Parse the file
  parse_file(&infile);

  if (g_my_rank == 0){
    //regex_test();
  }

  // Close the file
  MPI_File_close(&infile);

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

// Parse the input file: pull out page titles and any links from a page to another
void parse_file(MPI_File *infile){
  //get file size
  MPI_Offset filesize;
  MPI_File_get_size(*infile, &filesize);

  // the size of each chunk that will be read in at a time
  //  TODO: find an optimal setting for this so that we aren't producing too many read reqeusts
  int chunk_size = 1000;
  //get size of the chunk this rank will handle
  long long int max_size = filesize / g_world_size;
  // where this rank will stop reading the file (aka where the next rank will start reading)
  long long int stopping_point = max_size * (g_my_rank + 1);

  //get the start point for this rank in the file:
  //    subtract chunk_size from the 'logical' start point to make sure
  //    that each node has a title for the links that it finds
  MPI_Offset offset = std::max(max_size * g_my_rank, max_size * g_my_rank - chunk_size);

  printf("Rank %d ==> start point: %lld\n", g_my_rank, offset);

  // the regex to find a tile in the file
  boost::regex title_regex("<title[^>]*>([^<]+)</title>");

  // declare some variables
  char * chunk;
  std::string current_title = "";
  LinkMap links;

  // keep going until the offset is in the next ranks group
  while (offset < stopping_point && links.size() < 100){
    // allocate a chunk to read in from the file
    chunk = (char *)malloc( (chunk_size + 1)*sizeof(char));
    // read it in
    MPI_File_read_at(*infile, offset, chunk, chunk_size, MPI_CHAR, MPI_STATUS_IGNORE);
    // end the string
    chunk[chunk_size] = '\0';
    // make it a c++ string for convenience
    std::string chunk_string(chunk);
    // free the allocated space
    free(chunk);
    //std::cout << "reading" << std::endl;
    //std::cout << chunk_string << std::endl;
    boost::smatch title_match;
    // keep looping while there is another title in the the current chunk
    while (boost::regex_search(chunk_string, title_match, title_regex)){
      // if we've already found at least one title, search the first part of the chunk for any links
      if (current_title != ""){
        find_links(title_match.prefix(), current_title, links);
      }

      // overwrite current_title with the new one
      current_title = title_match[1].str();
      // initilize the new title's spot in the links map with an empty set
      links[current_title] = std::set<std::string>();

      printf("title %lu: %s\n", links.size(), current_title.c_str());
      //std::cout << title_match[0] << std::endl;

      // set the chunk_string to be everything after the title
      chunk_string = title_match.suffix();
    }
    // do one last search through the remainder of the chunk for any links
    if (current_title != ""){
      find_links(chunk_string, current_title, links);
    }
    offset += chunk_size;
  }

  //output the contents of the links map after parsing
  std::cout << links.size() << std::endl;
  for (const auto &key : links) {
    std::cout << key.first << "  " << key.second.size() << std::endl;
    /*for (const auto &val: key.second){
      std::cout << "    " << val << std::endl;
    }*/
  }

}

void find_links(std::string section, std::string current_title, LinkMap &links){
  //links[current_title].push_back("test");
  //std::cout << section << std::endl;
  boost::regex link_regex("\\[\\[([^\\[\\]]*)\\]\\]");
  boost::smatch link_match;
  while (boost::regex_search(section, link_match, link_regex)){
    boost::ssub_match sub_match = link_match[1];
    std::string piece = sub_match.str();
    //std::cout << piece << '\n';
    links[current_title].insert(piece);
    //std::cout << current_title << " > " << piece << std::endl;
    section = link_match.suffix().str();
  }
}

void regex_test(){

  std::string s ("this <title>abc test def</title> has a submarine as <title>another title</title> subsequence");
  boost::smatch m;
  boost::regex e ("<title[^>]*>([^<]+)</title>");   // matches words beginning by "sub"

  std::cout << "The following matches and submatches were found:" << std::endl;

  while (boost::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << "\n";
    std::cout << std::endl;
    s = m.suffix().str();
  }

}
<commit_msg>starting to remove regex<commit_after>#include <stdio.h>
#include <mpi.h>
#include <boost/regex.hpp>
#include <regex>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>

typedef std::map<std::string, std::set<std::string>> LinkMap;

int g_world_size;
int g_my_rank;
std::string g_filename = "enwiki-20160305-pages-articles.xml";

void parse_file(MPI_File *infile);
void regex_test();
void find_links(std::string section, std::string current_title, LinkMap &links);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  MPI_Init(NULL, NULL);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_my_rank);

  // Print off a hello world message
  printf("Hello world from rank %d out of %d processors\n", g_my_rank, g_world_size);

  // Open up the wikipedia xml file
  MPI_File infile;
  MPI_File_open(MPI_COMM_WORLD, (char *)g_filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);

  // Parse the file
  //parse_file(&infile);

  if (g_my_rank == 0){
    regex_test();
  }

  // Close the file
  MPI_File_close(&infile);

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

// Parse the input file: pull out page titles and any links from a page to another
void parse_file(MPI_File *infile){
  //get file size
  MPI_Offset filesize;
  MPI_File_get_size(*infile, &filesize);

  // the size of each chunk that will be read in at a time
  //  TODO: find an optimal setting for this so that we aren't producing too many read reqeusts
  int chunk_size = 1000;
  //get size of the chunk this rank will handle
  long long int max_size = filesize / g_world_size;
  // where this rank will stop reading the file (aka where the next rank will start reading)
  long long int stopping_point = max_size * (g_my_rank + 1);

  //get the start point for this rank in the file:
  //    subtract chunk_size from the 'logical' start point to make sure
  //    that each node has a title for the links that it finds
  MPI_Offset offset = std::max(max_size * g_my_rank, max_size * g_my_rank - chunk_size);

  printf("Rank %d ==> start point: %lld\n", g_my_rank, offset);

  // the regex to find a tile in the file
  boost::regex title_regex("<title[^>]*>([^<]+)</title>");

  // declare some variables
  char * chunk;
  std::string current_title = "";
  LinkMap links;

  // keep going until the offset is in the next ranks group
  while (offset < stopping_point && links.size() < 100){
    // allocate a chunk to read in from the file
    chunk = (char *)malloc( (chunk_size + 1)*sizeof(char));
    // read it in
    MPI_File_read_at(*infile, offset, chunk, chunk_size, MPI_CHAR, MPI_STATUS_IGNORE);
    // end the string
    chunk[chunk_size] = '\0';
    // make it a c++ string for convenience
    std::string chunk_string(chunk);
    // free the allocated space
    free(chunk);
    //std::cout << "reading" << std::endl;
    //std::cout << chunk_string << std::endl;
    boost::smatch title_match;
    // keep looping while there is another title in the the current chunk
    while (boost::regex_search(chunk_string, title_match, title_regex)){
      // if we've already found at least one title, search the first part of the chunk for any links
      if (current_title != ""){
        find_links(title_match.prefix(), current_title, links);
      }

      // overwrite current_title with the new one
      current_title = title_match[1].str();
      // initilize the new title's spot in the links map with an empty set
      links[current_title] = std::set<std::string>();

      printf("title %lu: %s\n", links.size(), current_title.c_str());
      //std::cout << title_match[0] << std::endl;

      // set the chunk_string to be everything after the title
      chunk_string = title_match.suffix();
    }
    // do one last search through the remainder of the chunk for any links
    if (current_title != ""){
      find_links(chunk_string, current_title, links);
    }
    offset += chunk_size;
  }

  //output the contents of the links map after parsing
  std::cout << links.size() << std::endl;
  for (const auto &key : links) {
    std::cout << key.first << "  " << key.second.size() << std::endl;
    /*for (const auto &val: key.second){
      std::cout << "    " << val << std::endl;
    }*/
  }

}

void find_links(std::string section, std::string current_title, LinkMap &links){
  //links[current_title].push_back("test");
  //std::cout << section << std::endl;
  boost::regex link_regex("\\[\\[([^\\[\\]]*)\\]\\]");
  boost::smatch link_match;
  while (boost::regex_search(section, link_match, link_regex)){
    boost::ssub_match sub_match = link_match[1];
    std::string piece = sub_match.str();
    //std::cout << piece << '\n';
    links[current_title].insert(piece);
    //std::cout << current_title << " > " << piece << std::endl;
    section = link_match.suffix().str();
  }
}

void regex_test(){

  std::string chunk_string ("this <title>abc test def</title><title>banana</title>has a submarine as <title>another title</title> subsequence");
  /*std::cout << chunk_string << std::endl;
  std::size_t found_start = chunk_string.find("<title>");
  std::size_t found_end = chunk_string.find("</title>");
  std::string title = chunk_string.substr(found_start+7, found_end-found_start-7);
  std::cout << found_start << std::endl;
  std::cout << found_end << std::endl;
  std::cout << title << std::endl;;*/

  int found_begin, found_end;

  found_begin = chunk_string.find("<title>");
  found_end = chunk_string.find("</title>");
  while(found_begin != std::string::npos && found_end != std::string::npos){

    std::string new_title = chunk_string.substr(found_begin+7, found_end-found_begin-7);
    std::cout << "new title: " << new_title << std::endl;
    std::cout << found_begin - 1 << std::endl;
    std::string prefix = chunk_string.substr(0, std::max(0, found_begin - 1));
    std::cout << "prefix: " << prefix << std::endl;

    chunk_string = chunk_string.substr(found_end+8);
    std::cout << "new search string: " << chunk_string << std::endl;
    std::cout << std::endl;
    found_begin = chunk_string.find("<title>");
    found_end = chunk_string.find("</title>");
  }

}
<|endoftext|>


<commit_before>901729c2-ad5b-11e7-b201-ac87a332f658<commit_msg>new flies<commit_after>90965257-ad5b-11e7-b26d-ac87a332f658<|endoftext|>


<commit_before>5c7d4cf0-2748-11e6-8f61-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>5c87aec7-2748-11e6-9ff7-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream.h>
#include <conio.h>
#include "quiz.h"

void main()
{
	clrscr();

	init_ques();
	init_ui();

	cout << questions[0][1][2].q;

	getch();
}
<commit_msg>Fixed error that was to be fixed earlier<commit_after>#include <iostream.h>
#include <conio.h>
#include "quiz.h"

extern question questions[3][3][3];

void main()
{
	clrscr();

	init_ques();
	init_ui();

	getch();
}
<|endoftext|>


<commit_before>/*
*   AED - 2015
*
*   Autor: Ferreyra, Maximiliano Gastn.
*
*   Legajjo: 155911-4.
*
*   Fecha: 20150411
*/

#include <iostream>

using namespace std;

int main(){

    /*
    * Declaramos variables que vamos a utilizar durante el programa.
    */

    int num1 = 37;
    int num2 = 4;

    float num3 = 35.7;
    float num4 = 9.4;

    double num5 = 38.99;
    double num6 = 21.65;

cout << "===============================================================================\n" << endl;
cout << "|                          Trabajo Practico No 1 AED                           |" << endl;
cout << "|                 \"Tipos de Datos y sus Operaciones Basicas\"                   |" << endl;
cout << "|           Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4           |" << endl;
cout << "===============================================================================" << endl;

cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl;

// Tipo de datos INT

cout << "Tipo de dato: Int" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num1 + num2): " << num1 + num2 << endl;
cout << "Resta (num1 - num2): " << num1 - num2 << endl;
cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl;
cout << "Division (num1 / num2): " << num1 / num2 << endl;
cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl;

// Tipo de datos Float

cout << "Tipo de dato: Float" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num3 + num4): " << num3 + num4 << endl;
cout << "Resta (num3 - num4): " << num3 - num4 << endl;
cout << "Multiplicacion (num3 * num4): " << num3 * num4 << endl;
cout << "Division (num3 / num4): " << num3 / num4 << endl;
// No se puede obtener un resto de una divisin de datos del tipo Float.

// Tipo de datos Double

cout << "Tipo de dato: Double" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num5 + num6): " << num5 + num6 << endl;
cout << "Resta (num5 - num6): " << num5 - num6 << endl;
cout << "Multiplicacion (num5 * num6): " << num5 * num6 << endl;
cout << "Division (num5 / num6): " << num5 / num6 << endl;
// No se puede obtener un resto de una divisin de datos del tipo Double.

}

<commit_msg>Se elimina tipo de datos Float, ya que no se pedía en el enunciado<commit_after>/*
*   AED - 2015
*
*   Autor: Ferreyra, Maximiliano Gastn.
*
*   Legajjo: 155911-4.
*
*   Fecha: 20150411
*/

#include <iostream>

using namespace std;

int main(){

    /*
    * Declaramos variables que vamos a utilizar durante el programa.
    */

    int num1 = 37;
    int num2 = 4;

    float num3 = 35.7;
    float num4 = 9.4;

    double num5 = 38.99;
    double num6 = 21.65;

cout << "===============================================================================\n" << endl;
cout << "|                          Trabajo Practico No 1 AED                           |" << endl;
cout << "|                 \"Tipos de Datos y sus Operaciones Basicas\"                   |" << endl;
cout << "|           Alumno: Ferreyra, Maximiliano Gaston || Legajo: 155911-4           |" << endl;
cout << "===============================================================================" << endl;

cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" << endl;

// Tipo de datos INT

cout << "Tipo de dato: Int" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num1 + num2): " << num1 + num2 << endl;
cout << "Resta (num1 - num2): " << num1 - num2 << endl;
cout << "Multiplicacion (num1 * num2): " << num1 * num2 << endl;
cout << "Division (num1 / num2): " << num1 / num2 << endl;
cout << "Resto de Division Entera (num1 % num2): " << num1 % num2 << "\n" << endl;

// Tipo de datos Double

cout << "Tipo de dato: Double" << endl;
cout << "_________________\n" << endl;

cout << "Suma (num5 + num6): " << num5 + num6 << endl;
cout << "Resta (num5 - num6): " << num5 - num6 << endl;
cout << "Multiplicacion (num5 * num6): " << num5 * num6 << endl;
cout << "Division (num5 / num6): " << num5 / num6 << endl;
// No se puede obtener un resto de una divisin de datos del tipo Double.

}

<|endoftext|>


<commit_before>#include <immintrin.h>
#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
extern "C"
{
#include <stdlib.h>
}
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#else
#define alignedMalloc(size,align)	memalign(align,size)
#endif

const int ALIGN=32; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

void float2half(float* floats, short* halfs) {
    __m256 float_vector = _mm256_load_ps(floats);
	__m128i half_vector = _mm256_cvtps_ph(float_vector, 0);
	*(__m128i*)halfs = half_vector;
}

int main()
{
	unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	short* gain  =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN));
	float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN));
	for (unsigned int i = 0;i < cSize;i++)
	{
		gainOriginal[i] = 1.0f;
	}
	for(unsigned int i = 0;i < cSize/8;i++)
	{
		float2half(&gainOriginal[i*8], &gain[i*8]);
	}
	for (unsigned int i = 0; i < cSize; i++)
	{
		if ((i & 7) == 0)
		{
			std::cout << std::dec << std::setfill(' ') << std::setw(5) << i;
		}
		std::cout  << " 0x" << std::hex << gain[i];
		if ((i & 7) == 7)
		{
			std::cout << std::endl;
		}
	}
	return 0;
}
<commit_msg>check compiler more strictly   * only gcc and Visual Studio is accepted to compile this source<commit_after>#include <immintrin.h>
#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
extern "C"
{
#include <stdlib.h>
}
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#elif defined (__GNUC__)
#define alignedMalloc(size,align)	memalign(align,size)
#endif

const int ALIGN=32; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

void float2half(float* floats, short* halfs) {
    __m256 float_vector = _mm256_load_ps(floats);
	__m128i half_vector = _mm256_cvtps_ph(float_vector, 0);
	*(__m128i*)halfs = half_vector;
}

int main()
{
	unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	short* gain  =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN));
	float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN));
	for (unsigned int i = 0;i < cSize;i++)
	{
		gainOriginal[i] = 1.0f;
	}
	for(unsigned int i = 0;i < cSize/8;i++)
	{
		float2half(&gainOriginal[i*8], &gain[i*8]);
	}
	for (unsigned int i = 0; i < cSize; i++)
	{
		if ((i & 7) == 0)
		{
			std::cout << std::dec << std::setfill(' ') << std::setw(5) << i;
		}
		std::cout  << " 0x" << std::hex << gain[i];
		if ((i & 7) == 7)
		{
			std::cout << std::endl;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

typedef union {
    size_t st;
    float f;
} ieee754Union;

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

	if (argc < 2) {
		cerr << "Please supply a float as the first argument." << endl;
        return EXIT_FAILURE;
	}

    ieee754Union u;

    if(sscanf(argv[1], "%f", &u.f) == 0) {
        cerr << "Please supply a float as the first argument." << endl;
        return EXIT_FAILURE;
    }

    string bitString = bitset<32>(u.st).to_string().insert(9, ":").insert(1, ":");

    cout << argv[1] << " (base 10 argument)" << endl;
    cout << u.f << " (base 10 internal float)" << endl;
    cout << hex << (((1 << 31) - 1) & u.st) << " (ieee754 hexadecimal)" << endl;
    cout << bitString << " (ieee754 sign:exponent:mantisa)" << endl;

    return EXIT_SUCCESS;
}<commit_msg>mantisa -> mantissa<commit_after>#include <iostream>

using namespace std;

typedef union {
    size_t st;
    float f;
} ieee754Union;

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

	if (argc < 2) {
		cerr << "Please supply a float as the first argument." << endl;
        return EXIT_FAILURE;
	}

    ieee754Union u;

    if(sscanf(argv[1], "%f", &u.f) == 0) {
        cerr << "Please supply a float as the first argument." << endl;
        return EXIT_FAILURE;
    }

    string bitString = bitset<32>(u.st).to_string().insert(9, ":").insert(1, ":");

    cout << argv[1] << " (base 10 argument)" << endl;
    cout << u.f << " (base 10 internal float)" << endl;
    cout << hex << (((1 << 31) - 1) & u.st) << " (ieee754 hexadecimal)" << endl;
    cout << bitString << " (ieee754 sign:exponent:mantissa)" << endl;

    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>#include <omp.h>

#include "evaluate_circuit.h"

// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
//            grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \
//       ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
  // Reading input.
  if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
  int current_arg = 1;
  qflex::QflexInput input;
  input.I = atoi(argv[current_arg++]);
  input.J = atoi(argv[current_arg++]);
  input.K = atoi(argv[current_arg++]);
  input.fidelity = atof(argv[current_arg++]);

  // Creating streams for input files.
  auto circuit_data = std::ifstream(std::string(argv[current_arg++]));
  if (!circuit_data.good()) {
      std::cout << "Cannot open circuit data file: " << std::string(argv[current_arg++]) << std::endl;
      assert(circuit_data.good());
  }
  input.circuit_data = &circuit_data;
  auto ordering_data = std::ifstream(std::string(argv[current_arg++]));
  if (!ordering_data.good()) {
      std::cout << "Cannot open ordering data file: " << std::string(argv[current_arg++]) << std::endl;
      assert(ordering_data.good());
  }
  input.ordering_data = &ordering_data;
  auto grid_data = std::ifstream(std::string(argv[current_arg++]));
  if (!grid_data.good()) {
      std::cout << "Cannot open grid data file: " << std::string(argv[current_arg++]) << std::endl;
      assert(grid_data.good());
  }
  input.grid_data = &grid_data;

  // Setting initial and final circuit states.
  if (argc > current_arg) {
    input.initial_state = std::string(argv[current_arg++]);
  }
  if (argc > current_arg) {
    input.final_state_A = std::string(argv[current_arg++]);
  }

  // Evaluating circuit.
  std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
      qflex::EvaluateCircuit(&input);

  // Printing output.
  for (int c = 0; c < amplitudes.size(); ++c) {
    const auto& state = amplitudes[c].first;
    const auto& amplitude = amplitudes[c].second;
    std::cout << input.initial_state << " --> " << state << ": "
              << std::real(amplitude) << " " << std::imag(amplitude)
              << std::endl;
  }
  return 0;
}
<commit_msg>small fixes<commit_after>#include <omp.h>

#include "evaluate_circuit.h"

// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
//            grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \
//       ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
  // Reading input.
  if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
  int current_arg = 1;
  qflex::QflexInput input;
  input.I = atoi(argv[current_arg++]);
  input.J = atoi(argv[current_arg++]);
  input.K = atoi(argv[current_arg++]);
  input.fidelity = atof(argv[current_arg++]);

  // Creating streams for input files.
  auto circuit_data = std::ifstream(std::string(argv[current_arg++]));
  if (!circuit_data.good()) {
      std::cout << "Cannot open circuit data file: " << std::string(argv[current_arg]) << std::endl;
      assert(circuit_data.good());
  }
  input.circuit_data = &circuit_data;
  auto ordering_data = std::ifstream(std::string(argv[current_arg++]));
  if (!ordering_data.good()) {
      std::cout << "Cannot open ordering data file: " << std::string(argv[current_arg]) << std::endl;
      assert(ordering_data.good());
  }
  input.ordering_data = &ordering_data;
  auto grid_data = std::ifstream(std::string(argv[current_arg++]));
  if (!grid_data.good()) {
      std::cout << "Cannot open grid data file: " << std::string(argv[current_arg]) << std::endl;
      assert(grid_data.good());
  }
  input.grid_data = &grid_data;

  // Setting initial and final circuit states.
  if (argc > current_arg) {
    input.initial_state = std::string(argv[current_arg++]);
  }
  if (argc > current_arg) {
    input.final_state_A = std::string(argv[current_arg++]);
  }

  // Evaluating circuit.
  std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
      qflex::EvaluateCircuit(&input);

  // Printing output.
  for (int c = 0; c < amplitudes.size(); ++c) {
    const auto& state = amplitudes[c].first;
    const auto& amplitude = amplitudes[c].second;
    std::cout << input.initial_state << " --> " << state << ": "
              << std::real(amplitude) << " " << std::imag(amplitude)
              << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

/*

    f   G   H
  g   b   C   I
h    c  a  D   J
  i   d   e   K
    j   k   l

    a
    b-B
    b+B
    c-C
    c+C
    ...

    Instead of sampling b, B, c, C... I sample b-B, b+B, c-C, c+C... to make the nn insensitive to direction.

*/

class Pet{

    protected:

    const int numLayers = 4; // Arbitrary
    const int layerSize = 10; // Arbitrary
    const int numInputPositions = 19; // All positions within 2 steps.
    const int numInputChannels = 6; // Other pets rgb, Scent rgb
    const int numOutputDirections = 6; // All directions
    const int numDirectionalOutputChannels = 3; // Move, Fight, Mate
    const int numGeneralOutputChannels = 3; // Null, Scent

    const int numInputNeurons = numInputPositions*numInputChannels;
    const int numProcessingNeurons = numLayers*layerSize;
    const int numOutputNeurons = numOutputDirections*numDirectionalOutputChannels + numGeneralOutputChannels;

    const int numInputConnections = numInputPositions*numInputChannels*layerSize;
    const int numProcessingConnections = (numLayers-1)*layerSize*layerSize;
    const int numOutputConnections = (numOutputDirections*numDirectionalOutputChannels + numGeneralOutputChannels)*layerSize;

    float inputNeurons[numInputNeurons];
    float processingNeurons[numProcessingNeurons];
    float outputNeurons[numOutputNeurons];

    float inputConnections[numinputConnections];
    float processingConnections[numProcessingConnections];
    float outputConnections[numOutputConnections];

    void collectInput(WorldCell environment[]){
        for(int i=0; i<)
    }
    void processInput(){
        // First layer takes input directly from input neurons.
        for(int write=0; write<layerSize; ++write){
            processingNeurons[write] = 0;
            for(int read=0; read<numInputNeurons; ++read)
                processingNeurons[write] = inputNeurons[read] * inputConnections[write*layerSize + read];
        }

        // Propagate through the rest of the processing layers.
        for(int layer=1; layer<numLayers; ++layer)
            for(int write=0; write<layerSize; ++write){
                processingNeurons[layer*layerSize + write] = 0;
                for(int read=0; read<layerSize; ++read)
                    processingNeurons[layer*layerSize + write] += processingNeurons[(layer-1)*layerSize + read] * processingConnections[write*layerSize + read];
            }

        // Output neurons read from the last layer.
        for(int write=0; write<numOutputNeurons; ++write){
            outputNeurons[write] = 0;
            for(int read=0; read<layerSize; ++read)
                outputNeurons[write] = processingNeurons[(numLayers-1)*layerSize + read] * outputConnections[read*layerSize + write];
        }
    }
    void respondToInput(){
        for(int i=0; i<)
    }

    const float breedingEnergy = 0.2;

    int direction;
    int position;
    float energy;
    float color[3];

    public:

    void live(){
        collectInput();
        processInput();
        respondToInput();
    }

}

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

<commit_msg>Begun implementing the movement.<commit_after>#include <iostream>

using namespace std;

/*

    f   G   H
  g   b   C   I
h    c  a  D   J
  i   d   e   K
    j   k   l

    a
    b-B
    b+B
    c-C
    c+C
    ...

    Instead of sampling b, B, c, C... I sample b-B, b+B, c-C, c+C... to make the nn insensitive to direction.
    HANDLED BY Environment::Sample.

*/

enum Directions {
    none,
    forward,
    forwardLeft,
    forwardRight,
    backward,
    backwardLeft,
    backwardRight,
    numDirections
};

class Pet{

    protected:

    const int numLayers = 1; // Arbitrary
    const int layerSize = 4; // Arbitrary
    const int numInputPositions = 7; // All positions within 1 steps.
    const int numInputChannels = 3; // Other pets mate-abillity, nutricient, danger.
    const int numOutputPositions = 7; // All positions within 1 steps.
    const int numGeneralOutputs = 2; // Mate, scent.

    const int numInputNeurons = numInputPositions*numInputChannels;
    const int numProcessingNeurons = numLayers*layerSize;
    const int numOutputNeurons = numOutputPositions + numGeneralOutputs;

    const int numInputConnections = numInputPositions*numInputChannels*layerSize;
    const int numProcessingConnections = (numLayers-1)*layerSize*layerSize;
    const int numOutputConnections = (numOutputPositions + numGeneralOutputs)*layerSize;

    float inputNeurons[numInputNeurons];
    float processingNeurons[numProcessingNeurons];
    float outputNeurons[numOutputNeurons];

    float inputConnections[numinputConnections];
    float processingConnections[numProcessingConnections];
    float outputConnections[numOutputConnections];

    Environment& environment;
    int position;
    Direction facingDirection;

    void collectInput(){

        for(Channels channel = 0; i<numChannels; ++i)
            for(Directions direction = 0; i<numDirections; ++i)
                inputNeurons[channel*numDirections + direction] = environment.sample(position, facingDirection, direction, channel);
    }

    void processInput(){
        // First layer takes input directly from input neurons.
        for(int write=0; write<layerSize; ++write){
            processingNeurons[write] = 0;
            for(int read=0; read<numInputNeurons; ++read)
                processingNeurons[write] = inputNeurons[read] * inputConnections[write*layerSize + read];
        }

        // Propagate through the rest of the processing layers.
        for(int layer=1; layer<numLayers; ++layer)
            for(int write=0; write<layerSize; ++write){
                processingNeurons[layer*layerSize + write] = 0;
                for(int read=0; read<layerSize; ++read)
                    processingNeurons[layer*layerSize + write] += processingNeurons[(layer-1)*layerSize + read] * processingConnections[write*layerSize + read];
            }

        // Output neurons read from the last layer.
        for(int write=0; write<numOutputNeurons; ++write){
            outputNeurons[write] = 0;
            for(int read=0; read<layerSize; ++read)
                outputNeurons[write] = processingNeurons[(numLayers-1)*layerSize + read] * outputConnections[read*layerSize + write];
        }
    }
    void respondToInput(){
        for(int i=0; i<)
    }

    const float breedingEnergy = 0.2;

    int direction;
    int position;
    float energy;
    float color[3];

    public:

    void live(){
        collectInput();
        processInput();
        respondToInput();
    }

}

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

<|endoftext|>


<commit_before>e7889151-ad58-11e7-b703-ac87a332f658<commit_msg>Typical bobby<commit_after>e7fbefb0-ad58-11e7-96d1-ac87a332f658<|endoftext|>


<commit_before>8fd2dfe8-4b02-11e5-80a9-28cfe9171a43<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>8fdfbca3-4b02-11e5-8249-28cfe9171a43<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2008  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "znc.h"
#include <getopt.h>

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "no-color",			no_argument,	0,	'n' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

static void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-n, --no-color     Don't use escape sequences in the output");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

static void die(int sig) {
	signal(SIGSEGV, SIG_DFL);
	signal(SIGABRT, SIG_DFL);
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

static void rehash(int sig) {
	CZNC::Get().SetNeedRehash(true);
}

int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));
	CUtils::SetStdoutIsTTY(isatty(1));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvncsped:", g_LongOpts, &iOptIndex)) != -1) {
#else
	while ((iArg = getopt_long(argc, argv, "hvncsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			    GenerateHelp(argv[0]);
			    return 0;
		case 'v':
			    cout << CZNC::GetTag() << endl;
			    return 0;
		case 'n':
			    CUtils::SetStdoutIsTTY(false);
			    break;
		case 'c':
			    bMakeConf = true;
			    break;
		case 's':
			    bMakePass = true;
			    break;
#ifdef HAVE_LIBSSL
		case 'p':
			    bMakePem = true;
			    break;
		case 'e':
			    bEncPem = true;
			    break;
#endif /* HAVE_LIBSSL */
		case 'd':
			    sDataDir = CString(optarg);
			    break;
		case '?':
		default:
			    GenerateHelp(argv[0]);
			    return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	if (bMakeConf) {
		CZNC& ZNC = CZNC::Get();
		ZNC.InitDirs("", sDataDir);
		if (ZNC.WriteNewConfig(sConfig)) {
			char const* args[5];

			if (argc > 2) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = argv[optind];
					args[4] = NULL;
				} else {
					args[1] = argv[optind];
					args[2] = NULL;
				}
			} else if (argc > 1) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = NULL;
				} else {
					args[1] = NULL;
				}
			} else {
				CUtils::PrintError("Unable to launch znc [Try manually restarting]");
				return 1;
			}

			if ((chdir(ZNC.GetCurPath().c_str()) == -1)
					|| (execv(*argv, (char *const*)args) == -1)) {
				CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]");
				return 1;
			}
		}

		return 0;
	}

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		CZNC* pZNC = &CZNC::Get();
		pZNC->InitDirs("", sDataDir);
		pZNC->WritePemFile(bEncPem);

		delete pZNC;
		return 0;
	}
	if (bEncPem && !bMakePem) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		return 1;
	}

#endif /* HAVE_LIBSSL */
	if (bMakePass) {
		CString sHash = CUtils::GetHashPass();
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = " + sHash + " -");

		return 0;
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

#ifdef _DEBUG
	int iPid = getpid();
	CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");

	pZNC->WritePidFile(iPid);
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		exit(1);
	}

	if (iPid > 0) {
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag(false));
		exit(0);
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);

	CUtils::SetStdoutIsTTY(false);
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	sa.sa_handler = rehash;
	sigaction(SIGHUP,  &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		// EX_Shutdown is thrown to exit
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<commit_msg>Call setsid() after forking<commit_after>/*
 * Copyright (C) 2004-2008  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "znc.h"
#include <getopt.h>

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "no-color",			no_argument,	0,	'n' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

static void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-n, --no-color     Don't use escape sequences in the output");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

static void die(int sig) {
	signal(SIGSEGV, SIG_DFL);
	signal(SIGABRT, SIG_DFL);
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

static void rehash(int sig) {
	CZNC::Get().SetNeedRehash(true);
}

int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));
	CUtils::SetStdoutIsTTY(isatty(1));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvncsped:", g_LongOpts, &iOptIndex)) != -1) {
#else
	while ((iArg = getopt_long(argc, argv, "hvncsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			    GenerateHelp(argv[0]);
			    return 0;
		case 'v':
			    cout << CZNC::GetTag() << endl;
			    return 0;
		case 'n':
			    CUtils::SetStdoutIsTTY(false);
			    break;
		case 'c':
			    bMakeConf = true;
			    break;
		case 's':
			    bMakePass = true;
			    break;
#ifdef HAVE_LIBSSL
		case 'p':
			    bMakePem = true;
			    break;
		case 'e':
			    bEncPem = true;
			    break;
#endif /* HAVE_LIBSSL */
		case 'd':
			    sDataDir = CString(optarg);
			    break;
		case '?':
		default:
			    GenerateHelp(argv[0]);
			    return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	if (bMakeConf) {
		CZNC& ZNC = CZNC::Get();
		ZNC.InitDirs("", sDataDir);
		if (ZNC.WriteNewConfig(sConfig)) {
			char const* args[5];

			if (argc > 2) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = argv[optind];
					args[4] = NULL;
				} else {
					args[1] = argv[optind];
					args[2] = NULL;
				}
			} else if (argc > 1) {
				args[0] = argv[0];
				if (!sDataDir.empty()) {
					args[1] = "--datadir";
					args[2] = strdup(sDataDir.c_str());
					args[3] = NULL;
				} else {
					args[1] = NULL;
				}
			} else {
				CUtils::PrintError("Unable to launch znc [Try manually restarting]");
				return 1;
			}

			if ((chdir(ZNC.GetCurPath().c_str()) == -1)
					|| (execv(*argv, (char *const*)args) == -1)) {
				CUtils::PrintError("Unable to launch znc [" + CString(strerror(errno)) + "]");
				return 1;
			}
		}

		return 0;
	}

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		CZNC* pZNC = &CZNC::Get();
		pZNC->InitDirs("", sDataDir);
		pZNC->WritePemFile(bEncPem);

		delete pZNC;
		return 0;
	}
	if (bEncPem && !bMakePem) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		return 1;
	}

#endif /* HAVE_LIBSSL */
	if (bMakePass) {
		CString sHash = CUtils::GetHashPass();
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = " + sHash + " -");

		return 0;
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

#ifdef _DEBUG
	int iPid = getpid();
	CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");

	pZNC->WritePidFile(iPid);
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		exit(1);
	}

	if (iPid > 0) {
		// We are the parent. We are done and will go to bed.
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag(false));
		exit(0);
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);

	CUtils::SetStdoutIsTTY(false);

	// We are the child. There is no way we can be a process group
	// leader, thus setsid() must succeed.
	setsid();
	// Now we are in our own process group and session (no controlling
	// terminal). We are independent!
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	sa.sa_handler = rehash;
	sigaction(SIGHUP,  &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		// EX_Shutdown is thrown to exit
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: 8 Oct 2016
 *      Author: muttley
 */

#include <iostream>
#include <gtkmm.h>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <regex>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#include "VDF.h"
#include "Filesystem.h"
#include "Settings.h"
#include "Utils.h"
#include "Logger.h"

#include "MainWindow.h"

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

using namespace std;

int main(int argc, char *argv[])
{
    //Checking parameters for --verbose or -v
    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0)
            LogLevel = 0;
    }

    LOG(1, "ArmA 3 Unix Launcher started");

    //~/.config/a3unixlauncher
    if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory))
    {
        bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory);
        if (!result)
            return 1;
    }

    if (!Filesystem::FileExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename))
    {
        Settings::Save(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory
                + Filesystem::LauncherSettingsFilename);
    }

    Settings::Load(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename);

    if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
        Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall);

    if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND)
        Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods);

    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--purge") == 0)
        {
            if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND)
            {
                string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop);
                string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom);
                system(removeWorkshop.c_str());
                system(removeCustom.c_str());
            }
            string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\"";
            system(removeConfig.c_str());

            LOG(1, "Purged config file, !workshop, !custom directories");
            exit(0);
        }
    }

    //Dirty fix to Gtk::Application trying to parse arguments on its own
    argc = 0;
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher");

#ifdef __APPLE__
    //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher
    char* path = new char[4096];
    unsigned int pathLength = 4095;
    _NSGetExecutablePath(path, &pathLength);
    string currentPath = path;
    delete[] path;

    string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade";
#else
    string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
        MainFormPath = "MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
    {
        string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe");
        MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade";
    }
#endif

    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath);

    cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl
         << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl;

    //if autodetection fails
    while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
    {
        string Message = string("Launcher couldn't detect ArmA 3 installation directory") +
                "\nClick 'Yes' to select appropriate directory" +
                "\nClick 'No' to close the program";

        Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO);
        int result = msg.run();

        if (result == Gtk::RESPONSE_NO)
            exit(2);

        Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
        fcDialog.add_button("_Open", 1);
        result = fcDialog.run();
        if (result == 1)
        {
            string currentFolder = fcDialog.get_current_folder();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386"))
                Settings::ArmaPath = currentFolder;
            currentFolder = fcDialog.get_filename();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386"))
                Settings::ArmaPath = currentFolder;

            if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
            {
                string Message2 = string("Selected directory seems incorrect") +
                                "\n" + currentFolder + "/arma3.i386 doesn't exist";

                Gtk::MessageDialog msg2(Message2);
                msg2.run();
            }
        }
    }

    MainWindow* mainWindow = NULL;

    builder->get_widget_derived("MainForm", mainWindow);

    if (mainWindow)
        app->run(*mainWindow);

    delete mainWindow;

    return 0;
}
<commit_msg>Quick & dirty fix for ArmA 3 detection on Mac OS X<commit_after>/*
 * main.cpp
 *
 *  Created on: 8 Oct 2016
 *      Author: muttley
 */

#include <iostream>
#include <gtkmm.h>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <regex>

#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#include "VDF.h"
#include "Filesystem.h"
#include "Settings.h"
#include "Utils.h"
#include "Logger.h"

#include "MainWindow.h"

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

using namespace std;

int main(int argc, char *argv[])
{
    //Checking parameters for --verbose or -v
    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0)
            LogLevel = 0;
    }

    LOG(1, "ArmA 3 Unix Launcher started");

    //~/.config/a3unixlauncher
    if (!Filesystem::DirectoryExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory))
    {
        bool result = Filesystem::CreateDirectory(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory);
        if (!result)
            return 1;
    }

    if (!Filesystem::FileExists(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename))
    {
        Settings::Save(Filesystem::HomeDirectory
                + Filesystem::LauncherSettingsDirectory
                + Filesystem::LauncherSettingsFilename);
    }

    Settings::Load(Filesystem::HomeDirectory
            + Filesystem::LauncherSettingsDirectory
            + Filesystem::LauncherSettingsFilename);

    if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
        Settings::ArmaPath = Filesystem::GetDirectory(DirectoryToFind::ArmaInstall);

    if (Settings::WorkshopPath == Filesystem::DIR_NOT_FOUND)
        Settings::WorkshopPath = Filesystem::GetDirectory(DirectoryToFind::WorkshopMods);

    for (int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i], "--purge") == 0)
        {
            if (Settings::ArmaPath != Filesystem::DIR_NOT_FOUND)
            {
                string removeWorkshop = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirWorkshop);
                string removeCustom = "rm -rf " + Utils::BashAdaptPath(Settings::ArmaPath + Filesystem::ArmaDirCustom);
                system(removeWorkshop.c_str());
                system(removeCustom.c_str());
            }
            string removeConfig = "rm -rf \"" + Filesystem::HomeDirectory + Filesystem::LauncherSettingsDirectory + "\"";
            system(removeConfig.c_str());

            LOG(1, "Purged config file, !workshop, !custom directories");
            exit(0);
        }
    }

    //Dirty fix to Gtk::Application trying to parse arguments on its own
    argc = 0;
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "muttley.a3unixlauncher");

#ifdef __APPLE__
    //apple path is like: /Applications/arma3-unix-launcher.app/Contents/MacOS/./arma3-unix-launcher
    char* path = new char[4096];
    unsigned int pathLength = 4095;
    _NSGetExecutablePath(path, &pathLength);
    string currentPath = path;
    delete[] path;

    string MainFormPath = Utils::RemoveLastElement(currentPath, false) + "MainForm.glade";
#else
    string MainFormPath = "/usr/share/arma3-unix-launcher/MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
        MainFormPath = "MainForm.glade";
    if (!Filesystem::FileExists(MainFormPath))
    {
        string binaryPath = Filesystem::GetSymlinkTarget("/proc/" + to_string(getpid()) + "/exe");
        MainFormPath = Utils::RemoveLastElement(binaryPath, false, 2) + "MainForm.glade";
    }
#endif

    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(MainFormPath);

    cout << "GTK+ version: " << gtk_major_version << "." << gtk_minor_version << "." << gtk_micro_version << endl
         << "Glib version: " << glib_major_version << "." << glib_minor_version << "." << glib_micro_version << endl;

    //if autodetection fails
    while (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
    {
        string Message = string("Launcher couldn't detect ArmA 3 installation directory") +
                "\nClick 'Yes' to select appropriate directory" +
                "\nClick 'No' to close the program";

        Gtk::MessageDialog msg(Message, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_YES_NO);
        int result = msg.run();

        if (result == Gtk::RESPONSE_NO)
            exit(2);

        Gtk::FileChooserDialog fcDialog("Select ArmA 3 install directory", Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
        fcDialog.add_button("_Open", 1);
        result = fcDialog.run();
        if (result == 1)
        {
            string currentFolder = fcDialog.get_current_folder();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;
            currentFolder = fcDialog.get_filename();
            if (Filesystem::FileExists(currentFolder + "/arma3.i386")
                    || Filesystem::FileExists(currentFolder + "/ArmA3.app")
                    || Filesystem::DirectoryExists(currentFolder + "/ArmA3.app"))
                Settings::ArmaPath = currentFolder;

            if (Settings::ArmaPath == Filesystem::DIR_NOT_FOUND)
            {
                string Message2 = string("Selected directory seems incorrect") +
                                "\n" + currentFolder + "/arma3.i386 doesn't exist"
                                 "\n" + currentFolder + "/ArmA3.app doesn't exist";

                Gtk::MessageDialog msg2(Message2);
                msg2.run();
            }
        }
    }

    MainWindow* mainWindow = NULL;

    builder->get_widget_derived("MainForm", mainWindow);

    if (mainWindow)
        app->run(*mainWindow);

    delete mainWindow;

    return 0;
}
<|endoftext|>


<commit_before>f278e24c-2747-11e6-b3cd-e0f84713e7b8<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>f290b245-2747-11e6-b5ed-e0f84713e7b8<|endoftext|>


<commit_before>993e835c-4b02-11e5-95bd-28cfe9171a43<commit_msg>GOD DAMNED IT!<commit_after>994be09c-4b02-11e5-bacd-28cfe9171a43<|endoftext|>


<commit_before>65e877b3-2749-11e6-a9f5-e0f84713e7b8<commit_msg>For ashok to integrate at some point<commit_after>65f67dc0-2749-11e6-b097-e0f84713e7b8<|endoftext|>


<commit_before>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>
#include <cudpp.h>
#include <cutil.h>

#include "cuda_test.h"
#include "cpu_test.h"
#include "cuda_defs.h"

#define DEBUG 1
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

#define TIME 1
#define LAT 190
#define LON 384
#define VARNAME "TMP_2maboveground"
#define DMIN 205
#define DMAX 320
#define MONTHS 12

void unpack_data(char *filename, float *data_in, char *varname);
int main(int argc, char *argv[]){

   int dmin, dmax, nSamples, dim;
   float *dataT=NULL;

   if (!DEBUG){
      int start = 1985;
      int end = 1986;
      //int end = 2009;

      int tsamples = ((end-start) + 1)*MONTHS;
      dim = 9; //num forecasts
      dmin = DMIN;
      dmax = DMAX;
      nSamples = tsamples * LAT * LON;
      int foffset, yoffset, moffset;

      char filename[23];
      float *data = NULL;
      CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim);
      CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim);
      printf("%d\n", nSamples*dim);

      char ffilename[25];
      int zcount=0;
      for (int f = 1; f<=9; f++){
	 foffset = nSamples*(f-1);
	 for (int y =start; y<=end; y++){
	    yoffset = (LAT*LON*12) * (y-start);
	    for (int m = 1; m<=MONTHS; m++){
	       sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f);
	       moffset = LAT*LON*(m-1);
	       unpack_data(ffilename, (data+(foffset+yoffset+moffset)), VARNAME);

	    }

	 }
      }
      assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples));
      //Transpose
      //http://stackoverflow.com/a/16743203/1267531
      for(unsigned int n=0; n<(nSamples*dim); n++){
	 dataT[n] = data[nSamples*(n%dim) +(n/dim)];
      }

      CPUFREE(data);
   }else{
      //Fake data, rows of all 0s...4s
      char *sfilename = "../data/simple.nc";
      char *varname = "data";
      dmin=0;
      dmax=4;
      nSamples = 100;
      dim = 5;
      CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim);
      unpack_data(sfilename, dataT, varname);
      /**
      for (int i=0; i<nSamples; i++){
	 for(int j=0; j<dim; j++){
	    printf("%1.0f ",dataT[(i*dim)+j]);
	 }
	 printf("\n");
      }**/
   }

   /*  Allocate enough space.. */
   unsigned int LSH = 0;
   unsigned int BS = 0;
   unsigned int RESULT = 0;
   unsigned int KNN = 0;
   if (argc>1){LSH = atoi(argv[1]);}
   if (argc>2){BS = atoi(argv[2]);}
   if (argc>3){RESULT = atoi(argv[3]);}
   if (argc>4){KNN = atoi(argv[4]);}

   testall(dataT, nSamples, dim, dmin, dmax, LSH, BS, RESULT);
   if(KNN){
      test_kdtree(dataT, nSamples, dim);
   }

   CPUFREE(dataT);
   return 0;
}

void unpack_data(char *filename, float *data_in, char *varname){
	//netCDF fileit and data var
	int ncid, varid;

	//loop inds and error_handling
	int ld, la, ln, retval;

	/** Open the file. NC_NOWRITE tells netCDF
  	we want read-only access  to the file.*/
  	if((retval = nc_open(filename, NC_NOWRITE, &ncid)))
		ERR(retval);

	/** Get the varid of the data variable,
 	    based on its name. */
   	if ((retval = nc_inq_varid(ncid, varname, &varid)))
		ERR(retval);

	/* Read the data. */
   	if ((retval = nc_get_var_float(ncid, varid, data_in)))
      		ERR(retval);

   	/* Close the file, freeing all resources. */
   	if ((retval = nc_close(ncid)))
     		 ERR(retval);

   	//printf("*** SUCCESS reading %s!\n", filename);
}

<commit_msg>removed char filename[32] 'cause unused<commit_after>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>
#include <cudpp.h>
#include <cutil.h>

#include "cuda_test.h"
#include "cpu_test.h"
#include "cuda_defs.h"

#define DEBUG 1
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

#define TIME 1
#define LAT 190
#define LON 384
#define VARNAME "TMP_2maboveground"
#define DMIN 205
#define DMAX 320
#define MONTHS 12

void unpack_data(char *filename, float *data_in, char *varname);
int main(int argc, char *argv[]){

   int dmin, dmax, nSamples, dim;
   float *dataT=NULL;

   if (!DEBUG){
      int start = 1985;
      int end = 1986;
      //int end = 2009;

      int tsamples = ((end-start) + 1)*MONTHS;
      dim = 9; //num forecasts
      dmin = DMIN;
      dmax = DMAX;
      nSamples = tsamples * LAT * LON;
      int foffset, yoffset, moffset;

      float *data = NULL;
      CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim);
      CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim);
      printf("%d\n", nSamples*dim);

      char ffilename[25];
      int zcount=0;
      for (int f = 1; f<=9; f++){
	 foffset = nSamples*(f-1);
	 for (int y =start; y<=end; y++){
	    yoffset = (LAT*LON*12) * (y-start);
	    for (int m = 1; m<=MONTHS; m++){
	       sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f);
	       moffset = LAT*LON*(m-1);
	       unpack_data(ffilename, (data+(foffset+yoffset+moffset)), VARNAME);

	    }

	 }
      }
      assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples));
      //Transpose
      //http://stackoverflow.com/a/16743203/1267531
      for(unsigned int n=0; n<(nSamples*dim); n++){
	 dataT[n] = data[nSamples*(n%dim) +(n/dim)];
      }

      CPUFREE(data);
   }else{
      //Fake data, rows of all 0s...4s
      char *sfilename = "../data/simple.nc";
      char *varname = "data";
      dmin=0;
      dmax=4;
      nSamples = 100;
      dim = 5;
      CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim);
      unpack_data(sfilename, dataT, varname);
      /**
      for (int i=0; i<nSamples; i++){
	 for(int j=0; j<dim; j++){
	    printf("%1.0f ",dataT[(i*dim)+j]);
	 }
	 printf("\n");
      }**/
   }

   /*  Allocate enough space.. */
   unsigned int LSH = 0;
   unsigned int BS = 0;
   unsigned int RESULT = 0;
   unsigned int KNN = 0;
   if (argc>1){LSH = atoi(argv[1]);}
   if (argc>2){BS = atoi(argv[2]);}
   if (argc>3){RESULT = atoi(argv[3]);}
   if (argc>4){KNN = atoi(argv[4]);}

   testall(dataT, nSamples, dim, dmin, dmax, LSH, BS, RESULT);
   if(KNN){
      test_kdtree(dataT, nSamples, dim);
   }

   CPUFREE(dataT);
   return 0;
}

void unpack_data(char *filename, float *data_in, char *varname){
	//netCDF fileit and data var
	int ncid, varid;

	//loop inds and error_handling
	int ld, la, ln, retval;

	/** Open the file. NC_NOWRITE tells netCDF
  	we want read-only access  to the file.*/
  	if((retval = nc_open(filename, NC_NOWRITE, &ncid)))
		ERR(retval);

	/** Get the varid of the data variable,
 	    based on its name. */
   	if ((retval = nc_inq_varid(ncid, varname, &varid)))
		ERR(retval);

	/* Read the data. */
   	if ((retval = nc_get_var_float(ncid, varid, data_in)))
      		ERR(retval);

   	/* Close the file, freeing all resources. */
   	if ((retval = nc_close(ncid)))
     		 ERR(retval);

   	//printf("*** SUCCESS reading %s!\n", filename);
}

<|endoftext|>