<commit_before>#include "QmitkNodeTableViewKeyFilter.h"

#include <QKeyEvent>
#include <QKeySequence>
#include <src/internal/QmitkDataManagerView.h>

QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter( QObject* _DataManagerView )
: QObject(_DataManagerView)
{
  m_PreferencesService =
    cherry::Platform::GetServiceRegistry().GetServiceById<cherry::IPreferencesService>(cherry::IPreferencesService::ID);
}

bool QmitkNodeTableViewKeyFilter::eventFilter( QObject *obj, QEvent *event )
{
  QmitkDataManagerView* _DataManagerView = qobject_cast<QmitkDataManagerView*>(this->parent());
  if (event->type() == QEvent::KeyPress && _DataManagerView)
  {
    cherry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock();
    cherry::IPreferences::Pointer nodeTableKeyPrefs = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys");

    QKeySequence _MakeAllInvisible = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Make all nodes invisible", "Ctrl+, V")));
    QKeySequence _ToggleVisibility = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Toggle visibility of selected nodes", "V")));
    QKeySequence _DeleteSelectedNodes = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Delete selected nodes", "Del")));
    QKeySequence _Reinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Reinit selected nodes", "R")));
    QKeySequence _GlobalReinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Global Reinit", "Ctrl+, R")));
    QKeySequence _Save = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Save selected nodes", "Ctrl+, S")));
    QKeySequence _Load = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Load", "Ctrl+, L")));
    QKeySequence _ShowInfo = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Show Node Information", "Ctrl+, I")));

    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

    QKeySequence _KeySequence = QKeySequence(keyEvent->modifiers(), keyEvent->key());
    // if no modifier was pressed the sequence is now empty
    if(_KeySequence.isEmpty())
      _KeySequence = QKeySequence(keyEvent->key());

    if(_KeySequence == _MakeAllInvisible)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->MakeAllNodesInvisible(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _DeleteSelectedNodes)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->RemoveSelectedNodes(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _ToggleVisibility)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->ToggleVisibilityOfSelectedNodes(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _Reinit)
    {
      _DataManagerView->ReinitSelectedNodes(false);
      return true;
    }
    else if(_KeySequence == _GlobalReinit)
    {
      _DataManagerView->GlobalReinit(false);
      return true;
    }
    else if(_KeySequence == _Save)
    {
      _DataManagerView->SaveSelectedNodes(false);
      return true;
    }
    else if(_KeySequence == _Load)
    {
      _DataManagerView->Load(false);
      return true;
    }
    else if(_KeySequence == _ShowInfo)
    {
      _DataManagerView->ShowInfoDialogForSelectedNodes(false);
      return true;
    }
  }
  // standard event processing
  return QObject::eventFilter(obj, event);
}<commit_msg>COMP: fixing include path<commit_after>#include "QmitkNodeTableViewKeyFilter.h"

#include <QKeyEvent>
#include <QKeySequence>
#include "../QmitkDataManagerView.h"

QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter( QObject* _DataManagerView )
: QObject(_DataManagerView)
{
  m_PreferencesService =
    cherry::Platform::GetServiceRegistry().GetServiceById<cherry::IPreferencesService>(cherry::IPreferencesService::ID);
}

bool QmitkNodeTableViewKeyFilter::eventFilter( QObject *obj, QEvent *event )
{
  QmitkDataManagerView* _DataManagerView = qobject_cast<QmitkDataManagerView*>(this->parent());
  if (event->type() == QEvent::KeyPress && _DataManagerView)
  {
    cherry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock();
    cherry::IPreferences::Pointer nodeTableKeyPrefs = prefService->GetSystemPreferences()->Node("/DataManager/Hotkeys");

    QKeySequence _MakeAllInvisible = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Make all nodes invisible", "Ctrl+, V")));
    QKeySequence _ToggleVisibility = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Toggle visibility of selected nodes", "V")));
    QKeySequence _DeleteSelectedNodes = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Delete selected nodes", "Del")));
    QKeySequence _Reinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Reinit selected nodes", "R")));
    QKeySequence _GlobalReinit = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Global Reinit", "Ctrl+, R")));
    QKeySequence _Save = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Save selected nodes", "Ctrl+, S")));
    QKeySequence _Load = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Load", "Ctrl+, L")));
    QKeySequence _ShowInfo = QKeySequence(QString::fromStdString(nodeTableKeyPrefs->Get("Show Node Information", "Ctrl+, I")));

    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

    QKeySequence _KeySequence = QKeySequence(keyEvent->modifiers(), keyEvent->key());
    // if no modifier was pressed the sequence is now empty
    if(_KeySequence.isEmpty())
      _KeySequence = QKeySequence(keyEvent->key());

    if(_KeySequence == _MakeAllInvisible)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->MakeAllNodesInvisible(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _DeleteSelectedNodes)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->RemoveSelectedNodes(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _ToggleVisibility)
    {
      // trigger deletion of selected node(s)
      _DataManagerView->ToggleVisibilityOfSelectedNodes(false);
      // return true: this means the delete key event is not send to the table
      return true;
    }
    else if(_KeySequence == _Reinit)
    {
      _DataManagerView->ReinitSelectedNodes(false);
      return true;
    }
    else if(_KeySequence == _GlobalReinit)
    {
      _DataManagerView->GlobalReinit(false);
      return true;
    }
    else if(_KeySequence == _Save)
    {
      _DataManagerView->SaveSelectedNodes(false);
      return true;
    }
    else if(_KeySequence == _Load)
    {
      _DataManagerView->Load(false);
      return true;
    }
    else if(_KeySequence == _ShowInfo)
    {
      _DataManagerView->ShowInfoDialogForSelectedNodes(false);
      return true;
    }
  }
  // standard event processing
  return QObject::eventFilter(obj, event);
}
<|endoftext|>


<commit_before>/*
 * RWLock
 * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
 * Copyright (C) 2011 by NeoSmart Technologies
 * This code is released under the terms of the MIT License
*/

#include "stdafx.h"
#include "RWLock.h"

#include <tchar.h>
#include <assert.h>
#include <stdlib.h>

__forceinline __int16 ReaderCount(unsigned __int32 lock)
{
	return lock & 0x00007FFF;
}

__forceinline __int32 SetReaders(unsigned __int32 lock, unsigned __int16 readers)
{
	return (lock & ~0x00007FFF) | readers;
}

__forceinline __int16 WaitingCount(unsigned __int32 lock)
{
	return (lock & 0x3FFF8000) >> 15;
}

__forceinline __int32 SetWaiting(unsigned __int32 lock, unsigned __int16 waiting)
{
	return (lock & ~0x3FFF8000) | (waiting << 15);
}

__forceinline bool Writer(unsigned __int32 lock)
{
	return (lock & 0x40000000) != 0;
}

__forceinline __int32 SetWriter(unsigned __int32 lock, bool writer)
{
	if(writer)
		return lock | 0x40000000;
	else
		return lock & ~0x40000000;
}

__forceinline bool AllClear(unsigned __int32 lock)
{
	return (lock & 0x40007FFF) == 0;
}

__forceinline bool Initialized(unsigned __int32 lock)
{
	return (lock & 0x80000000) != 0;
}

__forceinline __int32 SetInitialized(unsigned __int32 lock, bool initialized)
{
	if(initialized)
		return lock | 0x80000000;
	else
		return lock & ~0x80000000;
}

RWLockIPC::RWLockIPC(unsigned __int32 *lock, LPCTSTR guid)
{
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = &sd;
	InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
	SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);

	_lock = lock;

	//Create local volatile pointer for double-checked locking to work
	volatile unsigned __int32 *vLock = lock;

	_event = CreateEvent(&sa, FALSE, FALSE, guid);

	if(!Initialized(*vLock))
	{
		HANDLE hMutex = CreateMutex(&sa, FALSE, guid);
		WaitForSingleObject(hMutex, INFINITE);

		if(!Initialized(*vLock))
		{
			*vLock = RWLOCK_INIT;
			*vLock = SetInitialized(*vLock, true);
		}

		ReleaseMutex(hMutex);
		CloseHandle(hMutex);
	}
}

RWLockIPC::~RWLockIPC()
{
	CloseHandle(_event);
}

void RWLockIPC::StartRead()
{
	for(int i = 0; ; ++i)
	{
		__int32 temp = *_lock;
		if(!Writer(temp))
		{
			if(InterlockedCompareExchange(_lock, SetReaders(temp, ReaderCount(temp) + 1), temp) == temp)
				return;
			else
				continue;
		}
		else
		{
			if(i < MAX_SPIN)
			{
				YieldProcessor();
				continue;
			}

			//The pending write operation is taking too long, so we'll drop to the kernel and wait
			if(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp)
				continue;

			i = 0; //Reset the spincount for the next time
			WaitForSingleObject(_event, INFINITE);

			do
			{
				temp = *_lock;
			} while(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp);
		}
	}
}

void RWLockIPC::StartWrite()
{
	for(int i = 0; ; ++i)
	{
		__int32 temp = *_lock;
		if(AllClear(temp))
		{
			if(InterlockedCompareExchange(_lock, SetWriter(temp, true), temp) == temp)
				return;
			else
				continue;
		}
		else
		{
			if(i < MAX_SPIN)
			{
				YieldProcessor();
				continue;
			}

			//The pending read operations are taking too long, so we'll drop to the kernel and wait
			if(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp)
				continue;

			i = 0; //Reset the spincount for the next time
			WaitForSingleObject(_event, INFINITE);

			do
			{
				temp = *_lock;
			} while(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp);
		}
	}
}

