<commit_before>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <X11/Xlib.h>
#include <base/contract.h>
#include <base/pointer.h>
#include <base/meta.h>
#include <utf/utf.h>
#include <utf/utfcat.h>
#include "dispatcher.h"

namespace platform { namespace xlib
{

////////////////////////////////////////

dispatcher::dispatcher( const std::shared_ptr<Display> &dpy, const std::shared_ptr<keyboard> &k, const std::shared_ptr<mouse> &m )
	: _display( dpy ), _keyboard( k ), _mouse( m )
{
	precondition( _display, "null display" );
	_atom_delete_window = XInternAtom( _display.get(), "WM_DELETE_WINDOW", True );

	_xim = XOpenIM( _display.get(), nullptr, nullptr, nullptr ); // TODO resource/class name?
	if ( !_xim )
		throw std::runtime_error( "failed to open input method" );
}

////////////////////////////////////////

dispatcher::~dispatcher( void )
{
}

////////////////////////////////////////

int dispatcher::execute( void )
{
	XFlush( _display.get() );
	_exit_code = 0;

	bool done = false;
	XEvent event;
	while ( !done )
	{
		XNextEvent( _display.get(), &event );
		switch ( event.type )
		{
			case Expose:
			{
				if ( event.xexpose.count == 0 )
				{
					auto win = _windows[event.xexpose.window];
					win->expose_event();
				}
				break;
			}

			case ConfigureNotify:
			{
				auto w = _windows[event.xconfigure.window];
				if ( w )
				{
					w->move_event( event.xconfigure.x, event.xconfigure.y );
					w->resize_event( event.xconfigure.width, event.xconfigure.height );
				}
				break;
			}

			case DestroyNotify:
			{
				auto w = _windows[event.xdestroywindow.window];
				w->closed();
				break;
			}

			case MapNotify:
			{
				auto w = _windows[event.xmap.window];
				w->shown();
				w->restored();
				break;
			}

			case UnmapNotify:
			{
				auto w = _windows[event.xunmap.window];
				if ( w )
				{
					w->hidden();
					w->minimized();
				}
				break;
			}

			case EnterNotify:
			{
				auto w = _windows[event.xcrossing.window];
				w->entered();
				break;
			}

			case LeaveNotify:
			{
				auto w = _windows[event.xcrossing.window];
				w->exited();
				break;
			}

			case KeyPress:
			{
				auto w = _windows[event.xkey.window];
				platform::scancode sc = _keyboard->get_scancode( event.xkey );
				w->key_pressed( _keyboard, sc );
				char keybuf[16];
				Status status;
				int length = Xutf8LookupString( w->input_context(), &event.xkey, keybuf, sizeof(keybuf), nullptr, &status );
				if ( length > 0 )
				{
					std::stringstream tmp( std::string( keybuf, size_t(length) ) );
					utf::iterator it( tmp, utf::UTF8 );
					while ( ++it )
					{
						if ( utf::is_graphic( *it ) )
							w->text_entered( _keyboard, *it );
					}
				}
				break;
			}

			case KeyRelease:
			{
				auto w = _windows[event.xkey.window];
				platform::scancode sc = _keyboard->get_scancode( event.xkey );
				w->key_released( _keyboard, sc );
				break;
			}

			case MappingNotify:
			{
				if ( event.xmapping.request == MappingKeyboard )
					XRefreshKeyboardMapping( &event.xmapping );
				break;
			}

			case ButtonPress:
			{
				auto w = _windows[event.xbutton.window];
				switch ( event.xbutton.button )
				{
					case 1:
					case 2:
					case 3:
						w->mouse_pressed( _mouse, { double(event.xbutton.x), double(event.xbutton.y) }, int(event.xbutton.button) );
						break;

					case 4:
						w->mouse_wheel( _mouse, 1 );
						break;

					case 5:
						w->mouse_wheel( _mouse, -1 );
						break;
				}
				break;
			}

			case ButtonRelease:
			{
				auto w = _windows[event.xbutton.window];
				switch ( event.xbutton.button )
				{
					case 1:
					case 2:
					case 3:
						w->mouse_released( _mouse, { double(event.xbutton.x), double(event.xbutton.y) }, int(event.xbutton.button) );
						break;

					case 4: // Mouse wheel up
					case 5: // Mouse wheel down
						break;
				}
				break;
			}

			case MotionNotify:
			{
				auto w = _windows[event.xmotion.window];
				w->mouse_moved( _mouse, { double(event.xmotion.x), double(event.xmotion.y) } );
				break;
			}

			case VisibilityNotify:
			case ReparentNotify:
				break;

			case ClientMessage:
			{
				auto w = _windows[event.xclient.window];
				if ( Atom(event.xclient.data.l[0]) == _atom_delete_window )
				{
					w->hide();
					_windows.erase( w->id() );
					done = _windows.empty();
				}
				break;
			}

			default:
				std::cout << "Unknown event: " << uint32_t( event.type ) << std::endl;
		}
	}

	return _exit_code;
}

////////////////////////////////////////

void dispatcher::exit( int code )
{
	_exit_code = code;
}

////////////////////////////////////////

void dispatcher::add_window( const std::shared_ptr<window> &w )
{
	_windows[w->id()] = w;
	XSetWMProtocols( _display.get(), w->id(), &_atom_delete_window, 1 );

	// Create an input context.
	auto xic = XCreateIC( _xim,
		XNClientWindow, w->id(),
		XNFocusWindow, w->id(),
		XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
		nullptr );
	if ( !xic )
		throw std::runtime_error( "failed to create input context" );
	w->set_input_context( xic );
}

////////////////////////////////////////

} }

<commit_msg>Fixed std::function calls without checking validity.<commit_after>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <X11/Xlib.h>
#include <base/contract.h>
#include <base/pointer.h>
#include <base/meta.h>
#include <utf/utf.h>
#include <utf/utfcat.h>
#include "dispatcher.h"

namespace platform { namespace xlib
{

////////////////////////////////////////

dispatcher::dispatcher( const std::shared_ptr<Display> &dpy, const std::shared_ptr<keyboard> &k, const std::shared_ptr<mouse> &m )
	: _display( dpy ), _keyboard( k ), _mouse( m )
{
	precondition( _display, "null display" );
	_atom_delete_window = XInternAtom( _display.get(), "WM_DELETE_WINDOW", True );

	_xim = XOpenIM( _display.get(), nullptr, nullptr, nullptr ); // TODO resource/class name?
	if ( !_xim )
		throw std::runtime_error( "failed to open input method" );
}

////////////////////////////////////////

dispatcher::~dispatcher( void )
{
}

////////////////////////////////////////

int dispatcher::execute( void )
{
	XFlush( _display.get() );
	_exit_code = 0;

	bool done = false;
	XEvent event;
	while ( !done )
	{
		XNextEvent( _display.get(), &event );
		switch ( event.type )
		{
			case Expose:
			{
				if ( event.xexpose.count == 0 )
				{
					auto win = _windows[event.xexpose.window];
					win->expose_event();
				}
				break;
			}

			case ConfigureNotify:
			{
				auto w = _windows[event.xconfigure.window];
				if ( w )
				{
					w->move_event( event.xconfigure.x, event.xconfigure.y );
					w->resize_event( event.xconfigure.width, event.xconfigure.height );
				}
				break;
			}

			case DestroyNotify:
			{
				auto w = _windows[event.xdestroywindow.window];
				w->closed();
				break;
			}

			case MapNotify:
			{
				auto w = _windows[event.xmap.window];
				if ( w->shown )
					w->shown();
				if ( w->restored )
					w->restored();
				break;
			}

			case UnmapNotify:
			{
				auto w = _windows[event.xunmap.window];
				if ( w )
				{
					if ( w->hidden )
						w->hidden();
					if ( w->minimized )
						w->minimized();
				}
				break;
			}

			case EnterNotify:
			{
				auto w = _windows[event.xcrossing.window];
				if ( w->entered )
					w->entered();
				break;
			}

			case LeaveNotify:
			{
				auto w = _windows[event.xcrossing.window];
				if ( w->exited )
					w->exited();
				break;
			}

			case KeyPress:
			{
				auto w = _windows[event.xkey.window];
				platform::scancode sc = _keyboard->get_scancode( event.xkey );
				if ( w->key_pressed )
					w->key_pressed( _keyboard, sc );
				if ( w->text_entered )
				{
					char keybuf[16];
					Status status;
					int length = Xutf8LookupString( w->input_context(), &event.xkey, keybuf, sizeof(keybuf), nullptr, &status );
					if ( length > 0 )
					{
						std::stringstream tmp( std::string( keybuf, size_t(length) ) );
						utf::iterator it( tmp, utf::UTF8 );
						while ( ++it )
						{
							if ( utf::is_graphic( *it ) )
								w->text_entered( _keyboard, *it );
						}
					}
				}
				break;
			}

			case KeyRelease:
			{
				auto w = _windows[event.xkey.window];
				platform::scancode sc = _keyboard->get_scancode( event.xkey );
				if ( w->key_released )
					w->key_released( _keyboard, sc );
				break;
			}

			case MappingNotify:
			{
				if ( event.xmapping.request == MappingKeyboard )
					XRefreshKeyboardMapping( &event.xmapping );
				break;
			}

			case ButtonPress:
			{
				auto w = _windows[event.xbutton.window];
				switch ( event.xbutton.button )
				{
					case 1:
					case 2:
					case 3:
						if ( w->mouse_pressed )
							w->mouse_pressed( _mouse, { double(event.xbutton.x), double(event.xbutton.y) }, int(event.xbutton.button) );
						break;

					case 4:
						if ( w->mouse_wheel )
							w->mouse_wheel( _mouse, 1 );
						break;

					case 5:
						if ( w->mouse_wheel )
							w->mouse_wheel( _mouse, -1 );
						break;
				}
				break;
			}

			case ButtonRelease:
			{
				auto w = _windows[event.xbutton.window];
				switch ( event.xbutton.button )
				{
					case 1:
					case 2:
					case 3:
						if ( w->mouse_released )
							w->mouse_released( _mouse, { double(event.xbutton.x), double(event.xbutton.y) }, int(event.xbutton.button) );
						break;

					case 4: // Mouse wheel up
					case 5: // Mouse wheel down
						break;
				}
				break;
			}

			case MotionNotify:
			{
				auto w = _windows[event.xmotion.window];
				if ( w->mouse_moved )
					w->mouse_moved( _mouse, { double(event.xmotion.x), double(event.xmotion.y) } );
				break;
			}

			case VisibilityNotify:
			case ReparentNotify:
				break;

			case ClientMessage:
			{
				auto w = _windows[event.xclient.window];
				if ( Atom(event.xclient.data.l[0]) == _atom_delete_window )
				{
					w->hide();
					_windows.erase( w->id() );
					done = _windows.empty();
				}
				break;
			}

			default:
				std::cout << "Unknown event: " << uint32_t( event.type ) << std::endl;
		}
	}

	return _exit_code;
}

////////////////////////////////////////

void dispatcher::exit( int code )
{
	_exit_code = code;
}

////////////////////////////////////////

void dispatcher::add_window( const std::shared_ptr<window> &w )
{
	_windows[w->id()] = w;
	XSetWMProtocols( _display.get(), w->id(), &_atom_delete_window, 1 );

	// Create an input context.
	auto xic = XCreateIC( _xim,
		XNClientWindow, w->id(),
		XNFocusWindow, w->id(),
		XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
		nullptr );
	if ( !xic )
		throw std::runtime_error( "failed to create input context" );
	w->set_input_context( xic );
}

////////////////////////////////////////

} }

