<commit_before>#include "mainpatch.h"

#include "console/windows_wrap.h"
#include <time.h>

#include "patchmanager.h"
#include "memory.h"
#include "offsets.h"
#include "commands.h"
#include "unit.h"
#include "text.h"
#include "selection.h"
#include "order.h"
#include "limits.h"
#include "targeting.h"
#include "draw.h"
#include "scthread.h"
#include "log.h"
#include "unitlist.h"
#include "bullet.h"
#include "ai.h"
#include "triggers.h"
#include "scconsole.h"
#include "bullet.h"
#include "sprite.h"
#include "building.h"
#include "replay.h"
#include "yms.h"
#include "unit_cache.h"
#include "perfclock.h"
#include "common/log_freeze.h"

namespace bw
{
    namespace storm
    {
        intptr_t base_diff;
    }
}

void WindowCreatedPatch()
{
    #ifdef CONSOLE
    Common::console->HookWndProc(*bw::main_window_hwnd);
    #endif
}

void WinMainPatch()
{
    Common::PatchContext patch = patch_mgr->BeginPatch(0, bw::base::starcraft);
    PatchDraw(&patch);
    #ifdef CONSOLE
    PatchConsole();
    Common::console->HookTranslateAccelerator(&patch, bw::base::starcraft);
    #endif
}

uint32_t GetRngSeed()
{
    uint32_t seed;
    if (StaticSeed)
        seed = StaticSeed;
    else if (SyncTest)
        seed = 0;
    else
        seed = time(0);

    debug_log->Log("Rng seed %08x\n", seed);
    return seed;
}

uint32_t __stdcall VersionCheckGuard(uint8_t *a, void *b, void *c, void *d, void *e)
{
    patch_mgr->Unpatch();
    uint32_t ret = SNetInitializeProvider(a, b, c, d, e);
    patch_mgr->Repatch();
    return ret;
}

static void SavePanickedReplay()
{
    if (!IsInGame())
        return;
    // Add some frames (1 should be enough) to make crash surely reproductable
    bw::replay_header[0].replay_end_frame = *bw::frame_count + 50;
    SaveReplay("crash", 1);
}

static LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter = nullptr;
static LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS *info)
{
    LONG result = EXCEPTION_CONTINUE_SEARCH;
    if (previous_exception_filter)
        result = previous_exception_filter(info);

    SavePanickedReplay();
    // Terminate on debug because why not - release crashes properly so people won't get confused
    if (Debug && result != EXCEPTION_CONTINUE_EXECUTION)
        TerminateProcess(GetCurrentProcess(), info->ExceptionRecord->ExceptionCode);

    return result;
}

struct DetectFreeze
{
    DetectFreeze() : last_value(draw_counter.load(std::memory_order_acquire)) {}
    bool operator()()
    {
        if (!IsInGame())
            return false;
        uintptr_t new_value = draw_counter.load(std::memory_order_acquire);
        bool frozen = new_value == last_value;
        last_value = new_value;
        return frozen;
    }
    uintptr_t last_value;
};

static void InitFreezeLogging()
{
    HANDLE thread_handle;
    auto success = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
            &thread_handle, 0, FALSE, DUPLICATE_SAME_ACCESS);
    if (success == 0)
    {
        char buf[64];
        auto error = GetLastError();
        snprintf(buf, sizeof buf, "DuplicateHandle: %x (%d)", error, error);
        // Show a noisy error instead of easily missed log line
        MessageBoxA(0, buf, "InitFreezeLogging failed", 0);
    }
    else
    {
        new FreezeLogger(thread_handle, "Errors/freeze.log", DetectFreeze(), [](const std::string &msg) {
            MessageBoxA(0, "InitFreezeLogging failed", msg.c_str(), 0);
        });
    }
}

void InitialPatch()
{
    InitLogs();
    InitSystemInfo();
    InitPerfClockFrequency();
    InitFreezeLogging();

    threads = new ThreadPool<ScThreadVars>;
    threads->Init(sysinfo.dwNumberOfProcessors * 2);
    int thread_count = threads->GetThreadCount();
    perf_log->Log("Thread amount: %d\n", thread_count);

    patch_mgr = new Common::PatchManager;
    Common::PatchContext patch = patch_mgr->BeginPatch(nullptr, bw::base::starcraft);

    patch.Patch(bw::WinMain, (void *)&WinMainPatch, 0, PATCH_HOOKBEFORE | PATCH_CALLHOOK);
    patch.Patch(bw::WindowCreated, (void *)&WindowCreatedPatch, 0, PATCH_HOOKBEFORE | PATCH_SAFECALLHOOK);

    PatchProcessCommands(&patch);
    PatchSelection(&patch);
    PatchTargeting(&patch);
    RemoveLimits(&patch);
    patch.Patch(bw::RngSeedPatch, 0, 9, PATCH_NOP);
    patch.Patch(bw::RngSeedPatch, (void *)&GetRngSeed, 0, PATCH_CALLHOOK);
    patch.JumpHook(bw::UpdateBuildingPlacementState, UpdateBuildingPlacementState);

    Common::PatchContext storm_patch = patch_mgr->BeginPatch("storm", bw::base::storm);
    bw::storm::base_diff = storm_patch.GetDiff();
    // #117 is SNetInitializeProvider
    storm_patch.Patch((void *)GetProcAddress(GetModuleHandle("storm"), (char *)117), (void *)&VersionCheckGuard, 0, PATCH_JMPHOOK);

    if (UseConsole)
        patch.JumpHook(bw::GenerateFog, GenerateFog);

    bullet_system = new BulletSystem;
    lone_sprites = new LoneSpriteSystem;
    enemy_unit_cache = new EnemyUnitCache;

    previous_exception_filter = SetUnhandledExceptionFilter(&ExceptionFilter);
}
<commit_msg>Create unique win32 event that can be used to tell if the hack is applied<commit_after>#include "mainpatch.h"

#include "console/windows_wrap.h"
#include <time.h>

#include "patchmanager.h"
#include "memory.h"
#include "offsets.h"
#include "commands.h"
#include "unit.h"
#include "text.h"
#include "selection.h"
#include "order.h"
#include "limits.h"
#include "targeting.h"
#include "draw.h"
#include "scthread.h"
#include "log.h"
#include "unitlist.h"
#include "bullet.h"
#include "ai.h"
#include "triggers.h"
#include "scconsole.h"
#include "bullet.h"
#include "sprite.h"
#include "building.h"
#include "replay.h"
#include "yms.h"
#include "unit_cache.h"
#include "perfclock.h"
#include "common/log_freeze.h"

namespace bw
{
    namespace storm
    {
        intptr_t base_diff;
    }
}

void WindowCreatedPatch()
{
    #ifdef CONSOLE
    Common::console->HookWndProc(*bw::main_window_hwnd);
    #endif
}

void WinMainPatch()
{
    Common::PatchContext patch = patch_mgr->BeginPatch(0, bw::base::starcraft);
    PatchDraw(&patch);
    #ifdef CONSOLE
    PatchConsole();
    Common::console->HookTranslateAccelerator(&patch, bw::base::starcraft);
    #endif
}

uint32_t GetRngSeed()
{
    uint32_t seed;
    if (StaticSeed)
        seed = StaticSeed;
    else if (SyncTest)
        seed = 0;
    else
        seed = time(0);

    debug_log->Log("Rng seed %08x\n", seed);
    return seed;
}

uint32_t __stdcall VersionCheckGuard(uint8_t *a, void *b, void *c, void *d, void *e)
{
    patch_mgr->Unpatch();
    uint32_t ret = SNetInitializeProvider(a, b, c, d, e);
    patch_mgr->Repatch();
    return ret;
}

static void SavePanickedReplay()
{
    if (!IsInGame())
        return;
    // Add some frames (1 should be enough) to make crash surely reproductable
    bw::replay_header[0].replay_end_frame = *bw::frame_count + 50;
    SaveReplay("crash", 1);
}

static LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter = nullptr;
static LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS *info)
{
    LONG result = EXCEPTION_CONTINUE_SEARCH;
    if (previous_exception_filter)
        result = previous_exception_filter(info);

    SavePanickedReplay();
    // Terminate on debug because why not - release crashes properly so people won't get confused
    if (Debug && result != EXCEPTION_CONTINUE_EXECUTION)
        TerminateProcess(GetCurrentProcess(), info->ExceptionRecord->ExceptionCode);

    return result;
}

struct DetectFreeze
{
    DetectFreeze() : last_value(draw_counter.load(std::memory_order_acquire)) {}
    bool operator()()
    {
        if (!IsInGame())
            return false;
        uintptr_t new_value = draw_counter.load(std::memory_order_acquire);
        bool frozen = new_value == last_value;
        last_value = new_value;
        return frozen;
    }
    uintptr_t last_value;
};

static void InitFreezeLogging()
{
    HANDLE thread_handle;
    auto success = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
            &thread_handle, 0, FALSE, DUPLICATE_SAME_ACCESS);
    if (success == 0)
    {
        char buf[64];
        auto error = GetLastError();
        snprintf(buf, sizeof buf, "DuplicateHandle: %x (%d)", error, error);
        // Show a noisy error instead of easily missed log line
        MessageBoxA(0, buf, "InitFreezeLogging failed", 0);
    }
    else
    {
        new FreezeLogger(thread_handle, "Errors/freeze.log", DetectFreeze(), [](const std::string &msg) {
            MessageBoxA(0, "InitFreezeLogging failed", msg.c_str(), 0);
        });
    }
}

static void CreateIdentifyingEvent()
{
    char buf[32];
    auto pid = GetCurrentProcessId();
    snprintf(buf, sizeof buf, "Teippi #%d", pid);
    CreateEventA(NULL, FALSE, FALSE, buf);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        // Maybe should silently abort patching?
        MessageBoxA(0, "Second copy of Teippi has been loaded to same process.\n\
Crashing is very likely.", "Very important warning", 0);
    }
}

void InitialPatch()
{
    CreateIdentifyingEvent();
    InitLogs();
    InitSystemInfo();
    InitPerfClockFrequency();
    InitFreezeLogging();

    threads = new ThreadPool<ScThreadVars>;
    threads->Init(sysinfo.dwNumberOfProcessors * 2);
    int thread_count = threads->GetThreadCount();
    perf_log->Log("Thread amount: %d\n", thread_count);

    patch_mgr = new Common::PatchManager;
    Common::PatchContext patch = patch_mgr->BeginPatch(nullptr, bw::base::starcraft);

    patch.Patch(bw::WinMain, (void *)&WinMainPatch, 0, PATCH_HOOKBEFORE | PATCH_CALLHOOK);
    patch.Patch(bw::WindowCreated, (void *)&WindowCreatedPatch, 0, PATCH_HOOKBEFORE | PATCH_SAFECALLHOOK);

    PatchProcessCommands(&patch);
    PatchSelection(&patch);
    PatchTargeting(&patch);
    RemoveLimits(&patch);
    patch.Patch(bw::RngSeedPatch, 0, 9, PATCH_NOP);
    patch.Patch(bw::RngSeedPatch, (void *)&GetRngSeed, 0, PATCH_CALLHOOK);
    patch.JumpHook(bw::UpdateBuildingPlacementState, UpdateBuildingPlacementState);

    Common::PatchContext storm_patch = patch_mgr->BeginPatch("storm", bw::base::storm);
    bw::storm::base_diff = storm_patch.GetDiff();
    // #117 is SNetInitializeProvider
    storm_patch.Patch((void *)GetProcAddress(GetModuleHandle("storm"), (char *)117), (void *)&VersionCheckGuard, 0, PATCH_JMPHOOK);

    if (UseConsole)
        patch.JumpHook(bw::GenerateFog, GenerateFog);

    bullet_system = new BulletSystem;
    lone_sprites = new LoneSpriteSystem;
    enemy_unit_cache = new EnemyUnitCache;

    previous_exception_filter = SetUnhandledExceptionFilter(&ExceptionFilter);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"

class Parallel2Test : testing::Test { };

TEST(Parallel2Test, Test1)
{
	std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
	ASSERT_EQ(f1.get(), 10);
}

TEST(Parallel2Test, Test2)
{
	auto f1 = asyncply::async([](){return 15;});
	auto f2 = f1->then([](int data) {
		std::cout << "post, received: " << data << std::endl;
		return data + 6;
	});
	ASSERT_EQ(f2->get(), 15 + 6);
}

TEST(Parallel2Test, Test3)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test3_async)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	auto task = asyncply::for_each(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	task->get();
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test4)
{
	double total_ps = asyncply::parallel_sync(
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		},
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		}
	);
	ASSERT_EQ(total_ps, 6);
}