void RWLockIPC::EndRead()
{
	while(true)
	{
		__int32 temp = *_lock;
		assert(ReaderCount(temp) > 0);

		if(ReaderCount(temp) == 1 && WaitingCount(temp) != 0)
		{
			//Note: this isn't nor has to be thread-safe, as the worst a duplicate notification can do
			//is cause a waiting to reader to wake, perform a spinlock, then go back to sleep

			//We're the last reader and there's a pending write
			//Wake one waiting writer
			SetEvent(_event);
		}

		//Decrement reader count
		if(InterlockedCompareExchange(_lock, SetReaders(temp, ReaderCount(temp) - 1), temp) == temp)
			break;
	}
}

void RWLockIPC::EndWrite()
{
	while(true)
	{
		__int32 temp;

		while(true)
		{
			temp = *_lock;
			assert(Writer(temp));
			if(WaitingCount(temp) == 0)
				break;

			//Note: this is thread-safe (there's guaranteed not to be another EndWrite simultaneously)
			//Wake all waiting readers or writers, loop until wake confirmation is received
			SetEvent(_event);
		}

		//Decrement writer count
		if(InterlockedCompareExchange(_lock, SetWriter(temp, false), temp) == temp)
			break;
	}
}

RWLock::RWLock()
	: _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL)
{
}

RWLock::~RWLock()
{
	delete _lock;
}

void RWLock::StartRead()
{
	_rwLock.StartRead();
}

void RWLock::StartWrite()
{
	_rwLock.StartWrite();
}

void RWLock::EndRead()
{
	_rwLock.EndRead();
}

void RWLock::EndWrite()
{
	_rwLock.EndWrite();
}

struct THREAD_ENTRY
{
	SLIST_ENTRY ItemEntry;
	unsigned int* ThreadPointer;
};

RWLockIPCReentrant::RWLockIPCReentrant(unsigned __int32 *lock, LPCTSTR guid)
	: _rwLock(lock, guid)
{
	_tlsIndex = TlsAlloc();

	_threadPointers = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT);
	InitializeSListHead(_threadPointers);
}

RWLockIPCReentrant::~RWLockIPCReentrant()
{
	THREAD_ENTRY *entry;
	while((entry = (THREAD_ENTRY*) InterlockedPopEntrySList(_threadPointers)) != NULL)
	{
		delete entry->ThreadPointer;
		_aligned_free(entry);
	}

	_aligned_free(_threadPointers);

	TlsFree(_tlsIndex);
}

void RWLockIPCReentrant::StartRead()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	if(InterlockedIncrement(threadCounter) == 1)
		_rwLock.StartRead();
}

void RWLockIPCReentrant::StartWrite()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	if(InterlockedIncrement(threadCounter) == 1)
		_rwLock.StartWrite();
}

void RWLockIPCReentrant::EndRead()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	assert(*threadCounter > 0);
	if(InterlockedDecrement(threadCounter) == 0)
		_rwLock.EndRead();
}

void RWLockIPCReentrant::EndWrite()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	assert(*threadCounter > 0);
	if(InterlockedDecrement(threadCounter) == 0)
		_rwLock.EndWrite();
}

RWLockReentrant::RWLockReentrant()
	: _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL)
{
}

RWLockReentrant::~RWLockReentrant()
{
	delete _lock;
}

void RWLockReentrant::StartRead()
{
	_rwLock.StartRead();
}

void RWLockReentrant::StartWrite()
{
	_rwLock.StartWrite();
}

void RWLockReentrant::EndRead()
{
	_rwLock.EndRead();
}

void RWLockReentrant::EndWrite()
{
	_rwLock.EndWrite();
}
<commit_msg>Fixed signed-unsigned comparison mismatch<commit_after>/*
 * RWLock
 * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
 * Copyright (C) 2011 by NeoSmart Technologies
 * This code is released under the terms of the MIT License
*/

#include "stdafx.h"
#include "RWLock.h"

#include <tchar.h>
#include <assert.h>
#include <stdlib.h>

__forceinline __int16 ReaderCount(unsigned __int32 lock)
{
	return lock & 0x00007FFF;
}

__forceinline __int32 SetReaders(unsigned __int32 lock, unsigned __int16 readers)
{
	return (lock & ~0x00007FFF) | readers;
}

__forceinline __int16 WaitingCount(unsigned __int32 lock)
{
	return (lock & 0x3FFF8000) >> 15;
}

__forceinline __int32 SetWaiting(unsigned __int32 lock, unsigned __int16 waiting)
{
	return (lock & ~0x3FFF8000) | (waiting << 15);
}

__forceinline bool Writer(unsigned __int32 lock)
{
	return (lock & 0x40000000) != 0;
}

__forceinline __int32 SetWriter(unsigned __int32 lock, bool writer)
{
	if(writer)
		return lock | 0x40000000;
	else
		return lock & ~0x40000000;
}

__forceinline bool AllClear(unsigned __int32 lock)
{
	return (lock & 0x40007FFF) == 0;
}

__forceinline bool Initialized(unsigned __int32 lock)
{
	return (lock & 0x80000000) != 0;
}

__forceinline __int32 SetInitialized(unsigned __int32 lock, bool initialized)
{
	if(initialized)
		return lock | 0x80000000;
	else
		return lock & ~0x80000000;
}

RWLockIPC::RWLockIPC(unsigned __int32 *lock, LPCTSTR guid)
{
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = &sd;
	InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
	SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);

	_lock = lock;

	//Create local volatile pointer for double-checked locking to work
	volatile unsigned __int32 *vLock = lock;

	_event = CreateEvent(&sa, FALSE, FALSE, guid);

	if(!Initialized(*vLock))
	{
		HANDLE hMutex = CreateMutex(&sa, FALSE, guid);
		WaitForSingleObject(hMutex, INFINITE);

		if(!Initialized(*vLock))
		{
			*vLock = RWLOCK_INIT;
			*vLock = SetInitialized(*vLock, true);
		}

		ReleaseMutex(hMutex);
		CloseHandle(hMutex);
	}
}

RWLockIPC::~RWLockIPC()
{
	CloseHandle(_event);
}

void RWLockIPC::StartRead()
{
	for(int i = 0; ; ++i)
	{
		unsigned __int32 temp = *_lock;
		if(!Writer(temp))
		{
			if(InterlockedCompareExchange(_lock, SetReaders(temp, ReaderCount(temp) + 1), temp) == temp)
				return;
			else
				continue;
		}
		else
		{
			if(i < MAX_SPIN)
			{
				YieldProcessor();
				continue;
			}

			//The pending write operation is taking too long, so we'll drop to the kernel and wait
			if(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp)
				continue;

			i = 0; //Reset the spincount for the next time
			WaitForSingleObject(_event, INFINITE);

			do
			{
				temp = *_lock;
			} while(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp);
		}
	}
}

void RWLockIPC::StartWrite()
{
	for(int i = 0; ; ++i)
	{
		unsigned __int32 temp = *_lock;
		if(AllClear(temp))
		{
			if(InterlockedCompareExchange(_lock, SetWriter(temp, true), temp) == temp)
				return;
			else
				continue;
		}
		else
		{
			if(i < MAX_SPIN)
			{
				YieldProcessor();
				continue;
			}

			//The pending read operations are taking too long, so we'll drop to the kernel and wait
			if(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp)
				continue;

			i = 0; //Reset the spincount for the next time
			WaitForSingleObject(_event, INFINITE);

			do
			{
				temp = *_lock;
			} while(InterlockedCompareExchange(_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp);
		}
	}
}

void RWLockIPC::EndRead()
{
	while(true)
	{
		unsigned __int32 temp = *_lock;
		assert(ReaderCount(temp) > 0);

		if(ReaderCount(temp) == 1 && WaitingCount(temp) != 0)
		{
			//Note: this isn't nor has to be thread-safe, as the worst a duplicate notification can do
			//is cause a waiting to reader to wake, perform a spinlock, then go back to sleep

			//We're the last reader and there's a pending write
			//Wake one waiting writer
			SetEvent(_event);
		}

		//Decrement reader count
		if(InterlockedCompareExchange(_lock, SetReaders(temp, ReaderCount(temp) - 1), temp) == temp)
			break;
	}
}

void RWLockIPC::EndWrite()
{
	while(true)
	{
		unsigned __int32 temp;

		while(true)
		{
			temp = *_lock;
			assert(Writer(temp));
			if(WaitingCount(temp) == 0)
				break;

			//Note: this is thread-safe (there's guaranteed not to be another EndWrite simultaneously)
			//Wake all waiting readers or writers, loop until wake confirmation is received
			SetEvent(_event);
		}

		//Decrement writer count
		if(InterlockedCompareExchange(_lock, SetWriter(temp, false), temp) == temp)
			break;
	}
}

RWLock::RWLock()
	: _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL)
{
}

RWLock::~RWLock()
{
	delete _lock;
}

void RWLock::StartRead()
{
	_rwLock.StartRead();
}

void RWLock::StartWrite()
{
	_rwLock.StartWrite();
}

void RWLock::EndRead()
{
	_rwLock.EndRead();
}

void RWLock::EndWrite()
{
	_rwLock.EndWrite();
}