<|endoftext|>


<commit_before>/*
* Alpha Entity List Adjuster
* Copyright (c) 2014 ThirteenAG <>
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
*/
#include "LimitAdjuster.h"

auto CVisibilityPlugins__Shutdown = (int *(__cdecl *)()) 0x582870;
auto CVisibilityPlugins__Initialise = (int *(__cdecl *)()) 0x5828A0;

auto CVisibilityPlugins__Shutdown3 = (int *(__cdecl *)()) 0x527EA0;
auto CVisibilityPlugins__Initialise3 = (int *(__cdecl *)()) 0x527E50;

class AlphaEntityListIII : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsIII() ? "AlphaEntityListSize" : nullptr; }
	void ChangeLimit(int, const std::string& value)
	{
		injector::WriteMemory(0x527E6B + 1, std::stoi(value), true);
		if (*(DWORD*)0x943098 == 0x4CBEBC20)
		{
			CVisibilityPlugins__Shutdown3();
			CVisibilityPlugins__Initialise3();
		}
	}

} AlphaEntityListIII;

class AlphaEntityListVC : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsVC() ? "AlphaEntityListSize" : nullptr; }
	void ChangeLimit(int, const std::string& value)
		{
			injector::WriteMemory(0x5828DB+1, std::stoi(value), true);

			if (*(DWORD*)0x97F30C == 0x4CBEBC20)
			{
				CVisibilityPlugins__Shutdown();
				CVisibilityPlugins__Initialise();
			}
		}

} AlphaEntityListVC;

class AlphaEntityListSA : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsSA() ? "AlphaEntityListSize" : nullptr; }

	void ChangeLimit(int, const std::string& value)
	{
		injector::WriteMemory(0x733B05, std::stoi(value), true);
		injector::WriteMemory(0x733B55, std::stoi(value), true);
	}
} AlphaEntityListSA;

<commit_msg>Initialise/Shutdown now local<commit_after>/*
* Alpha Entity List Adjuster
* Copyright (c) 2014 ThirteenAG <>
* Copyright (c) 2014 Silent <zdanio95@gmail.com>
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
*/
#include "LimitAdjuster.h"

class AlphaEntityListIII : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsIII() ? "AlphaEntityListSize" : nullptr; }
	void ChangeLimit(int, const std::string& value)
	{
		injector::WriteMemory(0x527E6B + 1, std::stoi(value), true);
		if (*(DWORD*)0x943098 == 0x4CBEBC20)
		{
			auto CVisibilityPlugins__Shutdown = (void (__cdecl *)()) 0x527EA0;
			auto CVisibilityPlugins__Initialise = (void (__cdecl *)()) 0x527E50;

			CVisibilityPlugins__Shutdown();
			CVisibilityPlugins__Initialise();
		}
	}

} AlphaEntityListIII;

class AlphaEntityListVC : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsVC() ? "AlphaEntityListSize" : nullptr; }
	void ChangeLimit(int, const std::string& value)
		{
			injector::WriteMemory(0x5828DB+1, std::stoi(value), true);

			if (*(DWORD*)0x97F30C == 0x4CBEBC20)
			{
				auto CVisibilityPlugins__Shutdown = (void (__cdecl *)()) 0x582870;
				auto CVisibilityPlugins__Initialise = (void (__cdecl *)()) 0x5828A0;

				CVisibilityPlugins__Shutdown();
				CVisibilityPlugins__Initialise();
			}
		}

} AlphaEntityListVC;

class AlphaEntityListSA : public SimpleAdjuster
{
public:
	const char* GetLimitName() { return GetGVM().IsSA() ? "AlphaEntityListSize" : nullptr; }

	void ChangeLimit(int, const std::string& value)
	{
		injector::WriteMemory(0x733B05, std::stoi(value), true);
		injector::WriteMemory(0x733B55, std::stoi(value), true);
	}
} AlphaEntityListSA;
<|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 BlockChainLoader.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2015
 */

#include "BlockChainLoader.h"
#include "StateLoader.h"
#include "Common.h"

using namespace std;
using namespace dev;
using namespace dev::test;
using namespace dev::eth;

namespace dev
{
namespace test
{
dev::eth::BlockInfo toBlockInfo(Json::Value const& _json);
bytes toGenesisBlock(Json::Value const& _json);
}
}

dev::eth::BlockInfo dev::test::toBlockInfo(Json::Value const& _json)
{
	RLPStream rlpStream;
	auto size = _json.getMemberNames().size();
	rlpStream.appendList(_json["hash"].empty() ? size : (size - 1));
	rlpStream << fromHex(_json["parentHash"].asString());
	rlpStream << fromHex(_json["uncleHash"].asString());
	rlpStream << fromHex(_json["coinbase"].asString());
	rlpStream << fromHex(_json["stateRoot"].asString());
	rlpStream << fromHex(_json["transactionsTrie"].asString());
	rlpStream << fromHex(_json["receiptTrie"].asString());
	rlpStream << fromHex(_json["bloom"].asString());
	rlpStream << bigint(_json["difficulty"].asString());
	rlpStream << bigint(_json["number"].asString());
	rlpStream << bigint(_json["gasLimit"].asString());
	rlpStream << bigint(_json["gasUsed"].asString());
	rlpStream << bigint(_json["timestamp"].asString());
	rlpStream << fromHex(_json["extraData"].asString());
	rlpStream << fromHex(_json["mixHash"].asString());
	rlpStream << fromHex(_json["nonce"].asString());

	BlockInfo result;
	RLP rlp(rlpStream.out());
	result.populateFromHeader(rlp, IgnoreNonce);
	return result;
}

bytes dev::test::toGenesisBlock(Json::Value const& _json)
{
	BlockInfo bi = toBlockInfo(_json);
	RLPStream rlpStream;
	bi.streamRLP(rlpStream, WithNonce);

	RLPStream fullStream(3);
	fullStream.appendRaw(rlpStream.out());
	fullStream.appendRaw(RLPEmptyList);
	fullStream.appendRaw(RLPEmptyList);
	bi.verifyInternals(&fullStream.out());

	return fullStream.out();
}

BlockChainLoader::BlockChainLoader(Json::Value const& _json)
{
	// load pre state
	StateLoader sl(_json["pre"]);
	m_state = sl.state();

	// load genesisBlock
	m_bc.reset(new BlockChain(toGenesisBlock(_json["genesisBlockHeader"]), m_dir.path(), true));

	// load blocks
	for (auto const& block: _json["blocks"])
	{
		bytes rlp = fromHex(block["rlp"].asString());
		m_bc->import(rlp, m_state.db());
	}

	// sync state
	m_state.sync(*m_bc);
}
<commit_msg>BlockChainLoader uses genesisRLP to load blockchain<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 BlockChainLoader.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2015
 */

#include "BlockChainLoader.h"
#include "StateLoader.h"
#include "Common.h"

using namespace std;
using namespace dev;
using namespace dev::test;
using namespace dev::eth;

BlockChainLoader::BlockChainLoader(Json::Value const& _json)
{
	// load pre state
	StateLoader sl(_json["pre"]);
	m_state = sl.state();

	// load genesisBlock
	m_bc.reset(new BlockChain(fromHex(_json["genesisRLP"].asString()), m_dir.path(), true));

	// load blocks
	for (auto const& block: _json["blocks"])
	{
		bytes rlp = fromHex(block["rlp"].asString());
		m_bc->import(rlp, m_state.db());
	}

	// sync state
	m_state.sync(*m_bc);
}
<|endoftext|>


<commit_before>#include "Athena/FileInfo.hpp"
#include "Athena/Utility.hpp"
#include "Athena/FileWriter.hpp"
#include "Athena/FileReader.hpp"
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#if !(defined(HW_DOL) || defined(HW_RVL) || defined(_WIN32))
#include <fcntl.h>
#endif

#ifdef _WIN32
#include <windows.h>
#include <wchar.h>
#endif

#ifdef _MSC_VER
#include <functional>
#include <locale>
#define stat64 __stat64
#define realpath(__name, __resolved) _fullpath((__name), (__resolved), 4096)
#endif