TEST(Parallel2Test, Test5)
{
	std::atomic<int> total;
	total = 0;
	auto process = asyncply::parallel(
				[&total]()
				{
					std::cout << "hi" << std::endl;
					total += 1;
				},
				[&total]()
				{
					std::cout << "bye" << std::endl;
					total += 1;
				}
			);
	auto process2 = process->then([&total]()
			{
				std::cout << "no accum" << std::endl;
				total += 1;
			});
	process2->get();
	ASSERT_EQ(total, 3);
}

TEST(Parallel2Test, Test6)
{
	std::atomic<int> total;
	total = 0;
	{
		auto process = asyncply::parallel(
					[&total]()
					{
						std::cout << "hi" << std::endl;
						total += 1;
					},
					[&total]()
					{
						std::cout << "bye" << std::endl;
						total += 1;
					}
				);
		auto process_then = process->then([&total]()
				{
					std::cout << "no accum" << std::endl;
					total += 1;
				});
		process_then->get();
	}
	ASSERT_EQ(total, 3);
}
<commit_msg>Update test_parallel2.cpp<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"

class Parallel2Test : testing::Test { };

TEST(Parallel2Test, Test1)
{
	std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
	ASSERT_EQ(f1.get(), 10);
}

TEST(Parallel2Test, Test2)
{
	auto f1 = asyncply::async([](){return 15;});
	auto f2 = f1->then([](int data) {
		std::cout << "post, received: " << data << std::endl;
		return data + 6;
	});
	ASSERT_EQ(f2->get(), 15 + 6);
}

TEST(Parallel2Test, Test3)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test3_async)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	auto task = asyncply::for_each(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	task->get();
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, collapse_double)
{
	double total_ps = asyncply::parallel_sync(
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		},
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		}
	);
	ASSERT_EQ(total_ps, 6);
}

TEST(Parallel2Test, collapse_bool)
{
	bool result = asyncply::parallel_sync(
		[]()
		{
			return asyncply::sequence(true,
				[](bool data)
				{
					return data;
				},
				[](bool data)
				{
					return data;
				});
		},
		[]()
		{
			return asyncply::sequence(false,
				[](bool data)
				{
					return data;
				},
				[](bool data)
				{
					return data;
				});
		}
	);
	ASSERT_EQ(result, false);
}

TEST(Parallel2Test, Test5)
{
	std::atomic<int> total;
	total = 0;
	auto process = asyncply::parallel(
				[&total]()
				{
					std::cout << "hi" << std::endl;
					total += 1;
				},
				[&total]()
				{
					std::cout << "bye" << std::endl;
					total += 1;
				}
			);
	auto process2 = process->then([&total]()
			{
				std::cout << "no accum" << std::endl;
				total += 1;
			});
	process2->get();
	ASSERT_EQ(total, 3);
}

TEST(Parallel2Test, Test6)
{
	std::atomic<int> total;
	total = 0;
	{
		auto process = asyncply::parallel(
					[&total]()
					{
						std::cout << "hi" << std::endl;
						total += 1;
					},
					[&total]()
					{
						std::cout << "bye" << std::endl;
						total += 1;
					}
				);
		auto process_then = process->then([&total]()
				{
					std::cout << "no accum" << std::endl;
					total += 1;
				});
		process_then->get();
	}
	ASSERT_EQ(total, 3);
}
<|endoftext|>


<commit_before>#include <cstdio>

int main(){
    char o;
    int i, j, c;
    float s = 0.0, n;
    scanf("%d", &c);
    scanf("%s", &o);
    for (i = 0; i <= 11; i++){
        for (j = 0; j <= 11; j++){
            scanf("%f", &n);
            if (j == c){
                s += n;
            }
        }
    }
    if (o == 'S')
        printf("%.1f\n", s);
    else
        printf("%.1f\n", s / 12);
    return 0;
}
<commit_msg>Corrige e reformata.<commit_after>#include <cstdio>

int main() {
    char o;
    int i, j, c;
    float s = 0.0, n;

    scanf("%d ", &c);
    scanf("%c", &o);

    for (i = 0; i <= 11; i++) {
        for (j = 0; j <= 11; j++) {
            scanf("%f", &n);
            if (j == c) s += n;
        }
    }

    if (o == 'S') printf("%.1f\n", s);
    else printf("%.1f\n", s / 12);

    return 0;
}
<|endoftext|>


<commit_before>
#include "LightApp_ShowHideOp.h"
#include "LightApp_Application.h"
#include "LightApp_DataOwner.h"
#include "LightApp_Module.h"
#include "LightApp_Study.h"
#include "LightApp_Displayer.h"
#include "CAM_Study.h"

#include "LightApp_SelectionMgr.h"
#include "LightApp_Selection.h"

#include <SALOME_ListIO.hxx>
#include <SALOME_ListIteratorOfListIO.hxx>

LightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )
: LightApp_Operation(),
  myActionType( type )
{
}

LightApp_ShowHideOp::~LightApp_ShowHideOp()
{
}

LightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const
{
  LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
  LightApp_Module* m = dynamic_cast<LightApp_Module*>( app ? app->module( mod_name ) : 0 );
  if( !m )
  {
    m = dynamic_cast<LightApp_Module*>( app->loadModule( mod_name ) );
    if( m )
      app->addModule( m );
  }

  if( m )
  {
    m->connectToStudy( dynamic_cast<CAM_Study*>( app->activeStudy() ) );
    m->setMenuShown( false );
    m->setToolShown( false );
  }
  return m ? m->displayer() : 0;
}

void LightApp_ShowHideOp::startOperation()
{
  LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
  LightApp_Study* study = app ? dynamic_cast<LightApp_Study*>( app->activeStudy() ) : 0;
  if( !app || !study )
  {
    abort();
    return;
  }

  LightApp_SelectionMgr* mgr = app->selectionMgr();
  LightApp_Selection sel; sel.init( "", mgr );
  if( sel.count()==0 && myActionType!=ERASE_ALL )
  {
    abort();
    return;
  }
  QString aStr =  sel.param( 0, "component" ).toString();
  QString mod_name = app->moduleTitle( aStr );//sel.param( 0, "component" ).toString() );
  LightApp_Displayer* d = displayer( mod_name );
  if( !d )
  {
    abort();
    return;
  }

  if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )
  {
    //ERASE ALL
    QStringList comps;
    study->components( comps );
    QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();
    for( ; anIt!=aLast; anIt++ )
    {
      LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );
      if( disp )
	disp->EraseAll( false, false, 0 );
    }
    if( myActionType==ERASE_ALL )
    {
      d->UpdateViewer();
      commit();
      return;
    }
  }

  SALOME_ListIO selObjs;
  mgr->selectedObjects( selObjs );

  QStringList entries;
  SALOME_ListIteratorOfListIO anIt( selObjs );
  for( ; anIt.More(); anIt.Next() )
  {
    if( anIt.Value().IsNull() )
      continue;

    if( study->isComponent( anIt.Value()->getEntry() ) )
      study->children( anIt.Value()->getEntry(), entries );
    else
      entries.append( anIt.Value()->getEntry() );
  }

  for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )
  {
    QString e = study->referencedToEntry( *it );
    if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )
      d->Display( e, false, 0 );
    else if( myActionType==ERASE )
      d->Erase( e, false, false, 0 );
  }
  d->UpdateViewer();
  commit();
}
<commit_msg>PAL10533 - main menu is changed after DisplayOnly operation for object from other module<commit_after>
#include "LightApp_ShowHideOp.h"
#include "LightApp_Application.h"
#include "LightApp_DataOwner.h"
#include "LightApp_Module.h"
#include "LightApp_Study.h"
#include "LightApp_Displayer.h"
#include "CAM_Study.h"

#include "LightApp_SelectionMgr.h"
#include "LightApp_Selection.h"

#include <SALOME_ListIO.hxx>
#include <SALOME_ListIteratorOfListIO.hxx>

LightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )
: LightApp_Operation(),
  myActionType( type )
{
}

LightApp_ShowHideOp::~LightApp_ShowHideOp()
{
}

LightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const
{
  LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
  LightApp_Module* m = dynamic_cast<LightApp_Module*>( app ? app->module( mod_name ) : 0 );
  if( !m )
  {
    m = dynamic_cast<LightApp_Module*>( app->loadModule( mod_name ) );
    if( m )
      app->addModule( m );
  }

  if( m )
  {
    m->connectToStudy( dynamic_cast<CAM_Study*>( app->activeStudy() ) );
    if( m!=app->activeModule() )
    {
      m->setMenuShown( false );
      m->setToolShown( false );
    }
  }
  return m ? m->displayer() : 0;
}

void LightApp_ShowHideOp::startOperation()
{
  LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
  LightApp_Study* study = app ? dynamic_cast<LightApp_Study*>( app->activeStudy() ) : 0;
  if( !app || !study )
  {
    abort();
    return;
  }

  LightApp_SelectionMgr* mgr = app->selectionMgr();
  LightApp_Selection sel; sel.init( "", mgr );
  if( sel.count()==0 && myActionType!=ERASE_ALL )
  {
    abort();
    return;
  }
  QString aStr =  sel.param( 0, "component" ).toString();
  QString mod_name = app->moduleTitle( aStr );//sel.param( 0, "component" ).toString() );
  LightApp_Displayer* d = displayer( mod_name );
  if( !d )
  {
    abort();
    return;
  }

  if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )
  {
    //ERASE ALL
    QStringList comps;
    study->components( comps );
    QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();
    for( ; anIt!=aLast; anIt++ )
    {
      LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );
      if( disp )
	disp->EraseAll( false, false, 0 );
    }
    if( myActionType==ERASE_ALL )
    {
      d->UpdateViewer();
      commit();
      return;
    }
  }

  SALOME_ListIO selObjs;
  mgr->selectedObjects( selObjs );

  QStringList entries;
  SALOME_ListIteratorOfListIO anIt( selObjs );
  for( ; anIt.More(); anIt.Next() )
  {
    if( anIt.Value().IsNull() )
      continue;

    if( study->isComponent( anIt.Value()->getEntry() ) )
      study->children( anIt.Value()->getEntry(), entries );
    else
      entries.append( anIt.Value()->getEntry() );
  }

  for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )
  {
    QString e = study->referencedToEntry( *it );
    if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )
      d->Display( e, false, 0 );
    else if( myActionType==ERASE )
      d->Erase( e, false, false, 0 );
  }
  d->UpdateViewer();
  commit();
}
<|endoftext|>