struct THREAD_ENTRY
{
	SLIST_ENTRY ItemEntry;
	unsigned int* ThreadPointer;
};

RWLockIPCReentrant::RWLockIPCReentrant(unsigned __int32 *lock, LPCTSTR guid)
	: _rwLock(lock, guid)
{
	_tlsIndex = TlsAlloc();

	_threadPointers = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT);
	InitializeSListHead(_threadPointers);
}

RWLockIPCReentrant::~RWLockIPCReentrant()
{
	THREAD_ENTRY *entry;
	while((entry = (THREAD_ENTRY*) InterlockedPopEntrySList(_threadPointers)) != NULL)
	{
		delete entry->ThreadPointer;
		_aligned_free(entry);
	}

	_aligned_free(_threadPointers);

	TlsFree(_tlsIndex);
}

void RWLockIPCReentrant::StartRead()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	if(InterlockedIncrement(threadCounter) == 1)
		_rwLock.StartRead();
}

void RWLockIPCReentrant::StartWrite()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	if(InterlockedIncrement(threadCounter) == 1)
		_rwLock.StartWrite();
}

void RWLockIPCReentrant::EndRead()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	assert(*threadCounter > 0);
	if(InterlockedDecrement(threadCounter) == 0)
		_rwLock.EndRead();
}

void RWLockIPCReentrant::EndWrite()
{
	unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex);
	if(threadCounter == NULL)
	{
		threadCounter = new unsigned int;
		*threadCounter = 0;
		TlsSetValue(_tlsIndex, threadCounter);
		THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
		entry->ThreadPointer = threadCounter;
		InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry));
	}
	assert(*threadCounter > 0);
	if(InterlockedDecrement(threadCounter) == 0)
		_rwLock.EndWrite();
}

RWLockReentrant::RWLockReentrant()
	: _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL)
{
}

RWLockReentrant::~RWLockReentrant()
{
	delete _lock;
}

void RWLockReentrant::StartRead()
{
	_rwLock.StartRead();
}

void RWLockReentrant::StartWrite()
{
	_rwLock.StartWrite();
}

void RWLockReentrant::EndRead()
{
	_rwLock.EndRead();
}

void RWLockReentrant::EndWrite()
{
	_rwLock.EndWrite();
}
<|endoftext|>


<commit_before>#include "drake/systems/framework/primitives/adder.h"

#include <stdexcept>
#include <string>

#include "drake/common/drake_assert.h"
#include "drake/drakeSystemFramework_export.h"
#include "drake/systems/framework/basic_vector.h"

namespace drake {
namespace systems {

template <typename T>
Adder<T>::Adder(int num_inputs, int length)
    : num_inputs_(num_inputs), length_(length) {

#if 0
  // What I'd prefer to look like.
  // Adder would inherit from System.
  System::add_port(InputPort("In1", length));
  System::add_port(InputPort("In2", length));

  System::add_port(OutputPort("Out", length));
#endif
}

template <typename T>
std::unique_ptr<Context<T>> Adder<T>::CreateDefaultContext() const {
  std::unique_ptr<Context<T>> context(new Context<T>);
  context->SetNumInputPorts(num_inputs_);
  return context;
}

template <typename T>
std::unique_ptr<SystemOutput<T>> Adder<T>::AllocateOutput() const {
  // An adder has just one output port, a BasicVector of the size specified
  // at construction time.
  std::unique_ptr<SystemOutput<T>> output(new SystemOutput<T>);
  {
    std::unique_ptr<BasicVector<T>> data(new BasicVector<T>(length_));
    std::unique_ptr<OutputPort<T>> port(new OutputPort<T>(std::move(data)));
    output->ports.push_back(std::move(port));
  }
  return output;
}

template <typename T>
void Adder<T>::EvalOutput(const Context<T>& context,
                          SystemOutput<T>* output) const {
  // Check that the single output port has the correct length, then zero it.
  // Checks on the output structure are assertions, not exceptions,
  // since failures would reflect a bug in the Adder implementation, not
  // user error setting up the system graph. They do not require unit test
  // coverage, and should not run in release builds.
  DRAKE_ASSERT(output->ports.size() == 1);
  VectorInterface<T>* output_port = output->ports[0]->GetMutableVectorData();
  DRAKE_ASSERT(output_port != nullptr);
  DRAKE_ASSERT(output_port->get_value().rows() == length_);
  output_port->get_mutable_value() = VectorX<T>::Zero(length_);

  // Check that there are the expected number of input ports.
  if (context.get_num_input_ports() != num_inputs_) {
    throw std::out_of_range("Expected " + std::to_string(num_inputs_) +
                            "input ports, but had " +
                            std::to_string(context.get_num_input_ports()));
  }

  // Sum each input port into the output, after checking that it has the
  // expected length.
  for (int i = 0; i < context.get_num_input_ports(); i++) {
    const VectorInterface<T>* input = context.get_vector_input(i);
    if (input == nullptr || input->get_value().rows() != length_) {
      throw std::out_of_range("Input port " + std::to_string(i) +
                              "is nullptr or has incorrect size.");
    }
    output_port->get_mutable_value() += input->get_value();
  }
}

template class DRAKESYSTEMFRAMEWORK_EXPORT Adder<double>;

}  // namespace systems
}  // namespace drake
<commit_msg>Removes comment on API<commit_after>#include "drake/systems/framework/primitives/adder.h"

#include <stdexcept>
#include <string>

#include "drake/common/drake_assert.h"
#include "drake/drakeSystemFramework_export.h"
#include "drake/systems/framework/basic_vector.h"

namespace drake {
namespace systems {

template <typename T>
Adder<T>::Adder(int num_inputs, int length)
    : num_inputs_(num_inputs), length_(length) {}

template <typename T>
std::unique_ptr<Context<T>> Adder<T>::CreateDefaultContext() const {
  std::unique_ptr<Context<T>> context(new Context<T>);
  context->SetNumInputPorts(num_inputs_);
  return context;
}

template <typename T>
std::unique_ptr<SystemOutput<T>> Adder<T>::AllocateOutput() const {
  // An adder has just one output port, a BasicVector of the size specified
  // at construction time.
  std::unique_ptr<SystemOutput<T>> output(new SystemOutput<T>);
  {
    std::unique_ptr<BasicVector<T>> data(new BasicVector<T>(length_));
    std::unique_ptr<OutputPort<T>> port(new OutputPort<T>(std::move(data)));
    output->ports.push_back(std::move(port));
  }
  return output;
}

template <typename T>
void Adder<T>::EvalOutput(const Context<T>& context,
                          SystemOutput<T>* output) const {
  // Check that the single output port has the correct length, then zero it.
  // Checks on the output structure are assertions, not exceptions,
  // since failures would reflect a bug in the Adder implementation, not
  // user error setting up the system graph. They do not require unit test
  // coverage, and should not run in release builds.
  DRAKE_ASSERT(output->ports.size() == 1);
  VectorInterface<T>* output_port = output->ports[0]->GetMutableVectorData();
  DRAKE_ASSERT(output_port != nullptr);
  DRAKE_ASSERT(output_port->get_value().rows() == length_);
  output_port->get_mutable_value() = VectorX<T>::Zero(length_);

  // Check that there are the expected number of input ports.
  if (context.get_num_input_ports() != num_inputs_) {
    throw std::out_of_range("Expected " + std::to_string(num_inputs_) +
                            "input ports, but had " +
                            std::to_string(context.get_num_input_ports()));
  }

  // Sum each input port into the output, after checking that it has the
  // expected length.
  for (int i = 0; i < context.get_num_input_ports(); i++) {
    const VectorInterface<T>* input = context.get_vector_input(i);
    if (input == nullptr || input->get_value().rows() != length_) {
      throw std::out_of_range("Input port " + std::to_string(i) +
                              "is nullptr or has incorrect size.");
    }
    output_port->get_mutable_value() += input->get_value();
  }
}

template class DRAKESYSTEMFRAMEWORK_EXPORT Adder<double>;

}  // namespace systems
}  // namespace drake
<|endoftext|>


<commit_before>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#include "NetworkTestHelpers.h"

#include "TestInetCommon.h"

#include <support/CodeUtils.h>
#include <support/ErrorStr.h>

namespace chip {
namespace Test {

CHIP_ERROR IOContext::Init(nlTestSuite * suite)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    InitNetwork();

    mSuite       = suite;
    mSystemLayer = &gSystemLayer;
    mInetLayer   = &gInet;

    return err;
}

// Shutdown all layers, finalize operations
CHIP_ERROR IOContext::Shutdown()
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    ShutdownNetwork();

    return err;
}

void IOContext::DriveIO()
{
    // Set the select timeout to 100ms
    struct timeval aSleepTime;
    aSleepTime.tv_sec  = 0;
    aSleepTime.tv_usec = 100 * 1000;

    ServiceEvents(aSleepTime);
}