namespace Athena
{

FileInfo::FileInfo(const std::string& path)
    : m_path(path)
{
}

std::string FileInfo::absolutePath() const
{
    std::string path = absoluteFilePath();
    size_t pos = path.find_last_of('/');
    if (pos == std::string::npos)
        pos = path.find_last_of('\\');
    if (pos == std::string::npos)
        return path;

    return path.substr(0, pos+1);
}

std::string FileInfo::absoluteFilePath() const
{
    char ret[4096];
    realpath(m_path.c_str(), ret);
    return ret;
}

std::string FileInfo::filename() const
{
    size_t pos = m_path.find_last_of('/');
    if (pos == std::string::npos)
        pos = m_path.find_last_of('\\');
    if (pos == std::string::npos)
        return m_path;
    return m_path.substr(pos + 1);
}

std::string FileInfo::extension() const
{
    size_t pos = m_path.find_last_of('.');
    if (pos == std::string::npos)
        return std::string();

    return m_path.substr(pos + 1);
}

atUint64 FileInfo::size() const
{
    return utility::fileSize(m_path);
}

bool FileInfo::exists() const
{
#ifdef GEKKO
    struct stat st;
    int e = stat(m_path.c_str(), &st);
#else
    struct stat64 st;
    int e = stat64(m_path.c_str(), &st);
#endif

    if (e < 0)
        return false;

    return (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode));
}

bool FileInfo::isLink() const
{
#ifdef GEKKO
    struct stat st;
    int e = stat(m_path.c_str(), &st);
#else
    struct stat64 st;
    int e = stat64(m_path.c_str(), &st);
#endif
    if (e < 0)
        return false;

    return (S_ISLNK(st.st_mode));
}

bool FileInfo::isFile() const
{
    stat64_t st;
    int e = stat64(m_path.c_str(), &st);
    if (e < 0)
        return false;

    return (S_ISREG(st.st_mode));
}

bool FileInfo::touch() const
{
#if defined(__GNUC__) && !(defined(HW_DOL) || defined(HW_RVL) || defined(GEKKO))
    stat64_t st;
    if (stat64(m_path.c_str(), &st) < 0) {
        (void)Athena::io::FileWriter(m_path);
        return true;
    }
    if (utimensat(AT_FDCWD, m_path.c_str(), NULL, 0) < 0) {
        return false;
    }
#elif defined(_WIN32)
    FILETIME modtime;
    SYSTEMTIME st;
    HANDLE fh;
    wchar_t date[80], time[80];

    fh = CreateFileW(path, GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, CREATE_NEW, 0, NULL);
    if (fh == INVALID_HANDLE_VALUE)
        return false;

    /*
     * Use GetFileTime() to get the file modification time.
     */
    if (GetFileTime(fh, NULL, NULL, &modtime) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    FileTimeToSystemTime(&modtime, &st);
    if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 ||
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    /*
     * Use SetFileTime() to change the file modification time
     * to the current time.
     */
    GetSystemTime(&st);
    if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 ||
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0)
    {
        CloseHandle(fh);
        return false;
    }
    SystemTimeToFileTime(&st, &modtime);
    if (SetFileTime(fh, NULL, NULL, &modtime) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    CloseHandle(fh);
#elif (defined(HW_RVL) || defined(HW_DOL)) && defined(GEKKO)
    // Generic portable version, not extremely reliable but does work
    atUint64 val = 0xCDCDCDCDCD;
    try
    {
        Athena::io::FileReader reader(m_path.c_str());
        val = reader.readUint64();
    }
    catch(...)
    {
    }

    try
    {
        Athena::io::FileWriter writer(m_path, false);
        if (val != 0xCDCDCDCDCD)
            writer.writeUint64(val);
    }
    catch(...)
    {
        return false;
    }

#endif

    return true;
}

}
<commit_msg>* struct stat64 -> stat64_t<commit_after>#include "Athena/FileInfo.hpp"
#include "Athena/Utility.hpp"
#include "Athena/FileWriter.hpp"
#include "Athena/FileReader.hpp"
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#if !(defined(HW_DOL) || defined(HW_RVL) || defined(_WIN32))
#include <fcntl.h>
#endif

#ifdef _WIN32
#include <windows.h>
#include <wchar.h>
#endif

#ifdef _MSC_VER
#include <functional>
#include <locale>
#define stat64 __stat64
#define realpath(__name, __resolved) _fullpath((__name), (__resolved), 4096)
#endif

namespace Athena
{

FileInfo::FileInfo(const std::string& path)
    : m_path(path)
{
}

std::string FileInfo::absolutePath() const
{
    std::string path = absoluteFilePath();
    size_t pos = path.find_last_of('/');
    if (pos == std::string::npos)
        pos = path.find_last_of('\\');
    if (pos == std::string::npos)
        return path;

    return path.substr(0, pos+1);
}

std::string FileInfo::absoluteFilePath() const
{
    char ret[4096];
    realpath(m_path.c_str(), ret);
    return ret;
}

std::string FileInfo::filename() const
{
    size_t pos = m_path.find_last_of('/');
    if (pos == std::string::npos)
        pos = m_path.find_last_of('\\');
    if (pos == std::string::npos)
        return m_path;
    return m_path.substr(pos + 1);
}

std::string FileInfo::extension() const
{
    size_t pos = m_path.find_last_of('.');
    if (pos == std::string::npos)
        return std::string();

    return m_path.substr(pos + 1);
}

atUint64 FileInfo::size() const
{
    return utility::fileSize(m_path);
}

bool FileInfo::exists() const
{
    struct stat64_t st;
    int e = stat64(m_path.c_str(), &st);

    if (e < 0)
        return false;

    return (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode));
}

bool FileInfo::isLink() const
{
    struct stat64_t st;
    int e = stat64(m_path.c_str(), &st);
    if (e < 0)
        return false;

    return (S_ISLNK(st.st_mode));
}

bool FileInfo::isFile() const
{
    stat64_t st;
    int e = stat64(m_path.c_str(), &st);
    if (e < 0)
        return false;

    return (S_ISREG(st.st_mode));
}

bool FileInfo::touch() const
{
#if defined(__GNUC__) && !(defined(HW_DOL) || defined(HW_RVL) || defined(GEKKO))
    stat64_t st;
    if (stat64(m_path.c_str(), &st) < 0) {
        (void)Athena::io::FileWriter(m_path);
        return true;
    }
    if (utimensat(AT_FDCWD, m_path.c_str(), NULL, 0) < 0) {
        return false;
    }
#elif defined(_WIN32)
    FILETIME modtime;
    SYSTEMTIME st;
    HANDLE fh;
    wchar_t date[80], time[80];

    fh = CreateFileW(path, GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, CREATE_NEW, 0, NULL);
    if (fh == INVALID_HANDLE_VALUE)
        return false;

    /*
     * Use GetFileTime() to get the file modification time.
     */
    if (GetFileTime(fh, NULL, NULL, &modtime) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    FileTimeToSystemTime(&modtime, &st);
    if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 ||
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    /*
     * Use SetFileTime() to change the file modification time
     * to the current time.
     */
    GetSystemTime(&st);
    if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 ||
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0)
    {
        CloseHandle(fh);
        return false;
    }
    SystemTimeToFileTime(&st, &modtime);
    if (SetFileTime(fh, NULL, NULL, &modtime) == 0)
    {
        CloseHandle(fh);
        return false;
    }

    CloseHandle(fh);
#elif (defined(HW_RVL) || defined(HW_DOL)) && defined(GEKKO)
    // Generic portable version, not extremely reliable but does work
    atUint64 val = 0xCDCDCDCDCD;
    try
    {
        Athena::io::FileReader reader(m_path.c_str());
        val = reader.readUint64();
    }
    catch(...)
    {
    }

    try
    {
        Athena::io::FileWriter writer(m_path, false);
        if (val != 0xCDCDCDCDCD)
            writer.writeUint64(val);
    }
    catch(...)
    {
        return false;
    }

#endif

    return true;
}

}
<|endoftext|>


<commit_before>#include "AudioSummer_F32.h"

void AudioSummer4_F32::update(void) {
  audio_block_f32_t *in, *out=NULL;

  //get the first available channel
  int channel = 0;
  while  (channel < 4) {
	  out = receiveWritable_f32(channel);
	  if (out) break;
	  channel++;
  }
  if (!out) return;  //there was no data available.  so exit.

  //add in the remaining channels, as available
  channel++;
  while  (channel < 4) {
    in = receiveReadOnly_f32(channel);
    if (in) {
		arm_add_f32(out->data, in->data, out->data, in->length);
		AudioStream_F32::release(in);
	} else {
		//do nothing, this vector is empty
	}
	channel++;
  }

  if (out) {
    AudioStream_F32::transmit(out);
    AudioStream_F32::release(out);
  }
}
<commit_msg>AudioSummer: do not use disabled channels<commit_after>#include "AudioSummer_F32.h"

void AudioSummer4_F32::update(void) {
  audio_block_f32_t *in, *out=NULL;

  //get the first available channel
  int channel = 0;
  while  (channel < 4) {
	  out = receiveWritable_f32(channel);
	  if (out && flag_useChan[channel]) {
		  //yes, this is an audio block and use it
		  break;
	  } else {
		  //this may or may not be an audio block, but don't use it
		  if (!out) AudioStream_F32::release(out);
	  }
	  channel++;
  }
  if (!out) return;  //there was no data available.  so exit.

  //add in the remaining channels, as available and if enabled
  channel++;
  while  (channel < 4) {
    in = receiveReadOnly_f32(channel);
    if (in) {
		if (flag_useChan[channel]) {
			arm_add_f32(out->data, in->data, out->data, in->length);
		}
		AudioStream_F32::release(in);
	} else {
		//do nothing, this vector is empty
	}
	channel++;
  }

  if (out) {
    AudioStream_F32::transmit(out);
    AudioStream_F32::release(out);
  }
}
<|endoftext|>