<commit_before>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/test/unit_test.hpp>
#include <roundc/round.h>

BOOST_AUTO_TEST_CASE(MutexTest) {
  RoundMutex *mutex;

  mutex = round_mutex_new();
  BOOST_CHECK(mutex);
  BOOST_CHECK(round_mutex_lock(mutex));
  BOOST_CHECK(round_mutex_unlock(mutex));
  BOOST_CHECK(round_mutex_delete(mutex));
}
<commit_msg>* Added tests for mutex functions.<commit_after>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/test/unit_test.hpp>
#include <roundc/round.h>

BOOST_AUTO_TEST_CASE(MutexTest)
{
  RoundMutex *mutex;

  mutex = round_mutex_new();
  BOOST_CHECK(mutex);
  BOOST_CHECK(round_mutex_lock(mutex));
  BOOST_CHECK(round_mutex_unlock(mutex));
  BOOST_CHECK(round_mutex_delete(mutex));
}
<|endoftext|>


<commit_before>#include "llvm/ADT/APInt.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NoFolder.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <iostream>
#include <fstream>

using namespace llvm;
using namespace std;

static LLVMContext C;
static IRBuilder<NoFolder> Builder(C);
static std::unique_ptr<Module> M = llvm::make_unique<Module>("calc", C);
static ifstream gInFile;
char gCurValue = -1;
int  gArgsLen = 6;
int  gLineNo = 1;
enum oper {ADD = 0, SUB, MUL, DIV, MOD};
bool debug = true;

void parseExpression();
void skipSpaces();

void usage(void) {
  printf("executable <input file.calc>\r\n");
  return;
}

bool openFile(int argc, char **argv) {
  if (argc < 2) {
    usage();
    return false;
  }
  gInFile.open (argv[1], ifstream::in);
  return true;
}

char getChar() {
  return gCurValue;
}

void nextChar(void) {
  if (!gInFile.eof()) {
    gCurValue = gInFile.get();
  } else {
    gCurValue = EOF;
  }
}

char getnextChar() {
  nextChar();
  return gCurValue;
}

bool accept(char c) {
  if (getChar() == c) {
    nextChar();
    return true;
  }
  return false;
}

bool check(char c) {
  if (getChar() == c) {
    return true;
  }
  return false;
}

string getContext() {
  string context;
  getline(gInFile, context);
  return context;
}

void printError() {
  printf ("Invalid statement at LineNo:%d:%d - %s",
           gLineNo, (int)gInFile.tellg(), getContext().c_str());
  exit(0);
}

void printError(const char *c) {
  printf("Unable to compile due to error %s at Line: %d FilePosition:%d \r\n",
      c, gLineNo, (int)gInFile.tellg());
  printf("Remaining Code: %s", getContext().c_str());
  exit(0);
}

void parseComment() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  while (getnextChar() != '\n');
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseArgs() {
  char errmsg[50];
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  int i;
  //Move the pointer next to a
  getnextChar();
  for (i = 0; i < gArgsLen; i++) {
    if (accept('0' + (i - 0))) { //Change from int to char
      break;
    }
  }
  if (i == gArgsLen) {
    sprintf(errmsg, "Invalid argument (a%c) used in the program",
            getChar());
    printError(errmsg);
  }
  getnextChar();
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

//Guess this should return an LLVM object
void parseArithmeticOperation() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  char oper = getChar();
  parseExpression();
  parseExpression();
  //Get Oper1
  //Oper1 = parseExpression();
  //Oper2 = parseExpression();
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseNumber() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  int num = 0, count = 0;
  char ch = getChar();
  while  ((ch >= 0) && (ch <= 9)) {
    num = (num * 10 * count++) + (0 + (ch - '0'));
  }
  //changed the int to number;
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseRelationalOperation() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  if (accept('>')) {
    //This is greater than
    if (accept('=')) {
      //This is greater than equals
    }
  } else if (accept('<')) {
    //This is less than
    if (accept('=')) {
      //This is less than equals
    }
  } else if (accept('!') && accept('=')) {
    //This is not equal to
  } else if (accept('=') && accept('=')) {
    //This is double equals
  }
  parseExpression();
  parseExpression();
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseBoolExpression() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  skipSpaces();

  char ch = getnextChar();

  if (accept('t') && accept('r') && accept('u') && accept('e')) {
    //Its a true condition
  } else if (accept('f') && accept('a') && accept('l')
      && accept('s') && accept('e')) {
    //Its a false condition
  } else if ((ch == '>') || (ch == '<') || (ch == '=') ||
             (ch == '!')) {
    parseRelationalOperation();
  } else if (ch == ('(')) {
    parseBoolExpression();
    if (accept(')') == false) {
      printError("Missing ) Paranthesis in boolean exp");
    }
  }

  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseIf() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  if (accept('i') && accept('f')) {
    //Move till you find the ( of the bool expression
      parseBoolExpression();
      parseExpression();
      parseExpression();
  } else {
    printError();
  }
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void skipSpaces() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  while (true) {
    if (accept(' ')) {
      continue;
    } else if (accept('\n')) {
      gLineNo++;
      continue;
    }
    break;
  }

  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

/* This function is called with the current pointer
 * at ( */
void parseExpression() {
  char errmsg[75];
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  skipSpaces();

  char ch = getChar();

  while (ch != EOF) {
    if (ch == '#') {
      parseComment();
      getnextChar();
    } else if (ch == 'a') {
      parseArgs();
      break;
    } else if (ch == '\n') {
      //Increment the line number, so that we can give a
      //meaningful error message
      gLineNo++;
    } else if (ch == ' ') {
      //Ignore White space
    } else if ((ch == '+') || (ch == '-') || (ch == '*') ||
               (ch == '/') || (ch == '%')) {
      parseArithmeticOperation();
      break;
    } else if ((ch >= 0) && (ch <= 9)) {
      return parseNumber();
    } else if (ch == '(') {
      getnextChar();
      return parseExpression();
      if (check(')') == false) {
        printError("Missing Matching paranthesis");
      }
    } else if (ch == 'i') {
      parseIf();
      break;
    } else if (ch == ')') {
      getnextChar();
      break;
    } else {
      printError();
    }
    ch = getnextChar();
  }
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parser() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  char ch = getnextChar();
  while(ch != EOF) {
    if (ch == '#') {
      parseComment();
    } else {
      parseExpression();
      skipSpaces();
      if (getChar() == EOF) {
        break;
      } else {
        printError();
      }
    }
    ch = getnextChar();
  }
  printf("Parsed successfully\r\n");
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

static int compile() {
  M->setTargetTriple(llvm::sys::getProcessTriple());
  std::vector<Type *> SixInts(6, Type::getInt64Ty(C));
  FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);
  Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*M);
  BasicBlock *BB = BasicBlock::Create(C, "entry", F);
  Builder.SetInsertPoint(BB);

  // TODO: parse the source program
  // TODO: generate correct LLVM instead of just an empty function

  Value *RetVal = ConstantInt::get(C, APInt(64, 0));
  Builder.CreateRet(RetVal);
  assert(verifyModule(*M));
  M->dump();
  return 0;
}

int main(int argc, char **argv) {
  if (openFile(argc, argv) == true) {
    parser();
    //return compile();
  }
  return -1;
}
<commit_msg>parser mostly working<commit_after>#include "llvm/ADT/APInt.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NoFolder.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <iostream>
#include <fstream>

using namespace llvm;
using namespace std;

static LLVMContext C;
static IRBuilder<NoFolder> Builder(C);
static std::unique_ptr<Module> M = llvm::make_unique<Module>("calc", C);
static ifstream gInFile;
char gCurValue = -1;
int  gArgsLen = 6;
int  gLineNo = 1;
enum oper {ADD = 0, SUB, MUL, DIV, MOD};
bool debug = true;

void parseExpression();
void skipSpaces();

void usage(void) {
  printf("executable <input file.calc>\r\n");
  return;
}

bool openFile(int argc, char **argv) {
  if (argc < 2) {
    usage();
    return false;
  }
  gInFile.open (argv[1], ifstream::in);
  return true;
}

char getChar() {
  return gCurValue;
}

void nextChar(void) {
  if (!gInFile.eof()) {
    gCurValue = gInFile.get();
  } else {
    gCurValue = EOF;
  }
}

char getnextChar() {
  nextChar();
  return gCurValue;
}

bool accept(char c) {
  if (getChar() == c) {
    nextChar();
    return true;
  }
  return false;
}

bool check(char c) {
  if (getChar() == c) {
    return true;
  }
  return false;
}

string getContext() {
  string context;
  getline(gInFile, context);
  return context;
}

void printError(int lineno) {
  printf ("%d:Invalid statement at LineNo:%d:%d - %c%s",
           lineno,
           gLineNo, (int)gInFile.tellg(), getChar(), getContext().c_str());
  exit(0);
}

void printError(int lineno, const char *c) {
  printf("%d:Unable to compile due to error %s at Line: %d FilePosition:%d \r\n",
      lineno,
      c, gLineNo, (int)gInFile.tellg());
  printf("Remaining Code: %c%s", getChar(), getContext().c_str());
  exit(0);
}