void IOContext::DriveIOUntil(unsigned maxWaitMs, std::function<bool(void)> completionFunction)
{
    uint64_t mStartTime = mSystemLayer->GetClock_MonotonicMS();

    while (true)
    {
        DriveIO(); // at least one IO loop is guaranteed

        if (completionFunction() || ((mSystemLayer->GetClock_MonotonicMS() - mStartTime) >= maxWaitMs))
        {
            break;
        }
    }
}

} // namespace Test
} // namespace chip
<commit_msg>Initialize system layer in network test helpers. (#1346)<commit_after>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#include "NetworkTestHelpers.h"

#include "TestInetCommon.h"

#include <support/CodeUtils.h>
#include <support/ErrorStr.h>

namespace chip {
namespace Test {

CHIP_ERROR IOContext::Init(nlTestSuite * suite)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    gSystemLayer.Init(NULL);

    InitNetwork();

    mSuite       = suite;
    mSystemLayer = &gSystemLayer;
    mInetLayer   = &gInet;

    return err;
}

// Shutdown all layers, finalize operations
CHIP_ERROR IOContext::Shutdown()
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    ShutdownNetwork();

    return err;
}

void IOContext::DriveIO()
{
    // Set the select timeout to 100ms
    struct timeval aSleepTime;
    aSleepTime.tv_sec  = 0;
    aSleepTime.tv_usec = 100 * 1000;

    ServiceEvents(aSleepTime);
}

void IOContext::DriveIOUntil(unsigned maxWaitMs, std::function<bool(void)> completionFunction)
{
    uint64_t mStartTime = mSystemLayer->GetClock_MonotonicMS();

    while (true)
    {
        DriveIO(); // at least one IO loop is guaranteed

        if (completionFunction() || ((mSystemLayer->GetClock_MonotonicMS() - mStartTime) >= maxWaitMs))
        {
            break;
        }
    }
}

} // namespace Test
} // namespace chip
<|endoftext|>


<commit_before>/**
 * @file Component.hpp
 * @author Denis Kotov
 * @date 10 Jun 2017
 * @brief Contains abstract class for Component.
 * It is thread safe version of Component class
 * Can be used to create different kind of architectures
 * without of warring og thread safety
 * @copyright MIT License. Open source:
 */

#ifndef ICC_COMPONENT_HPP
#define ICC_COMPONENT_HPP

#include <memory>
#include <thread>
#include <algorithm>
#include <boost/asio/io_service.hpp>

class IComponent
  : public std::enable_shared_from_this<IComponent> {
 public:
  /**
   * Default constructor.
   * Only with this constructor object will be owner of service_.
   */
  IComponent()
    : owner_of_service_(true),
      service_(std::make_shared<boost::asio::io_service>()),
      worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Constructor for initializing within event loop created outside.
   * Owner of this pointer is not we
   * @param _eventLoop Event loop that will be used
   */
  IComponent(boost::asio::io_service * _eventLoop)
      : service_(std::shared_ptr<boost::asio::io_service>(_eventLoop,
  [=](boost::asio::io_service *){
    // NOTE(redra): Nothing need to do. Owner of this pointer is not we
  })),
        worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Constructor for initializing within event loop created outside
   * @param _eventLoop Event loop that will be used
   */
  IComponent(std::shared_ptr<boost::asio::io_service> _eventLoop)
    : service_(_eventLoop),
      worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Used to share event loop of parent object
   * @param _parent Parent compenent that will share event loop
   */
  IComponent(IComponent * _parent)
    : service_(_parent->getEventLoop()),
      worker_(new boost::asio::io_service::work(*service_)),
      parent_(_parent) {
    _parent->setChild(this);
  }

  /**
   * Used to share event loop of parent object
   * @param _parent Parent compenent that will share event loop
   */
  IComponent(std::shared_ptr<IComponent> _parent)
      : service_(_parent->getEventLoop()),
        worker_(new boost::asio::io_service::work(*service_)),
        parent_(_parent.get()) {
    _parent->setChild(this);
  }

  /**
   * Disable ability to copy Component class
   */
  IComponent(IComponent const &) = delete;
  IComponent & operator=(IComponent const &) = delete;

  /**
   * Destructor used for removing children or waiting end of event loop
   */
  virtual ~IComponent() {
    if (parent_) {
      parent_->removeChild(this);
    }
  }

 public:
  operator std::shared_ptr<IComponent>() {
    return shared_from_this();
  }

 public:
  /**
   * Used to start event loop
   */
  virtual void exec() {
    if (owner_of_service_) {
      service_->run();
    }
  }

  /**
   * Called to exit from execution in main loop
   */
  virtual void exit() {
    push([=]{
      if (worker_) {
        for (auto & child : childern_) {
          child->exit();
        }
        if (parent_) {
          parent_->exit();
        }
        worker_.reset(nullptr);
      }
    });
  }

  /**
   * Method used to push task for execution
   * @param _task Task that will be executed
   */
  virtual void push(std::function<void(void)> _task) {
    service_->post(_task);
  }

 protected:
  /**
   * Method return used io_service
   * @return IO Service
   */
  virtual std::shared_ptr<boost::asio::io_service>
  getEventLoop() const {
    return service_;
  }

  /**
   * Method that allow to add _child component to the vector
   * @param _child Component that will be added
   */
  virtual void setChild(IComponent * _child) {
    if (_child) {
      push([=]{
        childern_.push_back(_child);
      });
    }
  }

  /**
   * Method that allow to delete _child component from the vector
   * @param _child Component that will be deleted
   */
  virtual void removeChild(IComponent * _child) {
    if (_child) {
      push([=]{
        auto childIter = std::find(childern_.begin(),
                                   childern_.end(),
                                   _child);
        if (childIter != childern_.end()) {
          childern_.erase(childIter);
        }
      });
    }
  }

 protected:
  bool owner_of_service_ = false;
  std::shared_ptr<boost::asio::io_service> service_;
  std::unique_ptr<boost::asio::io_service::work> worker_;

 private:
  IComponent * parent_ = nullptr;
  std::vector<IComponent *> childern_;
};

#endif //ICC_COMPONENT_HPP
<commit_msg>Made IComponent abstract class<commit_after>/**
 * @file Component.hpp
 * @author Denis Kotov
 * @date 10 Jun 2017
 * @brief Contains abstract class for Component.
 * It is thread safe version of Component class
 * Can be used to create different kind of architectures
 * without of warring og thread safety
 * @copyright MIT License. Open source:
 */

#ifndef ICC_COMPONENT_HPP
#define ICC_COMPONENT_HPP

#include <memory>
#include <thread>
#include <algorithm>
#include <boost/asio/io_service.hpp>

class IComponent
  : public std::enable_shared_from_this<IComponent> {
 public:
  /**
   * Default constructor.
   * Only with this constructor object will be owner of service_.
   */
  IComponent()
    : owner_of_service_(true),
      service_(std::make_shared<boost::asio::io_service>()),
      worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Constructor for initializing within event loop created outside.
   * Owner of this pointer is not we
   * @param _eventLoop Event loop that will be used
   */
  IComponent(boost::asio::io_service * _eventLoop)
      : service_(std::shared_ptr<boost::asio::io_service>(_eventLoop,
  [=](boost::asio::io_service *){
    // NOTE(redra): Nothing need to do. Owner of this pointer is not we
  })),
        worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Constructor for initializing within event loop created outside
   * @param _eventLoop Event loop that will be used
   */
  IComponent(std::shared_ptr<boost::asio::io_service> _eventLoop)
    : service_(_eventLoop),
      worker_(new boost::asio::io_service::work(*service_)) {
  }

  /**
   * Used to share event loop of parent object
   * @param _parent Parent compenent that will share event loop
   */
  IComponent(IComponent * _parent)
    : service_(_parent->getEventLoop()),
      worker_(new boost::asio::io_service::work(*service_)),
      parent_(_parent) {
    _parent->setChild(this);
  }

  /**
   * Used to share event loop of parent object
   * @param _parent Parent compenent that will share event loop
   */
  IComponent(std::shared_ptr<IComponent> _parent)
      : service_(_parent->getEventLoop()),
        worker_(new boost::asio::io_service::work(*service_)),
        parent_(_parent.get()) {
    _parent->setChild(this);
  }

  /**
   * Disable ability to copy Component class
   */
  IComponent(IComponent const &) = delete;
  IComponent & operator=(IComponent const &) = delete;

  /**
   * Destructor used for removing children or waiting end of event loop
   */
  virtual ~IComponent() = 0;

 public:
  operator std::shared_ptr<IComponent>() {
    return shared_from_this();
  }

 public:
  /**
   * Used to start event loop
   */
  virtual void exec() {
    if (owner_of_service_) {
      service_->run();
    }
  }

  /**
   * Called to exit from execution in main loop
   */
  virtual void exit() {
    push([=]{
      if (worker_) {
        for (auto & child : childern_) {
          child->exit();
        }
        if (parent_) {
          parent_->exit();
        }
        worker_.reset(nullptr);
      }
    });
  }

  /**
   * Method used to push task for execution
   * @param _task Task that will be executed
   */
  virtual void push(std::function<void(void)> _task) {
    service_->post(_task);
  }

 protected:
  /**
   * Method return used io_service
   * @return IO Service
   */
  virtual std::shared_ptr<boost::asio::io_service>
  getEventLoop() const {
    return service_;
  }

  /**
   * Method that allow to add _child component to the vector
   * @param _child Component that will be added
   */
  virtual void setChild(IComponent * _child) {
    if (_child) {
      push([=]{
        childern_.push_back(_child);
      });
    }
  }

  /**
   * Method that allow to delete _child component from the vector
   * @param _child Component that will be deleted
   */
  virtual void removeChild(IComponent * _child) {
    if (_child) {
      push([=]{
        auto childIter = std::find(childern_.begin(),
                                   childern_.end(),
                                   _child);
        if (childIter != childern_.end()) {
          childern_.erase(childIter);
        }
      });
    }
  }

 protected:
  bool owner_of_service_ = false;
  std::shared_ptr<boost::asio::io_service> service_;
  std::unique_ptr<boost::asio::io_service::work> worker_;

 private:
  IComponent * parent_ = nullptr;
  std::vector<IComponent *> childern_;
};