<commit_before>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'

R__LOAD_LIBRARY(libRooFit)

#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill

using namespace RooFit;

////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
//                      { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////

void workbench(std::string workspace_filepath,
               std::string workspace_name,
               std::string model_config_name="ModelConfig",
               std::string data_name="obsData",
               int num_cpu=1,
               int optConst=0,
               int parallel_interleave=0,
               bool cpu_affinity=true,
               int seed=1,
               int timing_flag=1,
               bool time_num_ints=false,
               bool fork_timer = false,
               int fork_timer_sleep_us = 100000,
               int print_level=0,
               bool debug=false,
               bool total_cpu_timing=false,
               bool fix_binned_pdfs=false,
               bool zero_initial_POI=false,
               std::string POI_name="",
               bool time_evaluate_partition=false,
               bool time_MPFE_forks=false
               ) {
  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::list<std::string> names = {"workspace_filepath", "workspace_name",
                                    "model_config_name", "data_name",
                                    "num_cpu", "parallel_interleave", "cpu_affinity",
                                    "seed", "pid", "time_num_ints",
                                    "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names.begin(), names.end());

    outfile << workspace_filepath << workspace_name
            << model_config_name << data_name
            << num_cpu << parallel_interleave << cpu_affinity
            << seed << getpid() << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTimer::set_timing_flag(timing_flag);
  if (time_num_ints) {
    RooTimer::set_time_numInts(kTRUE);
  }
  if (time_evaluate_partition) {
    RooTimer::set_time_evaluate_partition(kTRUE);
  }
  if (time_MPFE_forks) {
    RooTimer::set_time_MPFE_forks(kTRUE);
  }

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // Load the workspace data and pdf
  TFile *_file0 = TFile::Open(workspace_filepath.c_str());

  RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));

  // Activate binned likelihood calculation for binned models
  if (fix_binned_pdfs) {
    RooFIter iter = w->components().fwdIterator();
    RooAbsArg* component_arg;
    while((component_arg = iter.next())) {
      if (component_arg->IsA() == RooRealSumPdf::Class()) {
        component_arg->setAttribute("BinnedLikelihood");
        std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
      }
    }
  }

  RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));

  // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
  RooAbsPdf* pdf = mc->GetPdf();
  RooAbsData * data = w->data(data_name.c_str());

  // Manually set initial values of parameter of interest
  if (zero_initial_POI) {
    if (POI_name.length() > 0) {
      RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
      POI->setVal(0);
    } else {
      std::cout << "POI_name is empty!" << std::endl;
      exit(1);
    }
  }

  // --- Perform extended ML fit of composite PDF to data ---

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    outfile.add_member_name("walltime_s")
           .add_member_name("segment")
           .add_member_name("pid");
  }

  RooJsonListFile outfile_cpu;
  RooCPUTimer ctimer;

  if (total_cpu_timing) {
    outfile_cpu.open("timing_full_minimize_cpu.json");
    outfile_cpu.add_member_name("cputime_s")
               .add_member_name("segment")
               .add_member_name("pid");
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                       CPUAffinity(cpuAffinity)));//, "Extended");
    std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll));

    if (time_evaluate_partition) {
      nll->setTimingEvaluatePartitions(kTRUE);
    }

    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */

      double time_migrad, time_hesse, time_minos;
      double ctime_migrad, ctime_hesse, ctime_minos;

      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }
      // m.hesse();

      m.migrad();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "migrad" << getpid();
        time_migrad = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
        ctime_migrad = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.hesse();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "hesse" << getpid();
        time_hesse = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
        ctime_hesse = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.minos(*mc->GetParametersOfInterest());

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "minos" << getpid();
        time_minos = timer.timing_s();

        outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "minos" << getpid();
        ctime_minos = ctimer.timing_s();

        outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }
  }
}
<commit_msg>Wrong function call fixed<commit_after>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'

R__LOAD_LIBRARY(libRooFit)

#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill

using namespace RooFit;

////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
//                      { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////

void workbench(std::string workspace_filepath,
               std::string workspace_name,
               std::string model_config_name="ModelConfig",
               std::string data_name="obsData",
               int num_cpu=1,
               int optConst=0,
               int parallel_interleave=0,
               bool cpu_affinity=true,
               int seed=1,
               int timing_flag=1,
               bool time_num_ints=false,
               bool fork_timer = false,
               int fork_timer_sleep_us = 100000,
               int print_level=0,
               bool debug=false,
               bool total_cpu_timing=false,
               bool fix_binned_pdfs=false,
               bool zero_initial_POI=false,
               std::string POI_name="",
               bool time_evaluate_partition=false,
               bool time_MPFE_forks=false
               ) {
  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::list<std::string> names = {"workspace_filepath", "workspace_name",
                                    "model_config_name", "data_name",
                                    "num_cpu", "parallel_interleave", "cpu_affinity",
                                    "seed", "pid", "time_num_ints",
                                    "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names.begin(), names.end());

    outfile << workspace_filepath << workspace_name
            << model_config_name << data_name
            << num_cpu << parallel_interleave << cpu_affinity
            << seed << getpid() << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTimer::set_timing_flag(timing_flag);
  if (time_num_ints) {
    RooTimer::set_time_numInts(kTRUE);
  }
  if (time_evaluate_partition) {
    RooTimer::set_time_evaluate_partition(kTRUE);
  }
  if (time_MPFE_forks) {
    RooTimer::set_time_MPFE_forks(kTRUE);
  }

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // Load the workspace data and pdf
  TFile *_file0 = TFile::Open(workspace_filepath.c_str());

  RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));

  // Activate binned likelihood calculation for binned models
  if (fix_binned_pdfs) {
    RooFIter iter = w->components().fwdIterator();
    RooAbsArg* component_arg;
    while((component_arg = iter.next())) {
      if (component_arg->IsA() == RooRealSumPdf::Class()) {
        component_arg->setAttribute("BinnedLikelihood");
        std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
      }
    }
  }

  RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));

  // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
  RooAbsPdf* pdf = mc->GetPdf();
  RooAbsData * data = w->data(data_name.c_str());

  // Manually set initial values of parameter of interest
  if (zero_initial_POI) {
    if (POI_name.length() > 0) {
      RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
      POI->setVal(0);
    } else {
      std::cout << "POI_name is empty!" << std::endl;
      exit(1);
    }
  }

  // --- Perform extended ML fit of composite PDF to data ---

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    outfile.add_member_name("walltime_s")
           .add_member_name("segment")
           .add_member_name("pid");
  }

  RooJsonListFile outfile_cpu;
  RooCPUTimer ctimer;

  if (total_cpu_timing) {
    outfile_cpu.open("timing_full_minimize_cpu.json");
    outfile_cpu.add_member_name("cputime_s")
               .add_member_name("segment")
               .add_member_name("pid");
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                       CPUAffinity(cpuAffinity)));//, "Extended");
    std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll));

    if (time_evaluate_partition) {
      nll->setTimeEvaluatePartition(kTRUE);
    }

    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */

      double time_migrad, time_hesse, time_minos;
      double ctime_migrad, ctime_hesse, ctime_minos;

      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }
      // m.hesse();

      m.migrad();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "migrad" << getpid();
        time_migrad = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
        ctime_migrad = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.hesse();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "hesse" << getpid();
        time_hesse = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
        ctime_hesse = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.minos(*mc->GetParametersOfInterest());

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "minos" << getpid();
        time_minos = timer.timing_s();

        outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "minos" << getpid();
        ctime_minos = ctimer.timing_s();

        outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }
  }
}
<|endoftext|>


<commit_before>// @(#)root/proof:$Name:  $:$Id: TProofChain.cxx,v 1.7 2007/05/08 14:57:02 rdm Exp $
// Author: G. Ganis  Nov 2006

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TProofChain                                                          //
//                                                                      //
// A TChain proxy on PROOF.                                             //
// Uses an internal TDSet to handle processing.                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TProofChain.h"
#include "TDSet.h"
#include "TList.h"
#include "TProof.h"
#include "TROOT.h"
#include "TEventList.h"
#include "TEntryList.h"

ClassImp(TProofChain)

//______________________________________________________________________________
TProofChain::TProofChain() : TChain()
{
   // Crates a new Proof chain proxy containing the files from the TDSet.

   fChain        = 0;
   fTree         = 0;
   fSet          = 0;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
}

//______________________________________________________________________________
TProofChain::TProofChain(TChain *chain) : TChain()
{
   // Crates a new Proof chain proxy containing the files from the TDSet.

   fChain        = chain;
   fTree         = 0;
   fSet          = chain ? new TDSet((const TChain &)(*chain)) : 0;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
   if (gProof)
      gProof->AddChain(chain);
}

//______________________________________________________________________________
TProofChain::~TProofChain()
{
   // Destructor

   if (fChain) {
      SafeDelete(fSet);
   } else {
      // Not owner
      fSet = 0;
   }
   SafeDelete(fTree);
   fDirectory    = 0;
}

//______________________________________________________________________________
TProofChain::TProofChain(TDSet *dset, Bool_t gettreeheader)
{
   // Constructor from existing data set

   fChain        = 0;
   fTree         = 0;
   fSet          = dset;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
   if (gProof) {
      ConnectProof();
      if (gettreeheader && dset)
         fTree = gProof->GetTreeHeader(dset);
   }
}

//______________________________________________________________________________
void TProofChain::Browse(TBrowser *b)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::Browse().

   fSet->Browse(b);
}

//______________________________________________________________________________
Long64_t TProofChain::Draw(const char *varexp, const TCut &selection,
                           Option_t *option, Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // Returns -1 in case of error or number of selected events in case of success.
   // See TDSet::Browse().

   if (!gProof) {
      Error("Draw", "no active PROOF session");
      return -1;
   }
   ConnectProof();

   if (fDrawFeedback)
      gProof->SetDrawFeedbackOption(fDrawFeedback, option);
   fReadEntry = firstentry;

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);
   return rv;
}