void parseComment() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  while (getnextChar() != '\n');
  //Skip \n
  getnextChar();
  gLineNo++;
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseArgs() {
  char errmsg[50];
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  int i;
  //Move the pointer next to a
  getnextChar();
  for (i = 0; i < gArgsLen; i++) {
    if (accept('0' + (i - 0))) { //Change from int to char
      break;
    }
  }
  if (i == gArgsLen) {
    sprintf(errmsg, "Invalid argument (a%c) used in the program",
            getChar());
    printError(__LINE__, errmsg);
  }
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

//Guess this should return an LLVM object
void parseArithmeticOperation(char oper) {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  parseExpression();
  parseExpression();
  //Get Oper1
  //Oper1 = parseExpression();
  //Oper2 = parseExpression();
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseNumber() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  int num = 0, count = 0;
  char ch = getChar();
  while  ((ch >= '0') && (ch <= '9')) {
    num = (num * 10 * count++) + (0 + (ch - '0'));
    ch = getnextChar();
  }
  //changed the int to number;
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseRelationalOperation() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  if (accept('>')) {
    //This is greater than
    if (accept('=')) {
      //This is greater than equals
    }
  } else if (accept('<')) {
    //This is less than
    if (accept('=')) {
      //This is less than equals
    }
  } else if (accept('!') && accept('=')) {
    //This is not equal to
  } else if (accept('=') && accept('=')) {
    //This is double equals
  }
  parseExpression();
  parseExpression();
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseBoolExpression() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  skipSpaces();

  char ch = getChar();

  if (accept('t') && accept('r') && accept('u') && accept('e')) {
    //Its a true condition
  } else if (accept('f') && accept('a') && accept('l')
      && accept('s') && accept('e')) {
    //Its a false condition
  } else if ((ch == '>') || (ch == '<') || (ch == '=') ||
             (ch == '!')) {
    parseRelationalOperation();
  } else if (ch == ('(')) {
    getnextChar();
    parseBoolExpression();
    if (accept(')') == false) {
      printError(__LINE__, "Missing ) Paranthesis in boolean exp");
    }
  } else {
    printError(__LINE__, "Boolean expression Missing");
  }

  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parseIf() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  if (accept('i') && accept('f')) {
    //Move till you find the ( of the bool expression
      parseBoolExpression();
      parseExpression();
      parseExpression();
  } else {
    printError(__LINE__);
  }
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void skipSpaces() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  while (getChar() != EOF) {
    if (accept(' ')) {
      continue;
    } else if (accept('\n')) {
      gLineNo++;
      continue;
    }
    break;
  }

  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

/* This function is called with the current pointer
 * at ( */
void parseExpression() {
  char errmsg[75];
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }

  skipSpaces();

  char ch = getChar();

  do{
    if (ch == '#') {
      parseComment();
    } else if (ch == 'a') {
      parseArgs();
      break;
    } else if (ch == '\n') {
      //Increment the line number, so that we can give a
      //meaningful error message
      gLineNo++;
    } else if (ch == ' ') {
      //Ignore White space
    } else if ((ch == '+') || (ch == '-') || (ch == '*') ||
               (ch == '/') || (ch == '%')) {
      getnextChar();
      parseArithmeticOperation(ch);
      break;
    } else if ((ch >= '0') && (ch <= '9')) {
      parseNumber();
      break;
    } else if (ch == '(') {
      getnextChar();
      parseExpression();
      if (accept(')') == false) {
        printError(__LINE__, "Missing Matching paranthesis");
      }
      break;
    } else if (ch == 'i') {
      parseIf();
      break;
    } else if (ch == ')') {
      getnextChar();
      break;
    } else {
      printError(__LINE__);
    }
    ch = getChar();
  }while (ch != EOF);
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

void parser() {
  if (debug) {
    printf("Enter %s\r\n", __PRETTY_FUNCTION__);
  }
  char ch = getnextChar();
  while(ch != EOF) {
    if (ch == '#') {
      parseComment();
    } else {
      parseExpression();
      skipSpaces();
      if (getChar() == EOF) {
        break;
      } else {
        printError(__LINE__);
      }
    }
    ch = getChar();
  }
  printf("Parsed successfully\r\n");
  if (debug) {
    printf("Exit %s\r\n", __PRETTY_FUNCTION__);
  }
}

static int compile() {
  M->setTargetTriple(llvm::sys::getProcessTriple());
  std::vector<Type *> SixInts(6, Type::getInt64Ty(C));
  FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);
  Function *F = Function::Create(FT, Function::ExternalLinkage, "f", &*M);
  BasicBlock *BB = BasicBlock::Create(C, "entry", F);
  Builder.SetInsertPoint(BB);

  // TODO: parse the source program
  // TODO: generate correct LLVM instead of just an empty function

  Value *RetVal = ConstantInt::get(C, APInt(64, 0));
  Builder.CreateRet(RetVal);
  assert(verifyModule(*M));
  M->dump();
  return 0;
}

int main(int argc, char **argv) {
  if (openFile(argc, argv) == true) {
    parser();
    //return compile();
  }
  return -1;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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 "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"

#include <boost/bind.hpp>

using namespace libtorrent;

// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
	if (filename(f)[0] == '.') return false;
	fprintf(stderr, "%s\n", f.c_str());
	return true;
}

void print_progress(int i, int num)
{
	fprintf(stderr, "\r%d/%d", i+1, num);
}

void print_usage()
{
	fputs("usage: make_torrent FILE [OPTIONS]\n"
		"\n"
		"Generates a torrent file from the specified file\n"
		"or directory and writes it to standard out\n\n"
		"OPTIONS:\n"
		"-m          generate a merkle hash tree torrent.\n"
		"            merkle torrents require client support\n"
		"-w url      adds a web seed to the torrent with\n"
		"            the specified url\n"
		"-t url      adds the specified tracker to the\n"
		"            torrent\n"
		"-p bytes    enables padding files. Files larger\n"
		"            than bytes will be piece-aligned\n"
		"-s bytes    specifies a piece size for the torrent\n"
		"            This has to be a multiple of 16 kiB\n"
		, stderr);
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	char const* creator_str = "libtorrent";

	if (argc < 2)
	{
		print_usage();
		return 1;
	}

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		std::vector<std::string> web_seeds;
		std::vector<std::string> trackers;
		int pad_file_limit = -1;
		int piece_size = 0;
		int flags = 0;

		for (int i = 2; i < argc; ++i)
		{
			if (argv[i][0] != '-')
			{
				print_usage();
				return 1;
			}

			switch (argv[i][1])
			{
				case 'w':
					++i;
					web_seeds.push_back(argv[i]);
					break;
				case 't':
					++i;
					trackers.push_back(argv[i]);
					break;
				case 'p':
					++i;
					pad_file_limit = atoi(argv[i]);
					flags |= create_torrent::optimize;
					break;
				case 's':
					++i;
					piece_size = atoi(argv[i]);
					break;
				case 'm':
					flags |= create_torrent::merkle;
					break;
				default:
					print_usage();
					return 1;
			}
		}

		file_storage fs;
		file_pool fp;
		std::string full_path = libtorrent::complete(argv[1]);

		add_files(fs, full_path, file_filter);

		create_torrent t(fs, piece_size, pad_file_limit, flags);
		for (std::vector<std::string>::iterator i = trackers.begin()
			, end(trackers.end()); i != end; ++i)
			t.add_tracker(*i);

		for (std::vector<std::string>::iterator i = web_seeds.begin()
			, end(web_seeds.end()); i != end; ++i)
			t.add_url_seed(*i);

		error_code ec;
		set_piece_hashes(t, parent_path(full_path)
			, boost::bind(&print_progress, _1, t.num_pieces()), ec);
		if (ec)
		{
			fprintf(stderr, "%s\n", ec.message().c_str());
			return 1;
		}

		fprintf(stderr, "\n");
		t.set_creator(creator_str);

		// create the torrent and print it to stdout
		std::vector<char> torrent;
		bencode(back_inserter(torrent), t.generate());
		fwrite(&torrent[0], 1, torrent.size(), stdout);

#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception& e)
	{
		fprintf(stderr, "%s\n", e.what());
	}
#endif

	return 0;
}

<commit_msg>error handling in make_torrent<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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 "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"

#include <boost/bind.hpp>

using namespace libtorrent;

// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
	if (filename(f)[0] == '.') return false;
	fprintf(stderr, "%s\n", f.c_str());
	return true;
}

void print_progress(int i, int num)
{
	fprintf(stderr, "\r%d/%d", i+1, num);
}

void print_usage()
{
	fputs("usage: make_torrent FILE [OPTIONS]\n"
		"\n"
		"Generates a torrent file from the specified file\n"
		"or directory and writes it to standard out\n\n"
		"OPTIONS:\n"
		"-m          generate a merkle hash tree torrent.\n"
		"            merkle torrents require client support\n"
		"-w url      adds a web seed to the torrent with\n"
		"            the specified url\n"
		"-t url      adds the specified tracker to the\n"
		"            torrent\n"
		"-p bytes    enables padding files. Files larger\n"
		"            than bytes will be piece-aligned\n"
		"-s bytes    specifies a piece size for the torrent\n"
		"            This has to be a multiple of 16 kiB\n"
		, stderr);
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	char const* creator_str = "libtorrent";

	if (argc < 2)
	{
		print_usage();
		return 1;
	}

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		std::vector<std::string> web_seeds;
		std::vector<std::string> trackers;
		int pad_file_limit = -1;
		int piece_size = 0;
		int flags = 0;

		for (int i = 2; i < argc; ++i)
		{
			if (argv[i][0] != '-')
			{
				print_usage();
				return 1;
			}

			switch (argv[i][1])
			{
				case 'w':
					++i;
					web_seeds.push_back(argv[i]);
					break;
				case 't':
					++i;
					trackers.push_back(argv[i]);
					break;
				case 'p':
					++i;
					pad_file_limit = atoi(argv[i]);
					flags |= create_torrent::optimize;
					break;
				case 's':
					++i;
					piece_size = atoi(argv[i]);
					break;
				case 'm':
					flags |= create_torrent::merkle;
					break;
				default:
					print_usage();
					return 1;
			}
		}

		file_storage fs;
		file_pool fp;
		std::string full_path = libtorrent::complete(argv[1]);

		add_files(fs, full_path, file_filter);
		if (fs.num_files() == 0)
		{
			fputs("no files specified.\n", stderr);
			return 1;
		}

		create_torrent t(fs, piece_size, pad_file_limit, flags);
		for (std::vector<std::string>::iterator i = trackers.begin()
			, end(trackers.end()); i != end; ++i)
			t.add_tracker(*i);

		for (std::vector<std::string>::iterator i = web_seeds.begin()
			, end(web_seeds.end()); i != end; ++i)
			t.add_url_seed(*i);

		error_code ec;
		set_piece_hashes(t, parent_path(full_path)
			, boost::bind(&print_progress, _1, t.num_pieces()), ec);
		if (ec)
		{
			fprintf(stderr, "%s\n", ec.message().c_str());
			return 1;
		}

		fprintf(stderr, "\n");
		t.set_creator(creator_str);

		// create the torrent and print it to stdout
		std::vector<char> torrent;
		bencode(back_inserter(torrent), t.generate());
		fwrite(&torrent[0], 1, torrent.size(), stdout);

#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception& e)
	{
		fprintf(stderr, "%s\n", e.what());
	}
#endif

	return 0;
}

<|endoftext|>


<commit_before>// Author: Daisuke Kanaizumi
// Affiliation: Department of Applied Mathematics, Waseda University
// Email: daisuke15@asagi.waseda.jp

// Verification program for modified q-Bessel functions
// by using double exponential formula with verified error bounds.
// References

// Zhang, R. (2008). Plancherel–Rotach Asymptotics for Certain Basic Hypergeometric Series. Advances in Mathematics, 217(4), 1588-1613.
// Okayama, T. (2013). Error estimates with explicit constants for Sinc quadrature and Sinc indefinite integration over infinite intervals. arXiv preprint arXiv:1302.1314.
// Ismail, M. E. (1981). The basic Bessel functions and polynomials. SIAM Journal on Mathematical Analysis, 12(3), 454-468.
#ifndef MQB_DE_HPP
#define MQB_DE_HPP

#include <kv/interval.hpp>
#include <kv/rdouble.hpp>

#include <kv/constants.hpp>
#include <kv/complex.hpp>
#include <kv/defint.hpp>
#include <kv/Pochhammer.hpp>
#include <kv/Heine.hpp>
#include <cmath>
#include <algorithm>
namespace kv{

  template <class TT> struct mqBreal {
    TT z, q, nu;
    int n; // Setting parameters
    mqBreal(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}

    template <class T> T operator() (const T& t) {
      complex<T>  pro;
      T proreal;
      complex<T> i;
      pro=1.;
      i=complex<T>::i();
      for(int k=0;k<=n-1;k++){
	pro=pro/(1-z*0.5*pow(T(q),k)*exp(i*t))/(1-z*0.5*pow(T(q),k)*exp(-i*t));
      }
      pro=pro*cos(T(nu)*t);
      proreal=pro.real();
      return proreal;
    }
  };