/**
 * Destructor used for removing children or waiting end of event loop
 */
inline
IComponent::~IComponent() {
  if (parent_) {
    parent_->removeChild(this);
  }
}

#endif //ICC_COMPONENT_HPP
<|endoftext|>


<commit_before><commit_msg>R/W file procedure<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "AI.h"

namespace Karo {
	namespace AI {
		AI::AI()
		{
			BoardState = gcnew Karo::Core::Karo();
		}

		Karo::Common::Move^ AI::ChooseBestMove(Karo::Core::Karo^ board, int depth, Karo::Core::Player player) {

			IEnumerable<Karo::Common::Move^>^ moves = board->GetAvailableMoves(player);

			Karo::Common::Move^ bestMove;
			int bestScore = -9001; // ITS OVER 9000!!!!!!!!!!!11111one1111

			for (int i = 0; i < System::Linq::Enumerable::Count(moves); i++)
			{
				int score = Evaluate(board->WithMoveApplied(System::Linq::Enumerable::ElementAt(moves, i), player), player);

				if (score > bestScore)
				{
					bestMove = System::Linq::Enumerable::ElementAt(moves, i); bestScore = score;
				}
			}

			if (depth == 0)
			{
				return bestMove;
			}

			return ChooseBestMove(board->WithMoveApplied(bestMove, player), --depth, Karo::Core::PlayerHelper::Opposite(player));
		}

		int AI::Evaluate(Karo::Core::Karo^ board, Karo::Core::Player player)
		{
			//array < Core::Piece^>^ _piece = board->Pieces;
			//for each(Core::Piece^ p in _piece) {
			//	if (p->Player == player) {
			//		/*for each(Tuple<int, int>^ tup in neighbours) {

			//		}*/
			//	}
			//}
			return rand->Next(0, 100);
		}

		void AI::DoMove(Karo::Common::Move^ previousMove, int timeLimit, Action<Karo::Common::Move^>^ done)
		{
			// add previous move
			if (previousMove != nullptr) BoardState = BoardState->WithMoveApplied(previousMove, Karo::Core::Player::Player2);
			// if you get a move to apply, it's always from player2
			Karo::Common::Move^ newMove = ChooseBestMove(BoardState, timeLimit, Karo::Core::Player::Player1);

			// apply our move
			BoardState = BoardState->WithMoveApplied(newMove, Karo::Core::Player::Player1);

			array<Karo::Common::Move^>^ moves = gcnew array< Karo::Common::Move^ > {newMove };

			done->Invoke(newMove);
		}
	}
}<commit_msg>Added proper minimax<commit_after>#include "stdafx.h"
#include "AI.h"

namespace Karo {
	namespace AI {
		AI::AI()
		{
			BoardState = gcnew Karo::Core::Karo();
		}

		Karo::Common::Move^ AI::ChooseBestMove(Karo::Core::Karo^ board, int depth, Karo::Core::Player player) {

			IEnumerable<Karo::Common::Move^>^ moves = board->GetAvailableMoves(player);

			// if we're not going any deeper, return best move
			if (depth <= 0)
			{
				Karo::Common::Move^ bestMove;
				int bestScore = -9001; // ITS OVER 9000!!!!!!!!!!!11111one1111

				for (int i = 0; i < System::Linq::Enumerable::Count(moves); i++)
				{
					int score = Evaluate(board->WithMoveApplied(System::Linq::Enumerable::ElementAt(moves, i), player), player);

					if (score > bestScore)
					{
						bestMove = System::Linq::Enumerable::ElementAt(moves, i);
						bestScore = score;
					}
				}

				return bestMove;
			}

			Karo::Common::Move^ bestMove;
			int bestScore = -9001; // ITS OVER 9000!!!!!!!!!!!11111one1111

			for (int i = 0; i < System::Linq::Enumerable::Count(moves); i++)
			{
				Core::Karo ^ innerBoard = board->WithMoveApplied(System::Linq::Enumerable::ElementAt(moves, i), player);

				Common::Move^ bestInnerMove = ChooseBestMove(innerBoard, --depth, Karo::Core::PlayerHelper::Opposite(player));

				int score = Evaluate(innerBoard->WithMoveApplied(bestInnerMove, player), player);

				if (score > bestScore)
				{
					bestMove = bestInnerMove;
					bestScore = score;
				}
			}

			return bestMove;
		}

		int AI::Evaluate(Karo::Core::Karo^ board, Karo::Core::Player player)
		{
			//array < Core::Piece^>^ _piece = board->Pieces;
			//for each(Core::Piece^ p in _piece) {
			//	if (p->Player == player) {
			//		/*for each(Tuple<int, int>^ tup in neighbours) {

			//		}*/
			//	}
			//}
			return rand->Next(0, 100);
		}

		void AI::DoMove(Karo::Common::Move^ previousMove, int timeLimit, Action<Karo::Common::Move^>^ done)
		{
			// add previous move
			if (previousMove != nullptr) BoardState = BoardState->WithMoveApplied(previousMove, Karo::Core::Player::Player2);
			// if you get a move to apply, it's always from player2
			Karo::Common::Move^ newMove = ChooseBestMove(BoardState, timeLimit, Karo::Core::Player::Player1);

			// apply our move
			BoardState = BoardState->WithMoveApplied(newMove, Karo::Core::Player::Player1);

			array<Karo::Common::Move^>^ moves = gcnew array< Karo::Common::Move^ > {newMove };

			done->Invoke(newMove);
		}
	}
}<|endoftext|>


<commit_before>/*
 * Copyright 2012 Bram van der Kroef
 *
 * This file is part of LESS CSS Compiler.
 *
 * LESS CSS Compiler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LESS CSS Compiler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LESS CSS Compiler.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Bram van der Kroef <bram@vanderkroef.net>
 */

#include "LessParser.h"
#include <config.h>

#ifdef WITH_LIBGLOG
#include <glog/logging.h>
#endif

#include <libgen.h>

/**
 * Only allows LessStylesheets
 */
void LessParser::parseStylesheet(LessStylesheet &stylesheet) {
#ifdef WITH_LIBGLOG
  VLOG(1) << "Parser Start";
#endif

  CssParser::parseStylesheet(stylesheet);

#ifdef WITH_LIBGLOG
  VLOG(1) << "Parser End";
#endif
}

bool LessParser::parseStatement(Stylesheet &stylesheet) {
  Selector selector;
  Mixin* mixin;
  LessStylesheet* ls = (LessStylesheet*)&stylesheet;

  if (parseSelector(selector) && !selector.empty()) {
#ifdef WITH_LIBGLOG
    VLOG(2) << "Parse: Selector: " << selector.toString();
#endif

    if (parseRuleset(*ls, selector))
      return true;

    // Parameter mixin in the root. Inserts nested rules but no
    // declarations.
    mixin = ls->createMixin();

    if (mixin->parse(selector)) {
      if (tokenizer->getTokenType() == Token::DELIMITER) {
        tokenizer->readNextToken();
        skipWhitespace();
      }
      return true;
    } else {
      ls->deleteMixin(*mixin);
      throw new ParseException(tokenizer->getToken(),
                               "a declaration block ('{...}') following selector");
    }

  } else {
    return parseAtRuleOrVariable(*ls);
  }
}

bool LessParser::parseAtRuleOrVariable (LessStylesheet &stylesheet) {
  Token token;
  TokenList value, rule;
  AtRule* atrule = NULL;

  if (tokenizer->getTokenType() != Token::ATKEYWORD)
    return false;

  token = tokenizer->getToken();
  tokenizer->readNextToken();
  skipWhitespace();

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parse: keyword: " << token;
#endif

  if (parseVariable(value)) {
#ifdef WITH_LIBGLOG
    VLOG(2) << "Parse: variable";
#endif
    stylesheet.putVariable(token, value);

  } else {
    if (token == "@media") {
      parseLessMediaQuery(token, stylesheet);
      return true;
    }

    while(parseAny(rule)) {};

    if (!parseBlock(rule)) {
      if (tokenizer->getTokenType() != Token::DELIMITER) {
        throw new ParseException(tokenizer->getToken(),
                                 "delimiter (';') at end of @-rule");
      }
      tokenizer->readNextToken();
      skipWhitespace();
    }
    // parse import
    if (token == "@import" && rule.size() > 0) {
      if (rule.front().type == Token::URL ||
          rule.front().type == Token::STRING) {
        if (importFile(rule.front(), stylesheet))
          return true;
      } else
        throw new ParseException(rule, "A string with the file path");
    }

    atrule = stylesheet.createLessAtRule(token);
    atrule->setRule(rule);
  }
  return true;
}