//______________________________________________________________________________
Long64_t TProofChain::Draw(const char *varexp, const char *selection,
                           Option_t *option,Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // Returns -1 in case of error or number of selected events in case of success.
   // See TDSet::Browse().

   if (!gProof) {
      Error("Draw", "no active PROOF session");
      return -1;
   }
   ConnectProof();

   if (fDrawFeedback)
      gProof->SetDrawFeedbackOption(fDrawFeedback, option);
   fReadEntry = firstentry;

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);
   return rv;
}

//______________________________________________________________________________
TBranch *TProofChain::FindBranch(const char* branchname)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::FindBranch().

   return (fTree ? fTree->FindBranch(branchname) : (TBranch *)0);
}

//______________________________________________________________________________
TLeaf *TProofChain::FindLeaf(const char* searchname)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::FindLeaf().

   return (fTree ? fTree->FindLeaf(searchname) : (TLeaf *)0);
}

//______________________________________________________________________________
TBranch *TProofChain::GetBranch(const char *name)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetBranch().

   return (fTree ? fTree->GetBranch(name) : (TBranch *)0);
}

//______________________________________________________________________________
Bool_t TProofChain::GetBranchStatus(const char *branchname) const
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetBranchStatus().

   return (fTree ? fTree->GetBranchStatus(branchname) : kFALSE);
}

//______________________________________________________________________________
TVirtualTreePlayer *TProofChain::GetPlayer()
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetPlayer().

   if (!fTree)
      if (gProof) {
         fTree = gProof->GetTreeHeader(fSet);
         ConnectProof();
      }

   return (fTree ? fTree->GetPlayer() : (TVirtualTreePlayer *)0);
}

//______________________________________________________________________________
Long64_t TProofChain::Process(const char *filename, Option_t *option,
                              Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // The return value is -1 in case of error and TSelector::GetStatus() in
   // in case of success.
   // See TDSet::Process().

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   return fSet->Process(filename, option, nentries, firstentry);
}

//______________________________________________________________________________
Long64_t TProofChain::Process(TSelector *selector, Option_t *option,
                              Long64_t nentries, Long64_t firstentry)
{
   // Not implemented in TProofChain. Shouldn't be used.
   // The return value is -1 in case of error and TSelector::GetStatus() in
   // in case of success.

   if (selector || option || nentries || firstentry);
   //   return fSet->Process(selector, option, nentries, firstentry);
   Warning("Process", "not implemented"); // TODO
   return -1;
}

//______________________________________________________________________________
void TProofChain::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
   // See TTree::SetDebug

   TTree::SetDebug(level, min, max);
}

//______________________________________________________________________________
void TProofChain::SetName(const char *name)
{
   // See TTree::GetName.

   TTree::SetName(name);
}

//______________________________________________________________________________
Long64_t TProofChain::GetEntries() const
{
   // Returns the total number of entries in the TProofChain, which is
   // the number of entries in the TDSet that it holds.

   // this was used for holding the total number of entries
   return (fTree ? fTree->GetMaxEntryLoop() : (Long64_t)(-1));
}

//______________________________________________________________________________
Long64_t TProofChain::GetEntries(const char *)
{
   // See TTree::GetEntries(const char *selection)
   // Not implemented in TProofChain. Shouldn't be used.

   return Long64_t(-1);
}

//______________________________________________________________________________
void TProofChain::Progress(Long64_t total, Long64_t processed)
{
   // Changes the number of processed entries.

   if (gROOT->IsInterrupted() && gProof)
      gProof->StopProcess(kTRUE);
   if (total)
      ;

   fReadEntry = processed;
}

//______________________________________________________________________________
Long64_t TProofChain::GetReadEntry() const
{
   // Returns the number of processed entries.

   return fReadEntry;
}

//______________________________________________________________________________
void TProofChain::ReleaseProof()
{
   // Releases PROOF. Disconnect the "progress" signal.

   if (!gProof)
      return;
   gProof->Disconnect("Progress(Long64_t,Long64_t)",
                      this, "Progress(Long64_t,Long64_t)");
   if (fDrawFeedback)
      gProof->DeleteDrawFeedback(fDrawFeedback);
   fDrawFeedback = 0;
}

//______________________________________________________________________________
void TProofChain::ConnectProof()
{
   // Connects the proof - creates a "DrawFeedback" and connects the
   // "Progress" signal.

   if (gProof && !fDrawFeedback) {
      fDrawFeedback = gProof->CreateDrawFeedback();

      gProof->Connect("Progress(Long64_t,Long64_t)", "TProofChain",
                       this, "Progress(Long64_t,Long64_t)");
   }
}
<commit_msg><commit_after>
// @(#)root/proof:$Name:  $:$Id: TProofChain.cxx,v 1.8 2007/07/13 13:22:57 ganis Exp $
// Author: G. Ganis  Nov 2006

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TProofChain                                                          //
//                                                                      //
// A TChain proxy on PROOF.                                             //
// Uses an internal TDSet to handle processing.                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TProofChain.h"
#include "TDSet.h"
#include "TList.h"
#include "TProof.h"
#include "TROOT.h"
#include "TEventList.h"
#include "TEntryList.h"

ClassImp(TProofChain)

//______________________________________________________________________________
TProofChain::TProofChain() : TChain()
{
   // Crates a new Proof chain proxy containing the files from the TDSet.

   fChain        = 0;
   fTree         = 0;
   fSet          = 0;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
}

//______________________________________________________________________________
TProofChain::TProofChain(TChain *chain) : TChain()
{
   // Crates a new Proof chain proxy containing the files from the TDSet.

   fChain        = chain;
   fTree         = 0;
   fSet          = chain ? new TDSet((const TChain &)(*chain)) : 0;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
   if (gProof)
      gProof->AddChain(chain);
}

//______________________________________________________________________________
TProofChain::~TProofChain()
{
   // Destructor

   if (fChain) {
      SafeDelete(fSet);
      // Remove the chain from the private lists in the TProof objects
      TIter nxp(gROOT->GetListOfSockets());
      TObject *o = 0;
      TProof *p = 0;
      while ((o = nxp()))
         if ((p = dynamic_cast<TProof *>(o)))
            p->RemoveChain(fChain);
      fChain->SetProof(0);
   } else {
      // Not owner
      fSet = 0;
   }
   SafeDelete(fTree);
   fDirectory    = 0;

}

//______________________________________________________________________________
TProofChain::TProofChain(TDSet *dset, Bool_t gettreeheader)
{
   // Constructor from existing data set

   fChain        = 0;
   fTree         = 0;
   fSet          = dset;
   fDirectory    = gDirectory;
   fDrawFeedback = 0;
   if (gProof) {
      ConnectProof();
      if (gettreeheader && dset)
         fTree = gProof->GetTreeHeader(dset);
   }
}

//______________________________________________________________________________
void TProofChain::Browse(TBrowser *b)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::Browse().

   fSet->Browse(b);
}

//______________________________________________________________________________
Long64_t TProofChain::Draw(const char *varexp, const TCut &selection,
                           Option_t *option, Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // Returns -1 in case of error or number of selected events in case of success.
   // See TDSet::Browse().

   if (!gProof) {
      Error("Draw", "no active PROOF session");
      return -1;
   }
   ConnectProof();

   if (fDrawFeedback)
      gProof->SetDrawFeedbackOption(fDrawFeedback, option);
   fReadEntry = firstentry;

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);
   return rv;
}

//______________________________________________________________________________
Long64_t TProofChain::Draw(const char *varexp, const char *selection,
                           Option_t *option,Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // Returns -1 in case of error or number of selected events in case of success.
   // See TDSet::Browse().

   if (!gProof) {
      Error("Draw", "no active PROOF session");
      return -1;
   }
   ConnectProof();

   if (fDrawFeedback)
      gProof->SetDrawFeedbackOption(fDrawFeedback, option);
   fReadEntry = firstentry;

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);
   return rv;
}

//______________________________________________________________________________
TBranch *TProofChain::FindBranch(const char* branchname)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::FindBranch().

   return (fTree ? fTree->FindBranch(branchname) : (TBranch *)0);
}

//______________________________________________________________________________
TLeaf *TProofChain::FindLeaf(const char* searchname)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::FindLeaf().

   return (fTree ? fTree->FindLeaf(searchname) : (TLeaf *)0);
}

//______________________________________________________________________________
TBranch *TProofChain::GetBranch(const char *name)
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetBranch().

   return (fTree ? fTree->GetBranch(name) : (TBranch *)0);
}

//______________________________________________________________________________
Bool_t TProofChain::GetBranchStatus(const char *branchname) const
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetBranchStatus().

   return (fTree ? fTree->GetBranchStatus(branchname) : kFALSE);
}

//______________________________________________________________________________
TVirtualTreePlayer *TProofChain::GetPlayer()
{
   // Forwards the execution to the dummy tree header.
   // See TTree::GetPlayer().

   if (!fTree)
      if (gProof) {
         fTree = gProof->GetTreeHeader(fSet);
         ConnectProof();
      }

   return (fTree ? fTree->GetPlayer() : (TVirtualTreePlayer *)0);
}

//______________________________________________________________________________
Long64_t TProofChain::Process(const char *filename, Option_t *option,
                              Long64_t nentries, Long64_t firstentry)
{
   // Forwards the execution to the TDSet.
   // The return value is -1 in case of error and TSelector::GetStatus() in
   // in case of success.
   // See TDSet::Process().

   // Set either the entry-list (priority) or the event-list
   if (fEntryList) {
      fSet->SetEntryList(fEntryList);
   } else if (fEventList) {
      fSet->SetEntryList(fEventList);
   }

   return fSet->Process(filename, option, nentries, firstentry);
}