  template <class TT> struct mqBimag {
    TT z, q, nu;
    int n; // Setting parameters
    mqBimag(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}

    template <class T> T operator() (const T& t) {
      complex<T>  pro;
      T proimag;
      complex<T> i;
      pro=1.;
      i=complex<T>::i();
      for(int k=0;k<=n-1;k++){
	pro=pro/(1-z*0.5*pow(T(q),k)*exp(i*t))/(1-z*0.5*pow(T(q),k)*exp(-i*t));
      }
      pro=pro*cos(T(nu)*t);
      proimag=pro.imag();
      return proimag;

    }
  };

  template <class T> complex<interval<T> >modified_qBesselI2_DE(const interval<T> & z,const interval<T> & nu,const interval<T>& q){
    //verification program for 2nd modified q-Bessel function I2
    if(abs(q)>=1){
      throw std::domain_error("absolute value of q must be under 1");
    }
    if(nu<=0){
      throw std::domain_error("value of nu must be more than 0");
    }
    interval<T> pi,realint,imagint,second,e,d,h,K,C3,sum,intrad;
    complex<interval<T> >res,first;
    pi=constants<interval<T> >::pi();
    e=constants<interval<T> >::e();
    int m,n,M,N;
    m=100;
    while(abs(z*pow(q,m))*0.5/(1-q)>=0.5){
      m=m+10;
    }
    d=1.;

    n=150;
    M=n;
    h=log(4*d*n)/T(n);
    N=n-std::floor(mid(log(nu)/h));

    while(n<=nu*e*0.25*d){
      n=n+10;
    }
    intrad=pow(1+2*abs(z)*pow(q,m)/(1-q)*interval<T>(-1.,1.),2);
    realint=defint(mqBreal<interval<T> >(z,q,nu,m),interval<T>(0.),interval<T>(pi),10,10);
    imagint=defint(mqBimag<interval<T> >(z,q,nu,m),interval<T>(0.),interval<T>(pi),10,10);
    first=intrad*complex<interval<T> >(realint,imagint)/pi;

    K=(1+2*z*pow(q,m)/(1-q))/infinite_qPochhammer(interval<T>(abs(z)*0.5),interval<T>(q))
      /qPochhammer(interval<T>(z*0.5),interval<T>(q),int(m));

    C3=2*K*(2/(1-exp(-pi*e*0.5))/cos(d)/pow(cos(pi*0.5*sin(d)),nu+1)+exp(pi*nu*0.5));

    sum=0.;
    for(int k=-M;k<=N;k++){
      sum=sum+exp(-(nu)*log(1+exp(pi*sinh(k*h))))
	/infinite_qPochhammer(interval<T> (-z*0.5*(1.+exp(pi*sinh(k*h)))),interval<T>(q))
	/infinite_qPochhammer(interval<T> (-0.5*z/(1.+exp(pi*sinh(k*h)))),interval<T>(q))
	*pi*exp(pi*sinh(k*h))*cosh(k*h)/(1.+exp(pi*sinh(k*h)));
    }

    second=(h*sum+C3*exp(-2*pi*d/h)*interval<T>(-1.,1.))*sin(pi*nu)/pi;
    res=(first-second)*infinite_qPochhammer(interval<T> (z*z*0.25),interval<T>(q));
    return res;
    // to be repaired
  }
}
#endif
<commit_msg>Update mqB_DE.hpp<commit_after>// Author: Daisuke Kanaizumi
// Affiliation: Department of Applied Mathematics, Waseda University

// Verification program for modified q-Bessel functions
// by using double exponential formula with verified error bounds.
// References

// Zhang, R. (2008). Plancherel–Rotach Asymptotics for Certain Basic Hypergeometric Series. Advances in Mathematics, 217(4), 1588-1613.
// Okayama, T. (2013). Error estimates with explicit constants for Sinc quadrature and Sinc indefinite integration over infinite intervals. arXiv preprint arXiv:1302.1314.
// Ismail, M. E. (1981). The basic Bessel functions and polynomials. SIAM Journal on Mathematical Analysis, 12(3), 454-468.
#ifndef MQB_DE_HPP
#define MQB_DE_HPP

#include <kv/interval.hpp>
#include <kv/rdouble.hpp>

#include <kv/constants.hpp>
#include <kv/complex.hpp>
#include <kv/defint.hpp>
#include <kv/Pochhammer.hpp>
#include <kv/Heine.hpp>
#include <cmath>
#include <algorithm>
namespace kv{

  template <class TT> struct mqBreal {
    TT z, q, nu;
    int n; // Setting parameters
    mqBreal(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}

    template <class T> T operator() (const T& t) {
      complex<T>  pro;
      T proreal;
      complex<T> i;
      pro=1.;
      i=complex<T>::i();
      for(int k=0;k<=n-1;k++){
	pro=pro/(1-z*0.5*pow(T(q),k)*exp(i*t))/(1-z*0.5*pow(T(q),k)*exp(-i*t));
      }
      pro=pro*cos(T(nu)*t);
      proreal=pro.real();
      return proreal;
    }
  };

  template <class TT> struct mqBimag {
    TT z, q, nu;
    int n; // Setting parameters
    mqBimag(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}

    template <class T> T operator() (const T& t) {
      complex<T>  pro;
      T proimag;
      complex<T> i;
      pro=1.;
      i=complex<T>::i();
      for(int k=0;k<=n-1;k++){
	pro=pro/(1-z*0.5*pow(T(q),k)*exp(i*t))/(1-z*0.5*pow(T(q),k)*exp(-i*t));
      }
      pro=pro*cos(T(nu)*t);
      proimag=pro.imag();
      return proimag;

    }
  };

  template <class T> complex<interval<T> >modified_qBesselI2_DE(const interval<T> & z,const interval<T> & nu,const interval<T>& q){
    //verification program for 2nd modified q-Bessel function I2
    if(abs(q)>=1){
      throw std::domain_error("absolute value of q must be under 1");
    }
    if(nu<=0){
      throw std::domain_error("value of nu must be more than 0");
    }
    interval<T> pi,realint,imagint,second,e,d,h,K,C3,sum,intrad;
    complex<interval<T> >res,first;
    pi=constants<interval<T> >::pi();
    e=constants<interval<T> >::e();
    int m,n,M,N;
    m=100;
    while(abs(z*pow(q,m))*0.5/(1-q)>=0.5){
      m=m+10;
    }
    d=1.;

    n=150;
    M=n;
    h=log(4*d*n)/T(n);
    N=n-std::floor(mid(log(nu)/h));

    while(n<=nu*e*0.25*d){
      n=n+10;
    }
    intrad=pow(1+2*abs(z)*pow(q,m)/(1-q)*interval<T>(-1.,1.),2);
    realint=defint(mqBreal<interval<T> >(z,q,nu,m),interval<T>(0.),interval<T>(pi),10,10);
    imagint=defint(mqBimag<interval<T> >(z,q,nu,m),interval<T>(0.),interval<T>(pi),10,10);
    first=intrad*complex<interval<T> >(realint,imagint)/pi;

    K=(1+2*z*pow(q,m)/(1-q))/infinite_qPochhammer(interval<T>(abs(z)*0.5),interval<T>(q))
      /qPochhammer(interval<T>(z*0.5),interval<T>(q),int(m));

    C3=2*K*(2/(1-exp(-pi*e*0.5))/cos(d)/pow(cos(pi*0.5*sin(d)),nu+1)+exp(pi*nu*0.5));

    sum=0.;
    for(int k=-M;k<=N;k++){
      sum=sum+exp(-(nu)*log(1+exp(pi*sinh(k*h))))
	/infinite_qPochhammer(interval<T> (-z*0.5*(1.+exp(pi*sinh(k*h)))),interval<T>(q))
	/infinite_qPochhammer(interval<T> (-0.5*z/(1.+exp(pi*sinh(k*h)))),interval<T>(q))
	*pi*exp(pi*sinh(k*h))*cosh(k*h)/(1.+exp(pi*sinh(k*h)));
    }

    second=(h*sum+C3*exp(-2*pi*d/h)*interval<T>(-1.,1.))*sin(pi*nu)/pi;
    res=(first-second)*infinite_qPochhammer(interval<T> (z*z*0.25),interval<T>(q));
    return res;
    // to be repaired
  }
}
#endif
<|endoftext|>


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

#include <sstream>

/** @class	StuffTest
 * @brief	Tests EMPA processor stuff functionality
 *
 */
extern bool UNIT_TESTING;		// Switched off by default
// A new test class  of these is created for each test
class EvalTest : public testing::Test
{
public:
public:

};

/**
 * Tests some routines of the stuff
 */
TEST_F(EvalTest, Tools)
{
    ESpectrumBase SP;
    EXPECT_EQ(-1, SP.XEnergy_Get()); // After creating, the X energy is invalid
    EXPECT_FALSE(SP.XEnergy_Valid());
    SP.XEnergy_Set(1486.295);
    EXPECT_EQ(1486.295, SP.XEnergy_Get()); // After setting, the X energy is valid
    EXPECT_TRUE(SP.XEnergy_Valid());
}
<commit_msg>New structure tested<commit_after>#include <gtest/gtest.h>
#include "Stuff.h"
#include "ESpectrumBase.h"

#include <sstream>

/** @class	StuffTest
 * @brief	Tests EMPA processor stuff functionality
 *
 */
extern bool UNIT_TESTING;		// Switched off by default
// A new test class  of these is created for each test
class EvalTest : public testing::Test
{
public:
public:

};

/**
 * Tests some routines of the stuff
 */