bool LessParser::parseVariable (TokenList &value) {
  if (tokenizer->getTokenType() != Token::COLON)
    return false;

  tokenizer->readNextToken();
  skipWhitespace();

  if (parseValue(value) == false || value.size() == 0) {
    throw new ParseException(tokenizer->getToken(),
                             "value for variable");
  }
  if (tokenizer->getTokenType() != Token::DELIMITER) {
    throw new ParseException(tokenizer->getToken(),
                             "delimiter (';') at end of @-rule");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  return true;
}

bool LessParser::parseSelector(Selector &selector) {
  if (!parseAny(selector))
    return false;

  while (parseAny(selector) || parseSelectorVariable(selector)) {};

  // delete trailing whitespace
  selector.rtrim();
  return true;
}

bool LessParser::parseSelectorVariable(Selector &selector) {
  Token* back;

  if (tokenizer->getTokenType() == Token::BRACKET_OPEN) {
    back = &selector.back();

    if (back->at(back->length() - 1) == '@') {
      back->append(tokenizer->getToken());

      if (tokenizer->readNextToken() != Token::IDENTIFIER)
        throw new ParseException(tokenizer->getToken(),
                                 "Variable inside selector (e.g.: \
@{identifier})");
      back->append(tokenizer->getToken());

      if (tokenizer->readNextToken() != Token::BRACKET_CLOSED)
        throw new ParseException(tokenizer->getToken(),
                                 "Closing bracket after variable.");

      back->append(tokenizer->getToken());
      tokenizer->readNextToken();

      parseWhitespace(selector);

      return true;
    }
  }
  return false;
}

bool LessParser::parseRuleset (LessStylesheet &stylesheet,
                               Selector &selector,
                               LessRuleset* parent) {
  LessRuleset* ruleset;

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN)
    return false;

  tokenizer->readNextToken();
  skipWhitespace();

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parse: Ruleset";
#endif

  // Create the ruleset and parse ruleset statements.
  if (parent == NULL)
    ruleset = stylesheet.createLessRuleset();
  else
    ruleset = parent->createNestedRule();

  ruleset->setSelector(selector);

  parseRulesetStatements(stylesheet, *ruleset);

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of declaration block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  return true;
}

void LessParser::parseRulesetStatements (LessStylesheet &stylesheet,
                                         LessRuleset &ruleset) {
  Token token;
  TokenList value;
  UnprocessedStatement* statement;

  while (true) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      token = tokenizer->getToken();
      tokenizer->readNextToken();
      skipWhitespace();

      if (parseVariable(value)) {
        ruleset.putVariable(token, value);
        value.clear();

      } else if (token == "@media") {
        parseMediaQueryRuleset(token, stylesheet, ruleset);

      } else {
        throw new ParseException(tokenizer->getToken(),
                                 "Variable declaration after keyword.");
      }

    } else if ((statement = parseRulesetStatement(ruleset)) != NULL) {
      // a selector followed by a ruleset is a nested rule
      if (tokenizer->getTokenType() == Token::BRACKET_OPEN) {
        parseRuleset(stylesheet, *statement->getTokens(), &ruleset);
        ruleset.deleteUnprocessedStatement(*statement);
      }

    } else
      break;
  }
}

void LessParser::parseMediaQueryRuleset(Token &mediatoken,
                                        LessStylesheet &stylesheet,
                                        LessRuleset &parent) {

  MediaQueryRuleset* query = parent.createMediaQuery();
  Selector selector;

  selector.push_back(mediatoken);
  selector.push_back(Token::BUILTIN_SPACE);

  skipWhitespace();

  while (parseAny(selector) ||
         tokenizer->getTokenType() == Token::ATKEYWORD) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      selector.push_back(tokenizer->getToken());
      tokenizer->readNextToken();
      parseWhitespace(selector);
    }
  }

  query->setSelector(selector);

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
    throw new ParseException(tokenizer->getToken(),
                             "{");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  parseRulesetStatements(stylesheet, *query);

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of media query block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();
}

UnprocessedStatement* LessParser::parseRulesetStatement (LessRuleset &ruleset) {
  UnprocessedStatement* statement;
  Selector tokens;
  size_t property_i;

  parseProperty(tokens);
  property_i = tokens.size();

  parseWhitespace(tokens);
  parseSelector(tokens);
  tokens.trim();

  if (tokens.empty())
    return NULL;

  statement = ruleset.createUnprocessedStatement();

  statement->getTokens()->swap(tokens);
  statement->property_i = property_i;

  if (tokenizer->getTokenType() == Token::BRACKET_OPEN)
    return statement;

  parseValue(*statement->getTokens());

  if (tokenizer->getTokenType() == Token::DELIMITER) {
    tokenizer->readNextToken();
    skipWhitespace();
  }
  return statement;
}

bool LessParser::importFile(Token uri,
                            LessStylesheet &stylesheet) {
  size_t pathend;
  size_t pos;
  std::string source;
  std::string relative_filename;
  std::list<const char*>::iterator i;
  char* relative_filename_cpy;

  if (uri.type == Token::URL) {
    uri = uri.getUrlString();

  } else if (uri.type == Token::STRING) {
    uri.removeQuotes();
  }

#ifdef WITH_LIBGLOG
  VLOG(2) << "Import filename: " << uri;
#endif

  pathend = uri.rfind('?');
  if (pathend == std::string::npos)
    pathend = uri.size();

  if (pathend > 4 &&
      (uri.substr(pathend - 4, 4) == ".css" ||
       uri.substr(0, 7) == "http://")) {
    return false;
  }

  if (pathend < 5 || uri.substr(pathend - 5, 5) != ".less") {
    uri.insert(pathend, ".less");
    pathend += 5;
  }

  // uri.source is the sourcefile that is currently parsed.
  source = uri.source;
  pos = source.find_last_of("/\\");

  // if the current stylesheet is outside of the current working
  //  directory then add the directory to the filename.
  if (pos != std::string::npos) {
    relative_filename.append(source.substr(0, pos + 1));
    relative_filename.append(uri);
  } else
    relative_filename = uri;

  // check if the file has already been imported.
  for (i = sources.begin(); i != sources.end(); i++) {
    if (relative_filename == (*i))
      return true;
  }

  ifstream in(relative_filename.c_str());
  if (in.fail() || in.bad())
    throw new ParseException(relative_filename, "existing file",
                             uri.line, uri.column, uri.source);

#ifdef WITH_LIBGLOG
  VLOG(1) << "Opening: " << relative_filename;
#endif

  relative_filename_cpy = new char[relative_filename.length() + 1];
  std::strcpy(relative_filename_cpy, relative_filename.c_str());

  sources.push_back(relative_filename_cpy);
  LessTokenizer tokenizer(in, relative_filename.c_str());
  LessParser parser(tokenizer, sources);

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parsing";
#endif

  parser.parseStylesheet(stylesheet);
  in.close();
  return true;
}

void LessParser::parseLessMediaQuery(Token &mediatoken,
                                     LessStylesheet &stylesheet) {
  LessMediaQuery* query = stylesheet.createLessMediaQuery();

  query->getSelector()->push_back(mediatoken);
  query->getSelector()->push_back(Token::BUILTIN_SPACE);

  skipWhitespace();

  while (parseAny(*query->getSelector()) ||
         tokenizer->getTokenType() == Token::ATKEYWORD) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      query->getSelector()->push_back(tokenizer->getToken());
      tokenizer->readNextToken();
      parseWhitespace(*query->getSelector());
    }
  }

#ifdef WITH_LIBGLOG
  VLOG(2) << "Media query: " << query->getSelector()->toString();
#endif

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
    throw new ParseException(tokenizer->getToken(),
                             "{");
  }
  tokenizer->readNextToken();

  skipWhitespace();
  while (parseStatement(*query)) {
    skipWhitespace();
  }

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of media query block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();
}
<commit_msg>Fixed importing so Token.source is a pointer to a string in the sources list.<commit_after>/*
 * Copyright 2012 Bram van der Kroef
 *
 * This file is part of LESS CSS Compiler.
 *
 * LESS CSS Compiler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LESS CSS Compiler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LESS CSS Compiler.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Bram van der Kroef <bram@vanderkroef.net>
 */

#include "LessParser.h"
#include <config.h>

#ifdef WITH_LIBGLOG
#include <glog/logging.h>
#endif

#include <libgen.h>

/**
 * Only allows LessStylesheets
 */
void LessParser::parseStylesheet(LessStylesheet &stylesheet) {
#ifdef WITH_LIBGLOG
  VLOG(1) << "Parser Start";
#endif

  CssParser::parseStylesheet(stylesheet);

#ifdef WITH_LIBGLOG
  VLOG(1) << "Parser End";
#endif
}

bool LessParser::parseStatement(Stylesheet &stylesheet) {
  Selector selector;
  Mixin* mixin;
  LessStylesheet* ls = (LessStylesheet*)&stylesheet;

  if (parseSelector(selector) && !selector.empty()) {
#ifdef WITH_LIBGLOG
    VLOG(2) << "Parse: Selector: " << selector.toString();
#endif

    if (parseRuleset(*ls, selector))
      return true;

    // Parameter mixin in the root. Inserts nested rules but no
    // declarations.
    mixin = ls->createMixin();

    if (mixin->parse(selector)) {
      if (tokenizer->getTokenType() == Token::DELIMITER) {
        tokenizer->readNextToken();
        skipWhitespace();
      }
      return true;
    } else {
      ls->deleteMixin(*mixin);
      throw new ParseException(tokenizer->getToken(),
                               "a declaration block ('{...}') following selector");
    }

  } else {
    return parseAtRuleOrVariable(*ls);
  }
}