//______________________________________________________________________________
Long64_t TProofChain::Process(TSelector *selector, Option_t *option,
                              Long64_t nentries, Long64_t firstentry)
{
   // Not implemented in TProofChain. Shouldn't be used.
   // The return value is -1 in case of error and TSelector::GetStatus() in
   // in case of success.

   if (selector || option || nentries || firstentry);
   //   return fSet->Process(selector, option, nentries, firstentry);
   Warning("Process", "not implemented"); // TODO
   return -1;
}

//______________________________________________________________________________
void TProofChain::SetDebug(Int_t level, Long64_t min, Long64_t max)
{
   // See TTree::SetDebug

   TTree::SetDebug(level, min, max);
}

//______________________________________________________________________________
void TProofChain::SetName(const char *name)
{
   // See TTree::GetName.

   TTree::SetName(name);
}

//______________________________________________________________________________
Long64_t TProofChain::GetEntries() const
{
   // Returns the total number of entries in the TProofChain, which is
   // the number of entries in the TDSet that it holds.

   // this was used for holding the total number of entries
   return (fTree ? fTree->GetMaxEntryLoop() : (Long64_t)(-1));
}

//______________________________________________________________________________
Long64_t TProofChain::GetEntries(const char *)
{
   // See TTree::GetEntries(const char *selection)
   // Not implemented in TProofChain. Shouldn't be used.

   return Long64_t(-1);
}

//______________________________________________________________________________
void TProofChain::Progress(Long64_t total, Long64_t processed)
{
   // Changes the number of processed entries.

   if (gROOT->IsInterrupted() && gProof)
      gProof->StopProcess(kTRUE);
   if (total)
      ;

   fReadEntry = processed;
}

//______________________________________________________________________________
Long64_t TProofChain::GetReadEntry() const
{
   // Returns the number of processed entries.

   return fReadEntry;
}

//______________________________________________________________________________
void TProofChain::ReleaseProof()
{
   // Releases PROOF. Disconnect the "progress" signal.

   if (!gProof)
      return;
   gProof->Disconnect("Progress(Long64_t,Long64_t)",
                      this, "Progress(Long64_t,Long64_t)");
   if (fDrawFeedback)
      gProof->DeleteDrawFeedback(fDrawFeedback);
   fDrawFeedback = 0;
}