TEST_F(EvalTest, Tools)
{
    double myints[]={10.,20.,30.,40.,50.,60.,70.};
    std::vector<double> myvector (7);
    std::copy ( myints, myints+7, myvector.begin() );
    ESpectrumBase SP(&myvector);
    EXPECT_EQ(-1, SP.XEnergy_Get()); // After creating, the X energy is invalid
    EXPECT_FALSE(SP.XEnergy_Valid());
    EXPECT_EQ(20,SP.Y_Get(1));
    EXPECT_EQ(1,SP.X_Get(1));
    EXPECT_EQ(1,SP.X_Get_Kinetic(1));
    SP.XEnergy_Set(1486.295);
    EXPECT_EQ(20,SP.Y_Get(1));
    EXPECT_EQ(1,SP.X_Get(1));
    EXPECT_EQ(1,SP.X_Get_Kinetic(1));
    EXPECT_EQ(1485.295,SP.X_Get_Binding(1));
    EXPECT_EQ(1486.295, SP.XEnergy_Get()); // After setting, the X energy is valid
    EXPECT_TRUE(SP.XEnergy_Valid());
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2020 ANON authors, see AUTHORS file.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "resin.h"
#include "time_utils.h"
#include <sys/timerfd.h>
#include <signal.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ChangeMessageVisibilityBatchRequest.h>
#include <aws/sqs/model/ChangeMessageVisibilityBatchRequestEntry.h>
#include <aws/sqs/model/ReceiveMessageRequest.h>
#include <aws/sqs/model/DeleteMessageRequest.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeInstancesRequest.h>

namespace
{

std::string replace_all(std::string &s, const std::string &pat, const std::string &rep)
{
  size_t pos = 0;
  auto plen = pat.size();
  auto rlen = rep.size();
  while (true)
  {
    auto fpos = s.find(pat, pos);
    if (fpos == std::string::npos)
      break;
    s = s.replace(fpos, plen, rep);
    pos = fpos + rlen;
  }
  return s;
}

std::string get_body(const Aws::SQS::Model::Message &m)
{
  auto body = m.GetBody();
  body = replace_all(body, "&", "&");
  body = replace_all(body, """, "\"");
  body = replace_all(body, "'", "\'");
  body = replace_all(body, "<", "<");
  return replace_all(body, ">", ">");
}

bool should_shut_down(const ec2_info &ec2i)
{
  if (ec2i.user_data_js.find("min_instance_url") != ec2i.user_data_js.end())
  {
    Aws::Client::ClientConfiguration ddb_config;
    if (ec2i.user_data_js.find("min_instance_region") != ec2i.user_data_js.end())
      ddb_config.region = ec2i.user_data_js["min_instance_region"];
    else
      ddb_config.region = ec2i.default_region;
    ddb_config.executor = ec2i.executor;
    Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);

    Aws::DynamoDB::Model::AttributeValue primary_key;
    primary_key.SetS(ec2i.user_data_js["min_instance_primary_key_value"]);
    Aws::DynamoDB::Model::GetItemRequest req;
    req.WithTableName(ec2i.user_data_js["min_instance_table_name"])
        .AddKey(ec2i.user_data_js["min_instance_primary_key_name"], primary_key);
    auto outcome = ddbc.GetItem(req);
    if (outcome.IsSuccess())
    {
      auto map = outcome.GetResult().GetItem();
      auto it = map.find("min_instances");
      if (it != map.end())
      {
        auto min_instances = std::atoi(it->second.GetN().c_str());
        std::string instance_name = ec2i.user_data_js["min_instance_name"];

        Aws::Client::ClientConfiguration ec2_config;
        ec2_config.region = ec2i.default_region;
        ec2_config.executor = ec2i.executor;
        Aws::EC2::EC2Client ec2(ec2_config);

        Aws::EC2::Model::DescribeInstancesRequest request;
        Aws::EC2::Model::Filter filter1;
        filter1.SetName("tag:Name");
        filter1.AddValues(instance_name);
        request.AddFilters(filter1);
        Aws::EC2::Model::Filter filter2;
        filter2.SetName("instance-state-name");
        filter2.AddValues("running");
        request.AddFilters(filter2);

        bool done = false;
        int total_instances = 0;
        while (!done)
        {
          auto outcome = ec2.DescribeInstances(request);
          if (outcome.IsSuccess())
          {
            const auto &reservations = outcome.GetResult().GetReservations();
            for (const auto &reservation : reservations)
            {
              const auto &instances = reservation.GetInstances();
              total_instances += instances.size();
              if (total_instances > min_instances)
                return true;
            }
            if (outcome.GetResult().GetNextToken().size() > 0)
              request.SetNextToken(outcome.GetResult().GetNextToken());
            else
              done = true;
          }
          else
            return true;
        }

        return total_instances > min_instances;
      }
    }
  }
  return true;
}

} // namespace

void run_worker(const ec2_info &ec2i)
{
  Aws::Client::ClientConfiguration config;
  if (ec2i.user_data_js.find("task_queue_region") != ec2i.user_data_js.end())
    config.region = ec2i.user_data_js["task_queue_region"];
  else
    config.region = ec2i.default_region;
  config.executor = ec2i.executor;

  std::string queue_url = ec2i.user_data_js["task_queue_url"];

  Aws::SQS::SQSClient client(config);
  std::mutex keep_alive_mutex;
  std::map<Aws::String, Aws::String> keep_alive_set;
  bool stop = false;
  auto timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  struct itimerspec t_spec = {0};
  t_spec.it_value = cur_time() + 30;
  timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);

  std::thread keep_alive_thread([&client, &keep_alive_mutex, &keep_alive_set,
                                 &stop, &timerfd, &queue_url] {
    while (true)
    {
      struct pollfd pfd;
      pfd.fd = timerfd;
      pfd.events = POLLIN;
      poll(&pfd, 1, 31000);

      std::unique_lock<std::mutex> l(keep_alive_mutex);
      if (stop)
        break;

      auto num_messages = keep_alive_set.size();
      if (num_messages > 0)
      {
        Aws::SQS::Model::ChangeMessageVisibilityBatchRequest req;
        Aws::Vector<Aws::Vector<Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v;
        int index = 0;
        for (auto it : keep_alive_set)
        {
          Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry ent;
          std::ostringstream str;
          if (index % 10 == 0)
            entries_v.push_back(Aws::Vector<Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry>());
          str << "message_" << ++index;
          ent.WithReceiptHandle(it.first).WithVisibilityTimeout(60).WithId(str.str());
          entries_v.back().push_back(ent);
        }
        l.unlock();
        for (auto &entries : entries_v)
        {
          req.WithQueueUrl(queue_url).WithEntries(entries);
          auto outcome = client.ChangeMessageVisibilityBatch(req);
          if (!outcome.IsSuccess())
            anon_log("ChangeMessageVisibilityBatch failed: " << outcome.GetError());
        }
      }

      struct itimerspec t_spec = {0};
      t_spec.it_value = cur_time() + 30;
      timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);
    }
  });

  while (true)
  {
    Aws::SQS::Model::ReceiveMessageRequest req;
    req.WithQueueUrl(queue_url).WithMaxNumberOfMessages(1).WithWaitTimeSeconds(5);
    Aws::Vector<Aws::SQS::Model::QueueAttributeName> att;
    att.push_back(Aws::SQS::Model::QueueAttributeName::All);
    req.WithAttributeNames(std::move(att));

    auto outcome = client.ReceiveMessage(req);
    if (!outcome.IsSuccess())
    {
      anon_log("ReceiveMessage failed: " << outcome.GetError());
      break;
    }
    auto &messages = outcome.GetResult().GetMessages();
    if (messages.size() > 0)
    {
      {
        std::unique_lock<std::mutex> l(keep_alive_mutex);
        for (auto &m : messages)
          keep_alive_set[m.GetReceiptHandle()] = m.GetMessageId();
      }
      struct itimerspec t_spec = {0};
      timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);

      for (auto &m : messages)
      {
        auto bash_cmd = get_body(m);

        const auto max_retries = 2;

        const auto &att = m.GetAttributes();
        auto arc = att.find(Aws::SQS::Model::MessageSystemAttributeName::ApproximateReceiveCount);
        auto approx_receive_count = 1000;
        if (arc != att.end())
          approx_receive_count = std::stoull(arc->second);

        auto pid = fork();
        if (pid == -1)
          do_error("fork()");
        if (pid != 0)
        {
          // the calling parent
          int status;
          auto w = waitpid(-1, &status, WUNTRACED | WCONTINUED);
          if (w == -1)
            do_error("waitpid(-1, &status, WUNTRACED | WCONTINUED)");

          auto script_exited_zero = false;
          if (WIFEXITED(status))
          {
            anon_log("bash exited with exit code: " << WEXITSTATUS(status));
            script_exited_zero = WEXITSTATUS(status) == 0;
          }
          else if (WIFSIGNALED(status))
            anon_log("bash killed by signal: " << WTERMSIG(status));
          else if (WIFSTOPPED(status))
            anon_log("bash stopped by signal: " << WSTOPSIG(status));

          {
            // regardless of whether the bash command succeeded or not
            // we don't want to keep calling ChangeVisibilityStatus on this message
            std::unique_lock<std::mutex> l(keep_alive_mutex);
            keep_alive_set.erase(m.GetReceiptHandle());
          }

          // if the script succeeded, or if we have failed too many times,
          // delete the message from sqs
          if (script_exited_zero || approx_receive_count >= max_retries)
          {
            Aws::SQS::Model::DeleteMessageRequest req;
            req.WithQueueUrl(queue_url).WithReceiptHandle(m.GetReceiptHandle());
            auto outcome = client.DeleteMessage(req);
            if (!outcome.IsSuccess())
              anon_log("DeleteMessage failed: " << outcome.GetError());
          }
        }
        else
        {
          // the child process
          auto bash_file_name = "/bin/bash";
          auto bash_fd = open(bash_file_name, O_RDONLY);
          if (bash_fd == -1)
            do_error("open(\"" << bash_file_name << "\", O_RDONLY)");

          const char *dash_c = "-c";
          const char *script = bash_cmd.c_str();
          const char *do_retry = approx_receive_count < max_retries ? "1" : "0";
          char *args[]{
              const_cast<char *>(bash_file_name),
              const_cast<char *>(dash_c),
              const_cast<char *>(script),
              const_cast<char *>(do_retry),
              0};

          fexecve(bash_fd, &args[0], environ);

          // if fexecve succeeded then we never get here.  So getting here is a failure,
          // but we are already in the child process at this point, so we do what we can
          // to signifify the error and then exit
          fprintf(stderr, "fexecve(%d, ...) failed with errno: %d - %s\n", bash_fd, errno, strerror(errno));
          exit(1);
        }
      }
    }
    else
    {
      // no messages after 10 seconds.  Check for shutdown
      anon_log("no messages after wating period");
      if (should_shut_down(ec2i))
      {
	anon_log("no reason to keep running, shutting down");
        break;
      }
    }
  }

  {
    std::unique_lock<std::mutex> l(keep_alive_mutex);
    stop = true;
    struct itimerspec t_spec = {0};
    t_spec.it_value = cur_time();
    timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);
  }
  keep_alive_thread.join();
}
<commit_msg>adding comments about libcurl timeout<commit_after>/*
 Copyright (c) 2020 ANON authors, see AUTHORS file.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "resin.h"
#include "time_utils.h"
#include <sys/timerfd.h>
#include <signal.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ChangeMessageVisibilityBatchRequest.h>
#include <aws/sqs/model/ChangeMessageVisibilityBatchRequestEntry.h>
#include <aws/sqs/model/ReceiveMessageRequest.h>
#include <aws/sqs/model/DeleteMessageRequest.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeInstancesRequest.h>

namespace
{

std::string replace_all(std::string &s, const std::string &pat, const std::string &rep)
{
  size_t pos = 0;
  auto plen = pat.size();
  auto rlen = rep.size();
  while (true)
  {
    auto fpos = s.find(pat, pos);
    if (fpos == std::string::npos)
      break;
    s = s.replace(fpos, plen, rep);
    pos = fpos + rlen;
  }
  return s;
}

std::string get_body(const Aws::SQS::Model::Message &m)
{
  auto body = m.GetBody();
  body = replace_all(body, "&", "&");
  body = replace_all(body, """, "\"");
  body = replace_all(body, "'", "\'");
  body = replace_all(body, "<", "<");
  return replace_all(body, ">", ">");
}

bool should_shut_down(const ec2_info &ec2i)
{
  if (ec2i.user_data_js.find("min_instance_url") != ec2i.user_data_js.end())
  {
    Aws::Client::ClientConfiguration ddb_config;
    if (ec2i.user_data_js.find("min_instance_region") != ec2i.user_data_js.end())
      ddb_config.region = ec2i.user_data_js["min_instance_region"];
    else
      ddb_config.region = ec2i.default_region;
    ddb_config.executor = ec2i.executor;
    Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);

    Aws::DynamoDB::Model::AttributeValue primary_key;
    primary_key.SetS(ec2i.user_data_js["min_instance_primary_key_value"]);
    Aws::DynamoDB::Model::GetItemRequest req;
    req.WithTableName(ec2i.user_data_js["min_instance_table_name"])
        .AddKey(ec2i.user_data_js["min_instance_primary_key_name"], primary_key);
    auto outcome = ddbc.GetItem(req);
    if (outcome.IsSuccess())
    {
      auto map = outcome.GetResult().GetItem();
      auto it = map.find("min_instances");
      if (it != map.end())
      {
        auto min_instances = std::atoi(it->second.GetN().c_str());
        std::string instance_name = ec2i.user_data_js["min_instance_name"];

        Aws::Client::ClientConfiguration ec2_config;
        ec2_config.region = ec2i.default_region;
        ec2_config.executor = ec2i.executor;
        Aws::EC2::EC2Client ec2(ec2_config);

        Aws::EC2::Model::DescribeInstancesRequest request;
        Aws::EC2::Model::Filter filter1;
        filter1.SetName("tag:Name");
        filter1.AddValues(instance_name);
        request.AddFilters(filter1);
        Aws::EC2::Model::Filter filter2;
        filter2.SetName("instance-state-name");
        filter2.AddValues("running");
        request.AddFilters(filter2);

        bool done = false;
        int total_instances = 0;
        while (!done)
        {
          auto outcome = ec2.DescribeInstances(request);
          if (outcome.IsSuccess())
          {
            const auto &reservations = outcome.GetResult().GetReservations();
            for (const auto &reservation : reservations)
            {
              const auto &instances = reservation.GetInstances();
              total_instances += instances.size();
              if (total_instances > min_instances)
                return true;
            }
            if (outcome.GetResult().GetNextToken().size() > 0)
              request.SetNextToken(outcome.GetResult().GetNextToken());
            else
              done = true;
          }
          else
            return true;
        }

        return total_instances > min_instances;
      }
    }
  }
  return true;
}

} // namespace