bool LessParser::parseAtRuleOrVariable (LessStylesheet &stylesheet) {
  Token token;
  TokenList value, rule;
  AtRule* atrule = NULL;

  if (tokenizer->getTokenType() != Token::ATKEYWORD)
    return false;

  token = tokenizer->getToken();
  tokenizer->readNextToken();
  skipWhitespace();

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parse: keyword: " << token;
#endif

  if (parseVariable(value)) {
#ifdef WITH_LIBGLOG
    VLOG(2) << "Parse: variable";
#endif
    stylesheet.putVariable(token, value);

  } else {
    if (token == "@media") {
      parseLessMediaQuery(token, stylesheet);
      return true;
    }

    while(parseAny(rule)) {};

    if (!parseBlock(rule)) {
      if (tokenizer->getTokenType() != Token::DELIMITER) {
        throw new ParseException(tokenizer->getToken(),
                                 "delimiter (';') at end of @-rule");
      }
      tokenizer->readNextToken();
      skipWhitespace();
    }
    // parse import
    if (token == "@import" && rule.size() > 0) {
      if (rule.front().type == Token::URL ||
          rule.front().type == Token::STRING) {
        if (importFile(rule.front(), stylesheet))
          return true;
      } else
        throw new ParseException(rule, "A string with the file path");
    }

    atrule = stylesheet.createLessAtRule(token);
    atrule->setRule(rule);
  }
  return true;
}

bool LessParser::parseVariable (TokenList &value) {
  if (tokenizer->getTokenType() != Token::COLON)
    return false;

  tokenizer->readNextToken();
  skipWhitespace();

  if (parseValue(value) == false || value.size() == 0) {
    throw new ParseException(tokenizer->getToken(),
                             "value for variable");
  }
  if (tokenizer->getTokenType() != Token::DELIMITER) {
    throw new ParseException(tokenizer->getToken(),
                             "delimiter (';') at end of @-rule");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  return true;
}

bool LessParser::parseSelector(Selector &selector) {
  if (!parseAny(selector))
    return false;

  while (parseAny(selector) || parseSelectorVariable(selector)) {};

  // delete trailing whitespace
  selector.rtrim();
  return true;
}

bool LessParser::parseSelectorVariable(Selector &selector) {
  Token* back;

  if (tokenizer->getTokenType() == Token::BRACKET_OPEN) {
    back = &selector.back();

    if (back->at(back->length() - 1) == '@') {
      back->append(tokenizer->getToken());

      if (tokenizer->readNextToken() != Token::IDENTIFIER)
        throw new ParseException(tokenizer->getToken(),
                                 "Variable inside selector (e.g.: \
@{identifier})");
      back->append(tokenizer->getToken());

      if (tokenizer->readNextToken() != Token::BRACKET_CLOSED)
        throw new ParseException(tokenizer->getToken(),
                                 "Closing bracket after variable.");

      back->append(tokenizer->getToken());
      tokenizer->readNextToken();

      parseWhitespace(selector);

      return true;
    }
  }
  return false;
}

bool LessParser::parseRuleset (LessStylesheet &stylesheet,
                               Selector &selector,
                               LessRuleset* parent) {
  LessRuleset* ruleset;

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN)
    return false;

  tokenizer->readNextToken();
  skipWhitespace();

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parse: Ruleset";
#endif

  // Create the ruleset and parse ruleset statements.
  if (parent == NULL)
    ruleset = stylesheet.createLessRuleset();
  else
    ruleset = parent->createNestedRule();

  ruleset->setSelector(selector);

  parseRulesetStatements(stylesheet, *ruleset);

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of declaration block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  return true;
}

void LessParser::parseRulesetStatements (LessStylesheet &stylesheet,
                                         LessRuleset &ruleset) {
  Token token;
  TokenList value;
  UnprocessedStatement* statement;

  while (true) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      token = tokenizer->getToken();
      tokenizer->readNextToken();
      skipWhitespace();

      if (parseVariable(value)) {
        ruleset.putVariable(token, value);
        value.clear();

      } else if (token == "@media") {
        parseMediaQueryRuleset(token, stylesheet, ruleset);

      } else {
        throw new ParseException(tokenizer->getToken(),
                                 "Variable declaration after keyword.");
      }

    } else if ((statement = parseRulesetStatement(ruleset)) != NULL) {
      // a selector followed by a ruleset is a nested rule
      if (tokenizer->getTokenType() == Token::BRACKET_OPEN) {
        parseRuleset(stylesheet, *statement->getTokens(), &ruleset);
        ruleset.deleteUnprocessedStatement(*statement);
      }

    } else
      break;
  }
}

void LessParser::parseMediaQueryRuleset(Token &mediatoken,
                                        LessStylesheet &stylesheet,
                                        LessRuleset &parent) {

  MediaQueryRuleset* query = parent.createMediaQuery();
  Selector selector;

  selector.push_back(mediatoken);
  selector.push_back(Token::BUILTIN_SPACE);

  skipWhitespace();

  while (parseAny(selector) ||
         tokenizer->getTokenType() == Token::ATKEYWORD) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      selector.push_back(tokenizer->getToken());
      tokenizer->readNextToken();
      parseWhitespace(selector);
    }
  }

  query->setSelector(selector);

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
    throw new ParseException(tokenizer->getToken(),
                             "{");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  parseRulesetStatements(stylesheet, *query);

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of media query block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();
}

UnprocessedStatement* LessParser::parseRulesetStatement (LessRuleset &ruleset) {
  UnprocessedStatement* statement;
  Selector tokens;
  size_t property_i;

  parseProperty(tokens);
  property_i = tokens.size();

  parseWhitespace(tokens);
  parseSelector(tokens);
  tokens.trim();

  if (tokens.empty())
    return NULL;

  statement = ruleset.createUnprocessedStatement();

  statement->getTokens()->swap(tokens);
  statement->property_i = property_i;

  if (tokenizer->getTokenType() == Token::BRACKET_OPEN)
    return statement;

  parseValue(*statement->getTokens());

  if (tokenizer->getTokenType() == Token::DELIMITER) {
    tokenizer->readNextToken();
    skipWhitespace();
  }
  return statement;
}

bool LessParser::importFile(Token uri,
                            LessStylesheet &stylesheet) {
  size_t pathend;
  size_t pos;
  std::string source;
  std::string relative_filename;
  std::list<const char*>::iterator i;
  char* relative_filename_cpy;

  if (uri.type == Token::URL) {
    uri = uri.getUrlString();

  } else if (uri.type == Token::STRING) {
    uri.removeQuotes();
  }

#ifdef WITH_LIBGLOG
  VLOG(2) << "Import filename: " << uri;
#endif

  pathend = uri.rfind('?');
  if (pathend == std::string::npos)
    pathend = uri.size();

  if (pathend > 4 &&
      (uri.substr(pathend - 4, 4) == ".css" ||
       uri.substr(0, 7) == "http://")) {
    return false;
  }

  if (pathend < 5 || uri.substr(pathend - 5, 5) != ".less") {
    uri.insert(pathend, ".less");
    pathend += 5;
  }

  // uri.source is the sourcefile that is currently parsed.
  source = uri.source;
  pos = source.find_last_of("/\\");

  // if the current stylesheet is outside of the current working
  //  directory then add the directory to the filename.
  if (pos != std::string::npos) {
    relative_filename.append(source.substr(0, pos + 1));
    relative_filename.append(uri);
  } else
    relative_filename = uri;

  // check if the file has already been imported.
  for (i = sources.begin(); i != sources.end(); i++) {
    if (relative_filename == (*i))
      return true;
  }

  ifstream in(relative_filename.c_str());
  if (in.fail() || in.bad())
    throw new ParseException(relative_filename, "existing file",
                             uri.line, uri.column, uri.source);

#ifdef WITH_LIBGLOG
  VLOG(1) << "Opening: " << relative_filename;
#endif

  relative_filename_cpy = new char[relative_filename.length() + 1];
  std::strcpy(relative_filename_cpy, relative_filename.c_str());

  sources.push_back(relative_filename_cpy);
  LessTokenizer tokenizer(in, relative_filename_cpy);
  LessParser parser(tokenizer, sources);

#ifdef WITH_LIBGLOG
  VLOG(2) << "Parsing";
#endif

  parser.parseStylesheet(stylesheet);
  in.close();
  return true;
}

void LessParser::parseLessMediaQuery(Token &mediatoken,
                                     LessStylesheet &stylesheet) {
  LessMediaQuery* query = stylesheet.createLessMediaQuery();

  query->getSelector()->push_back(mediatoken);
  query->getSelector()->push_back(Token::BUILTIN_SPACE);

  skipWhitespace();

  while (parseAny(*query->getSelector()) ||
         tokenizer->getTokenType() == Token::ATKEYWORD) {
    if (tokenizer->getTokenType() == Token::ATKEYWORD) {
      query->getSelector()->push_back(tokenizer->getToken());
      tokenizer->readNextToken();
      parseWhitespace(*query->getSelector());
    }
  }

#ifdef WITH_LIBGLOG
  VLOG(2) << "Media query: " << query->getSelector()->toString();
#endif

  if (tokenizer->getTokenType() != Token::BRACKET_OPEN) {
    throw new ParseException(tokenizer->getToken(),
                             "{");
  }
  tokenizer->readNextToken();

  skipWhitespace();
  while (parseStatement(*query)) {
    skipWhitespace();
  }

  if (tokenizer->getTokenType() != Token::BRACKET_CLOSED) {
    throw new ParseException(tokenizer->getToken(),
                             "end of media query block ('}')");
  }
  tokenizer->readNextToken();
  skipWhitespace();
}
<|endoftext|>