//______________________________________________________________________________
void TProofChain::ConnectProof()
{
   // Connects the proof - creates a "DrawFeedback" and connects the
   // "Progress" signal.

   if (gProof && !fDrawFeedback) {
      fDrawFeedback = gProof->CreateDrawFeedback();

      gProof->Connect("Progress(Long64_t,Long64_t)", "TProofChain",
                       this, "Progress(Long64_t,Long64_t)");
   }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2014 UCR-UAS
 * You should have recieved a copy of the MIT license with this file.
 * Engineer: Brandon Lu
 * Description: This is the BISON-Transfer server version.
 * What dose it do?  Tarring and insanity.
 * This is indeed a child-processed server.
 */

// ================= TODO =================
// Read the Trello cards.  (You can be added if you ask!)

// =============== Includes ===============
#include <arpa/inet.h>
#include "BISON-Defaults.h"
#include <boost/circular_buffer.hpp>
#include <boost/filesystem.hpp>
#include "config-check.h"
#include <dirent.h>
#include <errno.h>
#include <exception>
#include <fstream>
#include <list>
#include <map>
#include <netinet/in.h>
#include <openssl/md5.h>
#include "parse-command.h"
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "filetable.h"
#include <vector>
#include <yaml-cpp/yaml.h>

// ===== Terrible global variables  ========
int sfd;
int MAX_BACKLOG;
bool BISON_TRANSMIT_REALTIME;
std::string BISON_TRANSFER_ADDRESS;
int BISON_TRANSFER_PORT;
std::string BISON_TRANSFER_DIR;
int ERROR_WAIT;
int argC;
char **argV;
std::map<std::string, std::vector<unsigned char>> filetable;
YAML::Node config;

// ============ Configuration ==============
void configure_server(YAML::Node &config)
{
	try {
		config = YAML::LoadFile(__DEF_SERVER_CONFIG_PATH__
				+ std::string(__DEF_SERVER_CONFIG_FILE__));
#if DEBUG
		std::cout << "Successfully opened configuration file." << std::endl;
#endif // DEBUG
	} catch (std::exception& e) {
		std::cerr << e.what() << std::endl;
		std::cerr << "Attempting to configure automatically." << std::endl;
	}

	// configure with the default settings if the values do not exist
	YAML::Node xferConfig = config["BISON-Transfer"]["Server"];
	if (!xferConfig["PID-File"])
		xferConfig["PID-File"] = DEF_TRANSMIT_PID_FILE;
	if (!xferConfig["Transmit-Mode"])
		xferConfig["Transmit-Mode"] = DEF_BISON_TRANSMIT_MODE;
	if (!xferConfig["Bind-Address"])
		xferConfig["Bind-Address"] = DEF_BISON_TRANSFER_BIND;
	if (!xferConfig["Port"])
		xferConfig["Port"] = DEF_BISON_TRANSFER_PORT;
	if (!xferConfig["Max-Backlog"])
		xferConfig["Max-Backlog"] = DEF_MAX_BACKLOG;
	if (!xferConfig["Transmit-Dir"])
		xferConfig["Transmit-Dir"] = DEF_TRANSMIT_DIR;
	if (!xferConfig["Error-Wait"])
		xferConfig["Error-Wait"] = DEF_ERROR_WAIT;

	// set file variables to the yaml configuration variables
	std::string BISON_TRANSMIT_MODE
		= xferConfig["Transmit-Mode"].as<std::string>();
	BISON_TRANSFER_ADDRESS
		= xferConfig["Bind-Address"].as<std::string>();
	BISON_TRANSFER_PORT = xferConfig["Port"].as<int>();
	MAX_BACKLOG = xferConfig["Max-Backlog"].as<int>();
	BISON_TRANSFER_DIR
		= xferConfig["Transmit-Dir"].as<std::string>();
	ERROR_WAIT = xferConfig["Error-Wait"].as<int>();

	// if we are debugging, output the debug information
	if (DEBUG) {
		std::cout << "Transmit mode:" << BISON_TRANSMIT_MODE << std::endl;
		std::cout << "Transfer Address (for binding): "
			<< BISON_TRANSFER_ADDRESS << std::endl;
		std::cout << "Transfer port: " << BISON_TRANSFER_PORT << std::endl;
		std::cout << "Max Backlog: " << MAX_BACKLOG << std::endl;
		std::cout << "Transmitting: " << BISON_TRANSFER_DIR << std::endl;
	}

	if (strcmp(BISON_TRANSMIT_MODE.c_str(), "REALTIME") == 0) {
		BISON_TRANSMIT_REALTIME = true;
		std::cout << "Transmitting realtime." << std::endl;
	} else if (strcmp(BISON_TRANSMIT_MODE.c_str(), "QUEUE") == 0) {

	}

#if DEBUG
	printf("Writing configuration file...\n");
#endif // if DEBUG

	dirChkCreate(__DEF_SERVER_CONFIG_PATH__, "configuration");

	writeOutYaml(config, __DEF_SERVER_CONFIG_PATH__
			+ std::string(__DEF_SERVER_CONFIG_FILE__));
}

// ========= Connection Management =========
int prepare_connection()
{
	struct sockaddr_in my_addr;

	// socket it
#if DEBUG
	printf("Socketing...\n");
#endif // if DEBUG
	sfd = socket(PF_INET, SOCK_STREAM, 0);
	if (sfd == -1) {
		std::cerr << "Could not create socket." << std::endl;
		errno = 0;
		return 1;
	}

	// set things for bind
	memset (&my_addr, 0, sizeof(struct sockaddr));
	my_addr.sin_family = AF_INET;
	if (inet_aton(BISON_TRANSFER_ADDRESS.c_str(), &my_addr.sin_addr) == 0) {
		std::cerr << "Could not parse bind address." << std::endl;
		exit(1);
	}
	my_addr.sin_port = htons(BISON_TRANSFER_PORT);
	if (my_addr.sin_port == -1) {
		std::cerr << "Could not convert input port." << std::endl;
		exit(1);
	}

	// bind
#if DEBUG
	printf("Binding...\n");
#endif // if DEBUG
	if (bind(sfd, (struct sockaddr*) &my_addr, sizeof(struct sockaddr_in))
			== -1) {
		std::cerr << "Could not bind to socket." << std::endl;
		errno = 0;
		return 2;
	}

	// listen for connections
	if (listen(sfd, MAX_BACKLOG) == -1) {
		std::cerr << "Could not listen to socket." << std::endl;
		errno = 0;
		return 3;
	}

	return 0;
}

// ============ Send Filetable =============
void send_filetable(int cfd)
{
	for (std::map<std::string, std::vector<unsigned char>>::iterator
			it=filetable.begin(); it != filetable.end(); it++) {
		for (std::vector<unsigned char>::iterator iter
				= it->second.begin(); iter != it->second.end(); iter++) {
			dprintf(cfd, "%02x", *iter);	// print MD5 sum
		}
		dprintf(cfd, "  %s\n", it->first.c_str());
		// print filename
	}
	// newline termination
	dprintf(cfd, "\n");
}

// ============ Child Function =============
void child_function(int cfd)
{
	action_t action;
	std::string filename;
	parse_command(cfd, action, filename);
	switch (action) {
		case NONE:
			std::cerr << "Defunct client found." << std::endl;
			break;
		case SEND:
		{
		/* Consider this: what if the server does not have the file? TODO
*/
			FILE *send_me = fopen((BISON_TRANSFER_DIR + filename).c_str(), "r");
			if (!send_me)
			   error("Could not open file for reading.");
			int len;
			char buf[MAXBUFLEN + 1];
			while ((len = fread(buf, sizeof(char), MAXBUFLEN, send_me)) > 0)
			   write(cfd, buf, len);
		}	break;
		case FILETABLE_REQ:
			send_filetable(cfd);
			break;
		case RECALCULATE_MD5:
			recalculate_MD5(BISON_TRANSFER_DIR, filename, filetable);
			break;
	}
}

// ========== Connection Handling ==========
void handle_connection()
{
	pid_t pid;
	int cfd;
	char c;

	// Wait to accept connection
	cfd = accept(sfd, NULL, NULL);
	if (cfd == -1) {
		crit_error("Could not accept connections");
	}

	pid = fork();
	if (pid == -1)
		error("Fork");
	if (pid == 0) {							// we are the child.
		child_function(cfd);
		printf("Spawned child exiting.\n");
		shutdown(cfd, SHUT_WR);
		std::cout << "Connection shutdown." << std::endl;
		while(read(cfd, &c, 1) == 0);
		std::cout << "Connection read." << std::endl;
		close(cfd);
		std::cout << "Connection closed." << std::endl;
		exit(0);
	} else {								// we are the parent
		close(cfd);							// the child handles this
	}
}

// =========== Child Handling =============
void handle_children()
{
	// I accidentally took all the pipes out, so I'll have to reimplement -
	// them for logging... or better yet, I can just have the server listen -
	// on a socket!
}

// ======= Nice Termination handler =======
// terminate nicely!
void terminate_nicely(int sig)
{
	printf("Caught signal %i, terminating nicely.\n", sig);
	close(sfd);
	exit(0);
}

// ===== Not Nice Termination handler =====
void error_terminate(const int status)
{
	close(sfd);
	exit(status);
}

// ======= Configuration Reloading ========
void configuration_reload(int sig)
{
	configure_server(config);
}

// =========== Signal Handling ============
void signalHandling()
{
	signal(SIGHUP, configuration_reload);
	signal(SIGTERM, terminate_nicely);
	signal(SIGINT, terminate_nicely);
	signal(SIGCHLD, SIG_IGN);				// IGNORE YOUR CHILDREN.
}

// ========== The Main Function ============
int main (int argc, char *argv[])
{
	configure_server(config);

	signalHandling();

#if DEBUG
	printf("Checking if transmission directory exists...\n");
#endif // if DEBUG
	dirChkCreate(BISON_TRANSFER_DIR.c_str(), "transfer");

	printf("Server Starting Up...\n");

	// Insert PID file management stuff here

	// keep on preparing the connection until it is prepared.
	while (1) {
		if (!prepare_connection())
			break;
		for (int i = 0; i > ERROR_WAIT; i++)
			usleep(1000);
	}

#if DEBUG
	printf("Server ready, waiting for connection.\n");
#endif // if DEBUG

	// Loop to keep accepting connections
	while (1) {
		const char* ret = update_filetable(BISON_TRANSFER_DIR, filetable);
		if (ret) {
			std::cerr << "Error on filetable update: " << ret << std::endl;
		}
		handle_connection();
		usleep(5000);					// wait a bit so that we won't -
		// overload the system
	}

	return 0;
}
<commit_msg>Made server authoritavely close.<commit_after>/* Copyright (c) 2014 UCR-UAS
 * You should have recieved a copy of the MIT license with this file.
 * Engineer: Brandon Lu
 * Description: This is the BISON-Transfer server version.
 * What dose it do?  Tarring and insanity.
 * This is indeed a child-processed server.
 */

// ================= TODO =================
// Read the Trello cards.  (You can be added if you ask!)

// =============== Includes ===============
#include <arpa/inet.h>
#include "BISON-Defaults.h"
#include <boost/circular_buffer.hpp>
#include <boost/filesystem.hpp>
#include "config-check.h"
#include <dirent.h>
#include <errno.h>
#include <exception>
#include <fstream>
#include <list>
#include <map>
#include <netinet/in.h>
#include <openssl/md5.h>
#include "parse-command.h"
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "filetable.h"
#include <vector>
#include <yaml-cpp/yaml.h>

// ===== Terrible global variables  ========
int sfd;
int MAX_BACKLOG;
bool BISON_TRANSMIT_REALTIME;
std::string BISON_TRANSFER_ADDRESS;
int BISON_TRANSFER_PORT;
std::string BISON_TRANSFER_DIR;
int ERROR_WAIT;
int argC;
char **argV;
std::map<std::string, std::vector<unsigned char>> filetable;
YAML::Node config;

// ============ Configuration ==============
void configure_server(YAML::Node &config)
{
	try {
		config = YAML::LoadFile(__DEF_SERVER_CONFIG_PATH__
				+ std::string(__DEF_SERVER_CONFIG_FILE__));
#if DEBUG
		std::cout << "Successfully opened configuration file." << std::endl;
#endif // DEBUG
	} catch (std::exception& e) {
		std::cerr << e.what() << std::endl;
		std::cerr << "Attempting to configure automatically." << std::endl;
	}

	// configure with the default settings if the values do not exist
	YAML::Node xferConfig = config["BISON-Transfer"]["Server"];
	if (!xferConfig["PID-File"])
		xferConfig["PID-File"] = DEF_TRANSMIT_PID_FILE;
	if (!xferConfig["Transmit-Mode"])
		xferConfig["Transmit-Mode"] = DEF_BISON_TRANSMIT_MODE;
	if (!xferConfig["Bind-Address"])
		xferConfig["Bind-Address"] = DEF_BISON_TRANSFER_BIND;
	if (!xferConfig["Port"])
		xferConfig["Port"] = DEF_BISON_TRANSFER_PORT;
	if (!xferConfig["Max-Backlog"])
		xferConfig["Max-Backlog"] = DEF_MAX_BACKLOG;
	if (!xferConfig["Transmit-Dir"])
		xferConfig["Transmit-Dir"] = DEF_TRANSMIT_DIR;
	if (!xferConfig["Error-Wait"])
		xferConfig["Error-Wait"] = DEF_ERROR_WAIT;

	// set file variables to the yaml configuration variables
	std::string BISON_TRANSMIT_MODE
		= xferConfig["Transmit-Mode"].as<std::string>();
	BISON_TRANSFER_ADDRESS
		= xferConfig["Bind-Address"].as<std::string>();
	BISON_TRANSFER_PORT = xferConfig["Port"].as<int>();
	MAX_BACKLOG = xferConfig["Max-Backlog"].as<int>();
	BISON_TRANSFER_DIR
		= xferConfig["Transmit-Dir"].as<std::string>();
	ERROR_WAIT = xferConfig["Error-Wait"].as<int>();

	// if we are debugging, output the debug information
	if (DEBUG) {
		std::cout << "Transmit mode:" << BISON_TRANSMIT_MODE << std::endl;
		std::cout << "Transfer Address (for binding): "
			<< BISON_TRANSFER_ADDRESS << std::endl;
		std::cout << "Transfer port: " << BISON_TRANSFER_PORT << std::endl;
		std::cout << "Max Backlog: " << MAX_BACKLOG << std::endl;
		std::cout << "Transmitting: " << BISON_TRANSFER_DIR << std::endl;
	}

	if (strcmp(BISON_TRANSMIT_MODE.c_str(), "REALTIME") == 0) {
		BISON_TRANSMIT_REALTIME = true;
		std::cout << "Transmitting realtime." << std::endl;
	} else if (strcmp(BISON_TRANSMIT_MODE.c_str(), "QUEUE") == 0) {

	}

#if DEBUG
	printf("Writing configuration file...\n");
#endif // if DEBUG

	dirChkCreate(__DEF_SERVER_CONFIG_PATH__, "configuration");

	writeOutYaml(config, __DEF_SERVER_CONFIG_PATH__
			+ std::string(__DEF_SERVER_CONFIG_FILE__));
}

// ========= Connection Management =========
int prepare_connection()
{
	struct sockaddr_in my_addr;

	// socket it
#if DEBUG
	printf("Socketing...\n");
#endif // if DEBUG
	sfd = socket(PF_INET, SOCK_STREAM, 0);
	if (sfd == -1) {
		std::cerr << "Could not create socket." << std::endl;
		errno = 0;
		return 1;
	}

	// set things for bind
	memset (&my_addr, 0, sizeof(struct sockaddr));
	my_addr.sin_family = AF_INET;
	if (inet_aton(BISON_TRANSFER_ADDRESS.c_str(), &my_addr.sin_addr) == 0) {
		std::cerr << "Could not parse bind address." << std::endl;
		exit(1);
	}
	my_addr.sin_port = htons(BISON_TRANSFER_PORT);
	if (my_addr.sin_port == -1) {
		std::cerr << "Could not convert input port." << std::endl;
		exit(1);
	}

	// bind
#if DEBUG
	printf("Binding...\n");
#endif // if DEBUG
	if (bind(sfd, (struct sockaddr*) &my_addr, sizeof(struct sockaddr_in))
			== -1) {
		std::cerr << "Could not bind to socket." << std::endl;
		errno = 0;
		return 2;
	}

	// listen for connections
	if (listen(sfd, MAX_BACKLOG) == -1) {
		std::cerr << "Could not listen to socket." << std::endl;
		errno = 0;
		return 3;
	}

	return 0;
}

// ============ Send Filetable =============
void send_filetable(int cfd)
{
	for (std::map<std::string, std::vector<unsigned char>>::iterator
			it=filetable.begin(); it != filetable.end(); it++) {
		for (std::vector<unsigned char>::iterator iter
				= it->second.begin(); iter != it->second.end(); iter++) {
			dprintf(cfd, "%02x", *iter);	// print MD5 sum
		}
		dprintf(cfd, "  %s\n", it->first.c_str());
		// print filename
	}
	// newline termination
	dprintf(cfd, "\n");
}

// ============ Child Function =============
void child_function(int cfd)
{
	action_t action;
	std::string filename;
	parse_command(cfd, action, filename);
	switch (action) {
		case NONE:
			std::cerr << "Defunct client found." << std::endl;
			break;
		case SEND:
		{
		/* Consider this: what if the server does not have the file? TODO
*/
			FILE *send_me = fopen((BISON_TRANSFER_DIR + filename).c_str(), "r");
			if (!send_me)
			   error("Could not open file for reading.");
			int len;
			char buf[MAXBUFLEN + 1];
			while ((len = fread(buf, sizeof(char), MAXBUFLEN, send_me)) > 0)
			   write(cfd, buf, len);
		}	break;
		case FILETABLE_REQ:
			send_filetable(cfd);
			break;
		case RECALCULATE_MD5:
			recalculate_MD5(BISON_TRANSFER_DIR, filename, filetable);
			break;
	}
}

// ========== Connection Handling ==========
void handle_connection()
{
	pid_t pid;
	int cfd;
	char c;

	// Wait to accept connection
	cfd = accept(sfd, NULL, NULL);
	if (cfd == -1) {
		crit_error("Could not accept connections");
	}

	pid = fork();
	if (pid == -1)
		error("Fork");
	if (pid == 0) {							// we are the child.
		child_function(cfd);
		printf("Spawned child exiting.\n");
		shutdown(cfd, SHUT_RDWR);
		std::cout << "Connection shutdown." << std::endl;
		close(cfd);
		std::cout << "Connection closed." << std::endl;
		exit(0);
	} else {								// we are the parent
		close(cfd);							// the child handles this
	}
}

// =========== Child Handling =============
void handle_children()
{
	// I accidentally took all the pipes out, so I'll have to reimplement -
	// them for logging... or better yet, I can just have the server listen -
	// on a socket!
}

// ======= Nice Termination handler =======
// terminate nicely!
void terminate_nicely(int sig)
{
	printf("Caught signal %i, terminating nicely.\n", sig);
	close(sfd);
	exit(0);
}

// ===== Not Nice Termination handler =====
void error_terminate(const int status)
{
	close(sfd);
	exit(status);
}

// ======= Configuration Reloading ========
void configuration_reload(int sig)
{
	configure_server(config);
}

// =========== Signal Handling ============
void signalHandling()
{
	signal(SIGHUP, configuration_reload);
	signal(SIGTERM, terminate_nicely);
	signal(SIGINT, terminate_nicely);
	signal(SIGCHLD, SIG_IGN);				// IGNORE YOUR CHILDREN.
}

// ========== The Main Function ============
int main (int argc, char *argv[])
{
	configure_server(config);

	signalHandling();

#if DEBUG
	printf("Checking if transmission directory exists...\n");
#endif // if DEBUG
	dirChkCreate(BISON_TRANSFER_DIR.c_str(), "transfer");

	printf("Server Starting Up...\n");

	// Insert PID file management stuff here

	// keep on preparing the connection until it is prepared.
	while (1) {
		if (!prepare_connection())
			break;
		for (int i = 0; i > ERROR_WAIT; i++)
			usleep(1000);
	}

#if DEBUG
	printf("Server ready, waiting for connection.\n");
#endif // if DEBUG

	// Loop to keep accepting connections
	while (1) {
		const char* ret = update_filetable(BISON_TRANSFER_DIR, filetable);
		if (ret) {
			std::cerr << "Error on filetable update: " << ret << std::endl;
		}
		handle_connection();
		usleep(5000);					// wait a bit so that we won't -
		// overload the system
	}

	return 0;
}
<|endoftext|>


<commit_before>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include <time.h>
#include "Log.h"

cMCLogger * cMCLogger::s_MCLogger = NULL;

#ifdef _WIN32
	HANDLE g_Console = GetStdHandle(STD_OUTPUT_HANDLE);
#endif

cMCLogger* cMCLogger::GetInstance()
{
	return s_MCLogger;
}

cMCLogger::cMCLogger(void)
{
	AString FileName;
	Printf(FileName, "LOG_%d.txt", (int)time(NULL));
	m_Log = new cLog(FileName);
	m_Log->Log("--- Started Log ---");

	s_MCLogger = this;
}

cMCLogger::cMCLogger(const AString & a_FileName)
{
	m_Log = new cLog(a_FileName);
}

cMCLogger::~cMCLogger()
{
	m_Log->Log("--- Stopped Log ---");
	delete m_Log;
	if (this == s_MCLogger)
		s_MCLogger = NULL;
}

void cMCLogger::LogSimple(const char* a_Text, int a_LogType /* = 0 */ )
{
	switch( a_LogType )
	{
		case 0:
			LOG("%s", a_Text);
			break;
		case 1:
			LOGINFO("%s", a_Text);
			break;
		case 2:
			LOGWARN("%s", a_Text);
			break;
		case 3:
			LOGERROR("%s", a_Text);
			break;
		default:
			LOG("(#%d#: %s", a_LogType, a_Text);
			break;
	}
}

void cMCLogger::Log(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csGrayOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Info(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csYellowOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Warn(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csRedOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Error(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csBlackOnRed);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::SetColor(eColorScheme a_Scheme)
{
	#ifdef _WIN32
		WORD Attrib = 0x07;  // by default, gray on black
		switch (a_Scheme)
		{
			case csGrayOnBlack:   Attrib = 0x07; break;
			case csYellowOnBlack: Attrib = 0x0e; break;
			case csRedOnBlack:    Attrib = 0x0c; break;
			case csBlackOnRed:    Attrib = 0xc0; break;
			default: ASSERT(!"Unhandled color scheme");
		}
		SetConsoleTextAttribute(g_Console, Attrib);
	#elif defined(LINUX) && !defined(ANDROID_NDK)
		switch (a_Scheme)
		{
			case csGrayOnBlack:   puts("\x1b[0m");    break;
			case csYellowOnBlack: puts("\x1b[33;1m"); break;
			case csRedOnBlack:    puts("\x1b[31;1m"); break;
			case csBlackOnRed:    puts("\x1b[7;31;1m"); break;
			default: ASSERT(!"Unhandled color scheme");
		}
	#endif
}

//////////////////////////////////////////////////////////////////////////
// Global functions
void LOG(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Log( a_Format, argList );
	va_end(argList);
}

void LOGINFO(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Info( a_Format, argList );
	va_end(argList);
}

void LOGWARN(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Warn( a_Format, argList );
	va_end(argList);
}

void LOGERROR(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Error( a_Format, argList );
	va_end(argList);
}

<commit_msg>Bad preprocesor used for discovering Linux<commit_after>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include <time.h>
#include "Log.h"

cMCLogger * cMCLogger::s_MCLogger = NULL;

#ifdef _WIN32
	HANDLE g_Console = GetStdHandle(STD_OUTPUT_HANDLE);
#endif

cMCLogger* cMCLogger::GetInstance()
{
	return s_MCLogger;
}

cMCLogger::cMCLogger(void)
{
	AString FileName;
	Printf(FileName, "LOG_%d.txt", (int)time(NULL));
	m_Log = new cLog(FileName);
	m_Log->Log("--- Started Log ---");

	s_MCLogger = this;
}

cMCLogger::cMCLogger(const AString & a_FileName)
{
	m_Log = new cLog(a_FileName);
}

cMCLogger::~cMCLogger()
{
	m_Log->Log("--- Stopped Log ---");
	delete m_Log;
	if (this == s_MCLogger)
		s_MCLogger = NULL;
}

void cMCLogger::LogSimple(const char* a_Text, int a_LogType /* = 0 */ )
{
	switch( a_LogType )
	{
		case 0:
			LOG("%s", a_Text);
			break;
		case 1:
			LOGINFO("%s", a_Text);
			break;
		case 2:
			LOGWARN("%s", a_Text);
			break;
		case 3:
			LOGERROR("%s", a_Text);
			break;
		default:
			LOG("(#%d#: %s", a_LogType, a_Text);
			break;
	}
}

void cMCLogger::Log(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csGrayOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Info(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csYellowOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Warn(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csRedOnBlack);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::Error(const char * a_Format, va_list a_ArgList)
{
	cCSLock Lock(m_CriticalSection);
	SetColor(csBlackOnRed);
	m_Log->Log(a_Format, a_ArgList);
}

void cMCLogger::SetColor(eColorScheme a_Scheme)
{
	#ifdef _WIN32
		WORD Attrib = 0x07;  // by default, gray on black
		switch (a_Scheme)
		{
			case csGrayOnBlack:   Attrib = 0x07; break;
			case csYellowOnBlack: Attrib = 0x0e; break;
			case csRedOnBlack:    Attrib = 0x0c; break;
			case csBlackOnRed:    Attrib = 0xc0; break;
			default: ASSERT(!"Unhandled color scheme");
		}
		SetConsoleTextAttribute(g_Console, Attrib);
	#elif defined(__linux) && !defined(ANDROID_NDK)
		switch (a_Scheme)
		{
			case csGrayOnBlack:   puts("\x1b[0m");    break;
			case csYellowOnBlack: puts("\x1b[33;1m"); break;
			case csRedOnBlack:    puts("\x1b[31;1m"); break;
			case csBlackOnRed:    puts("\x1b[7;31;1m"); break;
			default: ASSERT(!"Unhandled color scheme");
		}
	#endif
}

//////////////////////////////////////////////////////////////////////////
// Global functions
void LOG(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Log( a_Format, argList );
	va_end(argList);
}

void LOGINFO(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Info( a_Format, argList );
	va_end(argList);
}

void LOGWARN(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Warn( a_Format, argList );
	va_end(argList);
}

void LOGERROR(const char* a_Format, ...)
{
	va_list argList;
	va_start(argList, a_Format);
	cMCLogger::GetInstance()->Error( a_Format, argList );
	va_end(argList);
}

<|endoftext|>