void run_worker(const ec2_info &ec2i)
{
  Aws::Client::ClientConfiguration config;
  if (ec2i.user_data_js.find("task_queue_region") != ec2i.user_data_js.end())
    config.region = ec2i.user_data_js["task_queue_region"];
  else
    config.region = ec2i.default_region;
  config.executor = ec2i.executor;

  std::string queue_url = ec2i.user_data_js["task_queue_url"];

  Aws::SQS::SQSClient client(config);
  std::mutex keep_alive_mutex;
  std::map<Aws::String, Aws::String> keep_alive_set;
  bool stop = false;
  auto timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  struct itimerspec t_spec = {0};
  t_spec.it_value = cur_time() + 30;
  timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);

  std::thread keep_alive_thread([&client, &keep_alive_mutex, &keep_alive_set,
                                 &stop, &timerfd, &queue_url] {
    while (true)
    {
      struct pollfd pfd;
      pfd.fd = timerfd;
      pfd.events = POLLIN;
      poll(&pfd, 1, 31000);

      std::unique_lock<std::mutex> l(keep_alive_mutex);
      if (stop)
        break;

      auto num_messages = keep_alive_set.size();
      if (num_messages > 0)
      {
        Aws::SQS::Model::ChangeMessageVisibilityBatchRequest req;
        Aws::Vector<Aws::Vector<Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v;
        int index = 0;
        for (auto it : keep_alive_set)
        {
          Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry ent;
          std::ostringstream str;
          if (index % 10 == 0)
            entries_v.push_back(Aws::Vector<Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry>());
          str << "message_" << ++index;
          ent.WithReceiptHandle(it.first).WithVisibilityTimeout(60).WithId(str.str());
          entries_v.back().push_back(ent);
        }
        l.unlock();
        for (auto &entries : entries_v)
        {
          req.WithQueueUrl(queue_url).WithEntries(entries);
          auto outcome = client.ChangeMessageVisibilityBatch(req);
          if (!outcome.IsSuccess())
            anon_log("ChangeMessageVisibilityBatch failed: " << outcome.GetError());
        }
      }

      struct itimerspec t_spec = {0};
      t_spec.it_value = cur_time() + 30;
      timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);
    }
  });

  while (true)
  {
    Aws::SQS::Model::ReceiveMessageRequest req;
    // be careful with the timeout for now.
    // we are using the default libcurl and it seems to have a timeout
    // that is less than 10 seconds.  If we set this value to 10 seconds
    // the aws code internally sees a timeout error from libcurl, which it
    // then decides to retry the request.  To get it to return from this
    // function we need to set the timeout less than whatever the libcurl
    // timeout is set to.
    req.WithQueueUrl(queue_url).WithMaxNumberOfMessages(1).WithWaitTimeSeconds(5);
    Aws::Vector<Aws::SQS::Model::QueueAttributeName> att;
    att.push_back(Aws::SQS::Model::QueueAttributeName::All);
    req.WithAttributeNames(std::move(att));

    auto outcome = client.ReceiveMessage(req);
    if (!outcome.IsSuccess())
    {
      anon_log("ReceiveMessage failed: " << outcome.GetError());
      break;
    }
    auto &messages = outcome.GetResult().GetMessages();
    if (messages.size() > 0)
    {
      {
        std::unique_lock<std::mutex> l(keep_alive_mutex);
        for (auto &m : messages)
          keep_alive_set[m.GetReceiptHandle()] = m.GetMessageId();
      }
      struct itimerspec t_spec = {0};
      timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);

      for (auto &m : messages)
      {
        auto bash_cmd = get_body(m);

        const auto max_retries = 2;

        const auto &att = m.GetAttributes();
        auto arc = att.find(Aws::SQS::Model::MessageSystemAttributeName::ApproximateReceiveCount);
        auto approx_receive_count = 1000;
        if (arc != att.end())
          approx_receive_count = std::stoull(arc->second);

        auto pid = fork();
        if (pid == -1)
          do_error("fork()");
        if (pid != 0)
        {
          // the calling parent
          int status;
          auto w = waitpid(-1, &status, WUNTRACED | WCONTINUED);
          if (w == -1)
            do_error("waitpid(-1, &status, WUNTRACED | WCONTINUED)");

          auto script_exited_zero = false;
          if (WIFEXITED(status))
          {
            anon_log("bash exited with exit code: " << WEXITSTATUS(status));
            script_exited_zero = WEXITSTATUS(status) == 0;
          }
          else if (WIFSIGNALED(status))
            anon_log("bash killed by signal: " << WTERMSIG(status));
          else if (WIFSTOPPED(status))
            anon_log("bash stopped by signal: " << WSTOPSIG(status));

          {
            // regardless of whether the bash command succeeded or not
            // we don't want to keep calling ChangeVisibilityStatus on this message
            std::unique_lock<std::mutex> l(keep_alive_mutex);
            keep_alive_set.erase(m.GetReceiptHandle());
          }

          // if the script succeeded, or if we have failed too many times,
          // delete the message from sqs
          if (script_exited_zero || approx_receive_count >= max_retries)
          {
            Aws::SQS::Model::DeleteMessageRequest req;
            req.WithQueueUrl(queue_url).WithReceiptHandle(m.GetReceiptHandle());
            auto outcome = client.DeleteMessage(req);
            if (!outcome.IsSuccess())
              anon_log("DeleteMessage failed: " << outcome.GetError());
          }
        }
        else
        {
          // the child process
          auto bash_file_name = "/bin/bash";
          auto bash_fd = open(bash_file_name, O_RDONLY);
          if (bash_fd == -1)
            do_error("open(\"" << bash_file_name << "\", O_RDONLY)");

          const char *dash_c = "-c";
          const char *script = bash_cmd.c_str();
          const char *do_retry = approx_receive_count < max_retries ? "1" : "0";
          char *args[]{
              const_cast<char *>(bash_file_name),
              const_cast<char *>(dash_c),
              const_cast<char *>(script),
              const_cast<char *>(do_retry),
              0};

          fexecve(bash_fd, &args[0], environ);

          // if fexecve succeeded then we never get here.  So getting here is a failure,
          // but we are already in the child process at this point, so we do what we can
          // to signifify the error and then exit
          fprintf(stderr, "fexecve(%d, ...) failed with errno: %d - %s\n", bash_fd, errno, strerror(errno));
          exit(1);
        }
      }
    }
    else
    {
      // no messages after 10 seconds.  Check for shutdown
      anon_log("no messages after wating period");
      if (should_shut_down(ec2i))
      {
	anon_log("no reason to keep running, shutting down");
        break;
      }
    }
  }

  {
    std::unique_lock<std::mutex> l(keep_alive_mutex);
    stop = true;
    struct itimerspec t_spec = {0};
    t_spec.it_value = cur_time();
    timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);
  }
  keep_alive_thread.join();
}
<|endoftext|>


<commit_before>#ifndef _vector_hpp_1337420
#define _vector_hpp_1337420

#include <cstdlib>
#include <new>
#include <utility>
#include <memory>
#include <type_traits>
#include <iterator>

#include "../core/algorithm.hpp"
#include "../ztl_base.hpp"

__ztl_namespace_start
	template <class T>
	class vector {
	public:
		typedef T						value_type;
		typedef T&						reference;
		typedef T*						iterator;
		typedef const T*						const_iterator;
		typedef __stl::random_access_iterator_tag		iterator_category;
		typedef __stl::reverse_iterator<const_iterator>		const_reverse_iterator;
		typedef __stl::reverse_iterator<iterator>		reverse_iterator;
		typedef size_t						size_type;
		typedef int						difference_type;

	private:
		iterator p_begin;
		iterator p_last;
		iterator p_end;

		inline void enlarge() {
			enlarge((p_end - p_begin + 1) * 2);
		}

		inline void enlarge(int size) {
			int n = p_last - p_begin;
			p_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size);
			p_end = p_begin + size - 1;
			p_last = p_begin + n;
		}

	public:
		vector() {
			p_begin = p_end = (iterator)malloc(sizeof(value_type));
			p_last = p_begin - 1;
		}

		vector(size_type starting_size) {
			p_begin = (iterator)calloc(starting_size, sizeof(value_type));
			p_end = p_begin + starting_size - 1;
			p_last = p_end - 1;
		}

		vector(size_type starting_size, T init_value) {
			p_begin = (iterator)malloc(sizeof(value_type) * starting_size);
			p_end = p_begin + starting_size - 1;
			p_last = p_begin - 1;

			if(sizeof(T) == 1) memset(p_begin, (int)init_value, starting_size);
			if(sizeof(T) == 4) memset32(p_begin, init_value, starting_size);
			else memset_custom(p_begin, init_value, starting_size);
		}

		~vector() {
			if (!__stl::is_trivially_destructible<value_type>::value) {
				++p_last;
				while (--p_last >= p_begin) {
					(p_last)->~T();
				}
			}

			free(p_begin);
		}

		template<class... Args>
		inline void emplace_back(Args&&... args) {
			if (p_last == p_end) enlarge();
			new (++p_last) T(__stl::forward<Args>(args)...);
		}

		inline void push_back(const T& other) {
			if (p_last == p_end) enlarge();
			new (++p_last) T(other);
		}

		inline void pop_back() {
			if (empty()) return;
			(p_last--)->~T();
		}

		/* Access elements */
		inline reference at(unsigned int id) {
			if (!(id < size()))
				throw __stl::out_of_range("Index out of range");
			return p_begin[id];
		}

		inline const reference at(unsigned int id) const {
			if (!(id < size()))
				throw __stl::out_of_range("Index out of range");
			return p_begin[id];
		}

		inline reference operator[](unsigned int id) { return p_begin[id]; }
		inline const reference operator[](unsigned int id) const { return p_begin[id]; }

		/* Iterators */
		inline iterator				begin() { return p_begin; }
		inline iterator				end() { return p_last + 1; }
		inline const_iterator			cbegin() const { return p_begin; }
		inline const_iterator			cend() const { return p_last + 1; }
		inline reverse_iterator			rbegin() { return reverse_iterator(end()); }
		inline reverse_iterator			rend() { return reverse_iterator(p_begin); }
		inline const_reverse_iterator		crbegin() const { return const_reverse_iterator(cend()); }
		inline const_reverse_iterator		crend() const { return const_reverse_iterator(p_begin); }

		inline reference			first() { return *p_begin; }
		inline const reference			first() const { return *p_begin; }
		inline reference			last() { return *p_last; }
		inline const reference			last() const { return *p_last; }

		/* Size / Allocation */
		inline bool				empty() const { return size() == 0; }
		inline size_type			size() const { return p_last - p_begin + 1; }
		inline size_type			max_size() const { return size_type(-1); }
		inline size_type			reserved() const { return p_end - p_begin + 1; }
		inline void				reserve(size_type num) { enlarge(num); }
		inline void				clear() { erase(p_begin, p_last); }
		inline void				erase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); }
		inline void				erase(iterator pa, iterator pb) {
			if (!__stl::is_trivially_destructible<value_type>::value) {
				iterator a = pa - 1;
				while (a < pb) (++a)->~T();
			}

			memmove(pa, pb + 1, sizeof(value_type) * (p_last - pb));
			p_last = pa + (p_last - pb) - 1;
		}
	};