<commit_before>/**
 /**
 * Contact: philipp.rescheneder@gmail.com
 */

#include "MappedRead.h"

#include <stdlib.h>

#undef module_name
#define module_name "READ"

//volatile int MappedRead::sInstanceCount = 0;
//
//#ifdef INSTANCE_COUNTING
//volatile int MappedRead::sInstanceCount = 0;
//volatile int LocationScore::sInstanceCount = 0;
//#endif

//volatile int Align::sInstanceCount = 0;

MappedRead::MappedRead(int const readid, int const qrymaxlen) :
		ReadId(readid), Calculated(-1), qryMaxLen(qrymaxlen), Scores(0), Alignments(0), iScores(0), Status(0), mappingQlty(255), s(0), length(0), RevSeq(0), Seq(0), qlty(0), name(0), AdditionalInfo(0), group(0) {
//#ifdef INSTANCE_COUNTING
//	AtomicInc(&sInstanceCount);
//	maxSeqCount = std::max(sInstanceCount, maxSeqCount);
//#endif

//Name
	static size_t const MAX_READNAME_LENGTH = 250;
	name = new char[MAX_READNAME_LENGTH];

}

static inline char cpl(char c) {
	if (c == 'A')
		return 'T';
	else if (c == 'T')
		return 'A';
	else if (c == 'C')
		return 'G';
	else if (c == 'G')
		return 'C';
	else
		return c;
}

//// swaps two bases and complements them
//static inline void rc(char & c1, char & c2)
//{
//	char x = c1;
//	c1 = cpl(c2);
//	c2 = cpl(x);
//}

char const * MappedRead::computeReverseSeq() {
	if (RevSeq == 0) {
//		RevSeq = new char[length + 1];
//		memset(RevSeq, 0, length + 1);
		int revLength = std::max(qryMaxLen, length + 16);
		RevSeq = new char[revLength];
		memset(RevSeq, 0, revLength);

		char * fwd = Seq;
		char * rev = RevSeq + length - 1;

		for (int i = 0; i < length; ++i) {
			*rev-- = cpl(*fwd++);
			//Seq[i] = cpl(RevSeq[length - i - 1]);
		}
	}
	return RevSeq;
}

void MappedRead::DeleteReadSeq() {
	if (Seq != 0)
		delete[] Seq;
	Seq = 0;
	if (RevSeq != 0)
		delete[] RevSeq;
	RevSeq = 0;
}

MappedRead::~MappedRead() {

	if (Scores != 0) {
		delete[] Scores;
		Scores = 0;
		iScores = 0;
	}
	if (Alignments != 0) {
		for (int i = 0; i < Calculated; ++i) {
			if (Alignments[i].pBuffer1 != 0) {
				delete[] Alignments[i].pBuffer1;
				Alignments[i].pBuffer1 = 0;
			}
			if (Alignments[i].pBuffer2 != 0) {
				delete[] Alignments[i].pBuffer2;
				Alignments[i].pBuffer2 = 0;
			}
			if (Alignments[i].nmPerPosition != 0) {
				delete[] Alignments[i].nmPerPosition;
				Alignments[i].nmPerPosition = 0;
			}
		}
		delete[] Alignments;
		Alignments = 0;
	}
	DeleteReadSeq();
	if (qlty != 0) {
		delete[] qlty;
		qlty = 0;
	}
	if (name != 0) {
		delete[] name;
		name = 0;
	}

//#ifdef INSTANCE_COUNTING
//	AtomicDec(&sInstanceCount);
//#endif
}

void MappedRead::AllocScores(LocationScore * tmp, int const n) {
	iScores = n;
	if (iScores > 0) {
		Scores = new LocationScore[iScores];
		memcpy(Scores, tmp, n * sizeof(LocationScore));
	}
}

//void MappedRead::reallocScores(int const n) {
//	if (Scores != 0) {
//		Scores = (LocationScore *) realloc(Scores, n * sizeof(LocationScore));
//	}
//}

void MappedRead::clearScores(int const TopScore) {
	if (Scores != 0) {
		if (TopScore != -1) {
			LocationScore tmp = Scores[TopScore];
			delete[] Scores;
			Scores = new LocationScore[1];
			//Scores = (LocationScore *)realloc(Scores, 1 * sizeof(LocationScore));
			Scores[0] = tmp;
			iScores = 1;
		} else {
			delete[] Scores;
			iScores = 0;
			Scores = 0;
		}
	}

}

int MappedRead::numScores() const {
	return iScores;
}

bool MappedRead::hasCandidates() const {
	return iScores > 0;
}
<commit_msg>Warning fixed<commit_after>/**
 *
 * Contact: philipp.rescheneder@gmail.com
 */

#include "MappedRead.h"

#include <stdlib.h>

#undef module_name
#define module_name "READ"

//volatile int MappedRead::sInstanceCount = 0;
//
//#ifdef INSTANCE_COUNTING
//volatile int MappedRead::sInstanceCount = 0;
//volatile int LocationScore::sInstanceCount = 0;
//#endif

//volatile int Align::sInstanceCount = 0;

MappedRead::MappedRead(int const readid, int const qrymaxlen) :
		ReadId(readid), Calculated(-1), qryMaxLen(qrymaxlen), Scores(0), Alignments(0), iScores(0), Status(0), mappingQlty(255), s(0), length(0), RevSeq(0), Seq(0), qlty(0), name(0), AdditionalInfo(0), group(0) {
//#ifdef INSTANCE_COUNTING
//	AtomicInc(&sInstanceCount);
//	maxSeqCount = std::max(sInstanceCount, maxSeqCount);
//#endif

//Name
	static size_t const MAX_READNAME_LENGTH = 250;
	name = new char[MAX_READNAME_LENGTH];

}

static inline char cpl(char c) {
	if (c == 'A')
		return 'T';
	else if (c == 'T')
		return 'A';
	else if (c == 'C')
		return 'G';
	else if (c == 'G')
		return 'C';
	else
		return c;
}

//// swaps two bases and complements them
//static inline void rc(char & c1, char & c2)
//{
//	char x = c1;
//	c1 = cpl(c2);
//	c2 = cpl(x);
//}

char const * MappedRead::computeReverseSeq() {
	if (RevSeq == 0) {
//		RevSeq = new char[length + 1];
//		memset(RevSeq, 0, length + 1);
		int revLength = std::max(qryMaxLen, length + 16);
		RevSeq = new char[revLength];
		memset(RevSeq, 0, revLength);

		char * fwd = Seq;
		char * rev = RevSeq + length - 1;

		for (int i = 0; i < length; ++i) {
			*rev-- = cpl(*fwd++);
			//Seq[i] = cpl(RevSeq[length - i - 1]);
		}
	}
	return RevSeq;
}

void MappedRead::DeleteReadSeq() {
	if (Seq != 0)
		delete[] Seq;
	Seq = 0;
	if (RevSeq != 0)
		delete[] RevSeq;
	RevSeq = 0;
}

MappedRead::~MappedRead() {

	if (Scores != 0) {
		delete[] Scores;
		Scores = 0;
		iScores = 0;
	}
	if (Alignments != 0) {
		for (int i = 0; i < Calculated; ++i) {
			if (Alignments[i].pBuffer1 != 0) {
				delete[] Alignments[i].pBuffer1;
				Alignments[i].pBuffer1 = 0;
			}
			if (Alignments[i].pBuffer2 != 0) {
				delete[] Alignments[i].pBuffer2;
				Alignments[i].pBuffer2 = 0;
			}
			if (Alignments[i].nmPerPosition != 0) {
				delete[] Alignments[i].nmPerPosition;
				Alignments[i].nmPerPosition = 0;
			}
		}
		delete[] Alignments;
		Alignments = 0;
	}
	DeleteReadSeq();
	if (qlty != 0) {
		delete[] qlty;
		qlty = 0;
	}
	if (name != 0) {
		delete[] name;
		name = 0;
	}

//#ifdef INSTANCE_COUNTING
//	AtomicDec(&sInstanceCount);
//#endif
}

void MappedRead::AllocScores(LocationScore * tmp, int const n) {
	iScores = n;
	if (iScores > 0) {
		Scores = new LocationScore[iScores];
		memcpy(Scores, tmp, n * sizeof(LocationScore));
	}
}

//void MappedRead::reallocScores(int const n) {
//	if (Scores != 0) {
//		Scores = (LocationScore *) realloc(Scores, n * sizeof(LocationScore));
//	}
//}

void MappedRead::clearScores(int const TopScore) {
	if (Scores != 0) {
		if (TopScore != -1) {
			LocationScore tmp = Scores[TopScore];
			delete[] Scores;
			Scores = new LocationScore[1];
			//Scores = (LocationScore *)realloc(Scores, 1 * sizeof(LocationScore));
			Scores[0] = tmp;
			iScores = 1;
		} else {
			delete[] Scores;
			iScores = 0;
			Scores = 0;
		}
	}

}

int MappedRead::numScores() const {
	return iScores;
}

bool MappedRead::hasCandidates() const {
	return iScores > 0;
}
<|endoftext|>