__ztl_namespace_end

#endif /* _vector_hpp_1337420 */
<commit_msg>Fixed allocation issues<commit_after>#ifndef _vector_hpp_1337420
#define _vector_hpp_1337420

#include <cstdlib>
#include <new>
#include <utility>
#include <memory>
#include <type_traits>
#include <iterator>

#include "../core/algorithm.hpp"
#include "../ztl_base.hpp"

__ztl_namespace_start
	template <class T>
	class vector {
	public:
		typedef T						value_type;
		typedef T&						reference;
		typedef T*						iterator;
		typedef const T*						const_iterator;
		typedef __stl::random_access_iterator_tag		iterator_category;
		typedef __stl::reverse_iterator<const_iterator>		const_reverse_iterator;
		typedef __stl::reverse_iterator<iterator>		reverse_iterator;
		typedef size_t						size_type;
		typedef int						difference_type;

	private:
		iterator p_begin;
		iterator p_last;
		iterator p_end;

		inline void enlarge() {
			enlarge((p_end - p_begin + 1) * 2);
		}

		inline void enlarge(int size) {
			int n = p_last - p_begin;
			p_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size);
			p_end = p_begin + size - 1;
			p_last = p_begin + n;
		}

	public:
		vector() {
			p_begin = p_end = (iterator)malloc(sizeof(value_type));
			p_last = p_begin - 1;
		}

		vector(size_type starting_size) {
			p_begin = (iterator)calloc(starting_size, sizeof(value_type));
			p_end = p_begin + starting_size ;
			p_last = p_end - 1;
		}

		vector(size_type starting_size, T init_value) {
			p_begin = (iterator)malloc(sizeof(value_type) * starting_size);
			p_end = p_begin + starting_size;
			p_last = p_begin - 1;

			if(sizeof(T) == 1) memset(p_begin, (int)init_value, starting_size);
			if(sizeof(T) == 4) memset32(p_begin, init_value, starting_size);
			else memset_custom(p_begin, init_value, starting_size);
		}

		~vector() {
			if (!__stl::is_trivially_destructible<value_type>::value) {
				++p_last;
				while (--p_last >= p_begin) {
					(p_last)->~T();
				}
			}

			free(p_begin);
		}

		template<class... Args>
		inline void emplace_back(Args&&... args) {
			if (p_last == p_end) enlarge();
			new (++p_last) T(__stl::forward<Args>(args)...);
		}

		inline void push_back(const T& other) {
			if (p_last == p_end) enlarge();
			new (++p_last) T(other);
		}

		inline void pop_back() {
			if (empty()) return;
			(p_last--)->~T();
		}

		/* Access elements */
		inline reference at(unsigned int id) {
			if (!(id < size()))
				throw __stl::out_of_range("Index out of range");
			return p_begin[id];
		}

		inline const reference at(unsigned int id) const {
			if (!(id < size()))
				throw __stl::out_of_range("Index out of range");
			return p_begin[id];
		}

		inline reference operator[](unsigned int id) { return p_begin[id]; }
		inline const reference operator[](unsigned int id) const { return p_begin[id]; }

		/* Iterators */
		inline iterator				begin() { return p_begin; }
		inline iterator				end() { return p_last + 1; }
		inline const_iterator			cbegin() const { return p_begin; }
		inline const_iterator			cend() const { return p_last + 1; }
		inline reverse_iterator			rbegin() { return reverse_iterator(end()); }
		inline reverse_iterator			rend() { return reverse_iterator(p_begin); }
		inline const_reverse_iterator		crbegin() const { return const_reverse_iterator(cend()); }
		inline const_reverse_iterator		crend() const { return const_reverse_iterator(p_begin); }

		inline reference			first() { return *p_begin; }
		inline const reference			first() const { return *p_begin; }
		inline reference			last() { return *p_last; }
		inline const reference			last() const { return *p_last; }

		/* Size / Allocation */
		inline bool				empty() const { return size() == 0; }
		inline size_type			size() const { return p_last - p_begin + 1; }
		inline size_type			max_size() const { return size_type(-1); }
		inline size_type			reserved() const { return p_end - p_begin + 1; }
		inline void				reserve(size_type num) { enlarge(num); }
		inline void				clear() { erase(p_begin, p_last); }
		inline void				erase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); }
		inline void				erase(iterator pa, iterator pb) {
			if (!__stl::is_trivially_destructible<value_type>::value) {
				iterator a = pa - 1;
				while (a < pb) (++a)->~T();
			}

			memmove(pa, pb + 1, sizeof(value_type) * (p_last - pb));
			p_last = pa + (p_last - pb) - 1;
		}
	};

__ztl_namespace_end

#endif /* _vector_hpp_1337420 */
<|endoftext|>


<commit_before>//
// Defines main() function and command-line arguments used by ccons.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include <iostream>
#include <fstream>
#include <sstream>

#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/StringExtras.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/Signals.h>
#include <llvm-c/Target.h>

#include "Console.h"
#include "EditLineReader.h"
#include "InternalCommands.h"
#include "RemoteConsole.h"

using std::string;
using ccons::Console;
using ccons::IConsole;
using ccons::RemoteConsole;
using ccons::SerializedOutputConsole;
using ccons::LineReader;
using ccons::EditLineReader;
using ccons::StdInLineReader;

static llvm::cl::opt<bool>
	DebugMode("ccons-debug",
			llvm::cl::desc("Print debugging information"));
static llvm::cl::opt<bool>
	UseStdIo("ccons-use-std-io",
			llvm::cl::desc("Use standard IO for input and output"));
static llvm::cl::opt<bool>
	SerializedOutput("ccons-serialized-output",
			llvm::cl::desc("Output will be serialized"));
static llvm::cl::opt<bool>
	MultiProcess("ccons-multi-process",
			llvm::cl::desc("Run in multi-process mode"));

static IConsole * createConsole()
{
	if (MultiProcess)
		return new RemoteConsole(DebugMode);
	else if (SerializedOutput)
		return new SerializedOutputConsole(DebugMode);
	else
		return new Console(DebugMode);
}

static LineReader * createReader()
{
	if (UseStdIo)
		return new StdInLineReader;
	else
		return new EditLineReader;
}

extern "C" void LLVMInitializeX86TargetMC();

int main(const int argc, char **argv)
{
	llvm::cl::SetVersionPrinter(ccons::PrintVersionInformation);
	llvm::cl::ParseCommandLineOptions(argc, argv, "ccons Interactive C Console\n",
	                                  false/*, "ccons-"*/);

	if (DebugMode && !SerializedOutput) {
		std::cerr << "NOTE: Debugging information will be displayed.\n";
		llvm::sys::PrintStackTraceOnErrorSignal();
	}

	LLVMInitializeNativeTarget();

	// FIXME: This shouldn't be needed - it should have been done by llvm::InitializeNativeTarget().
	// TODO: Bisect builds and report a bug to LLVM if this doesn't disappear soon. I noticed the breakage at r139193 of LLVM.
	LLVMInitializeX86TargetMC();

	llvm::OwningPtr<IConsole> console(createConsole());
	llvm::OwningPtr<LineReader> reader(createReader());

	const char *line = reader->readLine(console->prompt(), console->input());
	while (line) {
		console->process(line);
		line = reader->readLine(console->prompt(), console->input());
	}

	return 0;
}

<commit_msg>remove FIXME/TODO since the llvm bug has been fixed<commit_after>//
// Defines main() function and command-line arguments used by ccons.
//
// Part of ccons, the interactive console for the C programming language.
//
// Copyright (c) 2009 Alexei Svitkine. This file is distributed under the
// terms of MIT Open Source License. See file LICENSE for details.
//

#include <iostream>
#include <fstream>
#include <sstream>

#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/StringExtras.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/Signals.h>
#include <llvm-c/Target.h>

#include "Console.h"
#include "EditLineReader.h"
#include "InternalCommands.h"
#include "RemoteConsole.h"

using std::string;
using ccons::Console;
using ccons::IConsole;
using ccons::RemoteConsole;
using ccons::SerializedOutputConsole;
using ccons::LineReader;
using ccons::EditLineReader;
using ccons::StdInLineReader;

static llvm::cl::opt<bool>
	DebugMode("ccons-debug",
			llvm::cl::desc("Print debugging information"));
static llvm::cl::opt<bool>
	UseStdIo("ccons-use-std-io",
			llvm::cl::desc("Use standard IO for input and output"));
static llvm::cl::opt<bool>
	SerializedOutput("ccons-serialized-output",
			llvm::cl::desc("Output will be serialized"));
static llvm::cl::opt<bool>
	MultiProcess("ccons-multi-process",
			llvm::cl::desc("Run in multi-process mode"));

static IConsole * createConsole()
{
	if (MultiProcess)
		return new RemoteConsole(DebugMode);
	else if (SerializedOutput)
		return new SerializedOutputConsole(DebugMode);
	else
		return new Console(DebugMode);
}

static LineReader * createReader()
{
	if (UseStdIo)
		return new StdInLineReader;
	else
		return new EditLineReader;
}

extern "C" void LLVMInitializeX86TargetMC();

int main(const int argc, char **argv)
{
	llvm::cl::SetVersionPrinter(ccons::PrintVersionInformation);
	llvm::cl::ParseCommandLineOptions(argc, argv, "ccons Interactive C Console\n",
	                                  false/*, "ccons-"*/);

	if (DebugMode && !SerializedOutput) {
		std::cerr << "NOTE: Debugging information will be displayed.\n";
		llvm::sys::PrintStackTraceOnErrorSignal();
	}

	LLVMInitializeNativeTarget();

	llvm::OwningPtr<IConsole> console(createConsole());
	llvm::OwningPtr<LineReader> reader(createReader());

	const char *line = reader->readLine(console->prompt(), console->input());
	while (line) {
		console->process(line);
		line = reader->readLine(console->prompt(), console->input());
	}

	return 0;
}

<|endoftext|>