text:
#include "FileBuffer.h"
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

/*
 * Page Structure
 *		Initial Page	: [uint64 NextInitialPage][uint64 FreePageItems]{[uint64 FreePage] ...}
 *		Use Mask Page	: [uint64 NextUseMaskPage]{[bit FreePageMask] ...}
 *			FreePageMask 1=used, 0=free
 */

#define INDEX_INVALID (~(vuint64_t)0)
#define INDEX_PAGE_USEMASK 0
#define INDEX_PAGE_FREEITEM 1
#define INDEX_PAGE_INDEX 2

#define INDEX_USEMASK_NEXTUSEMASKPAGE 0
#define INDEX_USEMASK_USEMASKBEGIN 1

#define INDEX_FREEITEM_NEXTINITIALPAGE 0
#define INDEX_FREEITEM_FREEPAGEITEMS 1
#define INDEX_FREEITEM_FREEPAGEITEMBEGIN 2

namespace vl
{
	namespace database
	{
		using namespace collections;
		using namespace buffer_internal;

		namespace buffer_internal
		{

/***********************************************************************
FileMapping
***********************************************************************/

			FileMapping::FileMapping(vuint64_t _pageSize, int _fileDescriptor, volatile vuint64_t* _totalUsedPages)
				:pageSize(_pageSize)
				,fileDescriptor(_fileDescriptor)
				,totalUsedPages(_totalUsedPages)
			{
			}

			void FileMapping::InitializeEmptySource()
			{
				totalPageCount = 3;
			}

			void FileMapping::InitializeExistingSource()
			{
				struct stat fileState;
				CHECK_ERROR(fstat(fileDescriptor, &fileState) != -1, L"vl::database::buffer_internal::FileMapping::InitializeExistingSource()#Internal error: Failed to call fstat.");
				totalPageCount = fileState.st_size / pageSize;
			}

			vuint64_t FileMapping::GetTotalPageCount()
			{
				return totalPageCount;
			}

			Ptr<BufferPageDesc> FileMapping::MapPage(BufferPage page)
			{
				vint index = mappedPages.Keys().IndexOf(page.index);
				if (index == -1)
				{
					vuint64_t offset = page.index * pageSize;
					struct stat fileState;
					CHECK_ERROR(fstat(fileDescriptor, &fileState) != -1, L"vl::database::buffer_internal::FileMapping::InitializeExistingSource()#Internal error: Failed to call fstat.");
					if (fileState.st_size < offset + pageSize)
					{
						CHECK_ERROR(fileState.st_size == offset, L"vl::database::buffer_internal::FileMapping::InitializeExistingSource()#Internal error: The file is corrupted.");
						ftruncate(fileDescriptor, offset + pageSize);
						totalPageCount = offset / pageSize + 1;
					}

					void* address = mmap(nullptr, pageSize, PROT_READ | PROT_WRITE, MAP_SHARED, fileDescriptor, offset);
					if (address == MAP_FAILED)
					{
						return nullptr;
					}

					auto pageDesc = MakePtr<BufferPageDesc>();
					pageDesc->address = address;
					pageDesc->offset = offset;
					pageDesc->lastAccessTime = (vuint64_t)time(nullptr);
					mappedPages.Add(page.index, pageDesc);
					INCRC(totalUsedPages);
					return pageDesc;
				}
				else
				{
					auto pageDesc = mappedPages.Values()[index];
					pageDesc->lastAccessTime = (vuint64_t)time(nullptr);
					return pageDesc;
				}
			}

			BufferPage FileMapping::AppendPage()
			{
				BufferPage result;
				BufferPage page{totalPageCount};
				if (MapPage(page))
				{
					result = page;
				}
				return result;
			}

			bool FileMapping::UnmapPage(BufferPage page)
			{
				vint index = mappedPages.Keys().IndexOf(page.index);
				if (index != -1)
				{
					auto pageDesc = mappedPages.Values()[index];
					if (!pageDesc->locked)
					{
						if (pageDesc->dirty)
						{
							CHECK_ERROR(msync(pageDesc->address, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileMapping::UnmapPage(BufferPage)#Internal error: Failed to call msync.");
							pageDesc->dirty = false;
						}
						CHECK_ERROR(munmap(pageDesc->address, pageSize) != -1, L"vl::database::buffer_internal::FileMapping::UnmapPage(BufferPage)#Internal error: Failed to call munmap.");

						mappedPages.Remove(page.index);
						DECRC(totalUsedPages);
						return true;
					}
				}
				return false;
			}

			void FileMapping::UnmapAllPages()
			{
				FOREACH(Ptr<BufferPageDesc>, pageDesc, mappedPages.Values())
				{
					DECRC(totalUsedPages);
					CHECK_ERROR(munmap(pageDesc->address, pageSize) != -1, L"vl::database::buffer_internal::FileMapping::UnmapAllPages(BufferPage)#Internal error: Failed to call munmap.");
				}
			}

			vint FileMapping::GetMappedPageCount()
			{
				return mappedPages.Count();
			}

			BufferPage FileMapping::GetMappedPage(vint index)
			{
				return mappedPages.Keys()[index];
			}

			Ptr<BufferPageDesc> FileMapping::GetMappedPageDesc(vint index)
			{
				return mappedPages.Values()[index];
			}

			Ptr<BufferPageDesc> FileMapping::GetMappedPageDesc(BufferPage page)
			{
				vint index = mappedPages.Keys().IndexOf(page.index);
				if (index == -1)
				{
					return nullptr;
				}
				return mappedPages.Values()[index];
			}

/***********************************************************************
FileUseMasks
***********************************************************************/

			FileUseMasks::FileUseMasks(vuint64_t _pageSize, int _fileDescriptor)
				:pageSize(_pageSize)
				,fileDescriptor(_fileDescriptor)
				,useMaskPageItemCount((_pageSize - INDEX_USEMASK_USEMASKBEGIN * sizeof(vuint64_t)) / sizeof(vuint64_t))
			{
			}

			void FileUseMasks::InitializeEmptySource(FileMapping* _fileMapping)
			{
				fileMapping = _fileMapping;

				useMaskPages.Clear();
				BufferPage page{INDEX_PAGE_USEMASK};
				auto pageDesc = fileMapping->MapPage(page);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileUseMasks::InitializeEmptySource()#Internal error: Failed to map INDEX_PAGE_USEMASK.");
				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				memset(numbers, 0, pageSize);
				numbers[INDEX_USEMASK_NEXTUSEMASKPAGE] = INDEX_INVALID;
				CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileUseMasks::InitializeEmptySource()#Internal error: Failed to call msync.");
				useMaskPages.Add(page.index);
			}

			void FileUseMasks::InitializeExistingSource(FileMapping* _fileMapping)
			{
				fileMapping = _fileMapping;

				useMaskPages.Clear();
				BufferPage page{INDEX_PAGE_USEMASK};

				while(page.index != INDEX_INVALID)
				{
					useMaskPages.Add(page.index);
					auto pageDesc = fileMapping->MapPage(page);
					vuint64_t* numbers = (vuint64_t*)pageDesc->address;
					page.index = numbers[INDEX_USEMASK_NEXTUSEMASKPAGE];
				}
			}

			bool FileUseMasks::GetUseMask(BufferPage page)
			{
				auto useMaskPageBits = 8 * sizeof(vuint64_t);
				auto useMaskPageIndex = page.index / (useMaskPageBits * useMaskPageItemCount);
				auto useMaskPageBitIndex = page.index % (useMaskPageBits * useMaskPageItemCount);
				auto useMaskPageItem = INDEX_USEMASK_USEMASKBEGIN + useMaskPageBitIndex / useMaskPageBits;
				auto useMaskPageShift = useMaskPageBitIndex % useMaskPageBits;

				BufferPage useMaskPage{useMaskPages[useMaskPageIndex]};
				auto pageDesc = fileMapping->MapPage(useMaskPage);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileUseMasks::GetUseMask(BufferPage)#Internal error: Failed to map the specified use mask page.");
				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				auto& item = numbers[useMaskPageItem];
				bool result = ((item >> useMaskPageShift) & ((vuint64_t)1)) == 1;
				CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileUseMasks::GetUseMask(page)#Internal error: Failed to call msync.");
				return result;
			}

			void FileUseMasks::SetUseMask(BufferPage page, bool available)
			{
				auto useMaskPageBits = 8 * sizeof(vuint64_t);
				auto useMaskPageIndex = page.index / (useMaskPageBits * useMaskPageItemCount);
				auto useMaskPageBitIndex = page.index % (useMaskPageBits * useMaskPageItemCount);
				auto useMaskPageItem = INDEX_USEMASK_USEMASKBEGIN + useMaskPageBitIndex / useMaskPageBits;
				auto useMaskPageShift = useMaskPageBitIndex % useMaskPageBits;
				bool newPage = false;

				BufferPage useMaskPage = BufferPage::Invalid();

				if (useMaskPageIndex == useMaskPages.Count())
				{
					newPage = true;
					BufferPage lastPage{useMaskPages[useMaskPageIndex - 1]};
					useMaskPage = fileMapping->AppendPage();
					CHECK_ERROR(useMaskPage.IsValid(), L"vl::database::buffer_internal::FileUseMasks::SetUseMask(BufferPage, bool)#Internal error: Failed to create a new use mask page.");
					SetUseMask(useMaskPage, true);
					useMaskPages.Add(useMaskPage.index);

					auto pageDesc = fileMapping->MapPage(lastPage);
					CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileUseMasks::SetUseMask(BufferPage, bool)#Internal error: Failed to map the last use mask page.");
					vuint64_t* numbers = (vuint64_t*)pageDesc->address;
					numbers[INDEX_USEMASK_NEXTUSEMASKPAGE] = useMaskPage.index;
					CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileUseMasks::SetUseMask(page, bool)#Internal error: Failed to call msync.");
				}
				else
				{
					useMaskPage.index = useMaskPages[useMaskPageIndex];
				}

				auto pageDesc = fileMapping->MapPage(useMaskPage);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileUseMasks::SetUseMask(BufferPage, bool)#Internal error: Failed to map the specified use mask page.");
				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				if (newPage)
				{
					memset(numbers, 0, pageSize);
					numbers[INDEX_USEMASK_NEXTUSEMASKPAGE] = INDEX_INVALID;
				}

				auto& item = numbers[useMaskPageItem];
				if (available)
				{
					vuint64_t mask = ((vuint64_t)1) << useMaskPageShift;
					item |= mask;
				}
				else
				{
					vuint64_t mask = ~(((vuint64_t)1) << useMaskPageShift);
					item &= mask;
				}
				CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileUseMasks::SetUseMask(page, bool)#Internal error: Failed to call msync.");
			}
		}

/***********************************************************************
FileFreePages
***********************************************************************/

			FileFreePages::FileFreePages(vuint64_t _pageSize)
				:pageSize(_pageSize)
				,freeItemPageItemCount((_pageSize - INDEX_FREEITEM_FREEPAGEITEMBEGIN * sizeof(vuint64_t)) / sizeof(vuint64_t))
				,activeFreeItemPageIndex(-1)
			{
			}

			void FileFreePages::InitializeEmptySource(FileMapping* _fileMapping, FileUseMasks* _fileUseMasks)
			{
				fileMapping = _fileMapping;
				fileUseMasks = _fileUseMasks;

				freeItemPages.Clear();
				BufferPage page{INDEX_PAGE_FREEITEM};
				auto pageDesc = fileMapping->MapPage(page);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileFreePages::InitializeEmptySource()#Internal error: Failed to map INDEX_PAGE_FREEITEM.");

				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				memset(numbers, 0, pageSize);
				numbers[INDEX_FREEITEM_NEXTINITIALPAGE] = INDEX_INVALID;
				numbers[INDEX_FREEITEM_FREEPAGEITEMS] = 0;
				CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileFreePages::InitializeEmptySource()#Internal error: Failed to call msync.");

				freeItemPages.Add(page.index);
				activeFreeItemPageIndex = 0;
			}

			void FileFreePages::InitializeExistingSource(FileMapping* _fileMapping, FileUseMasks* _fileUseMasks)
			{
				fileMapping = _fileMapping;
				fileUseMasks = _fileUseMasks;

				freeItemPages.Clear();
				BufferPage page{INDEX_PAGE_FREEITEM};

				while(page.index != INDEX_INVALID)
				{
					freeItemPages.Add(page.index);
					auto pageDesc = fileMapping->MapPage(page);
					vuint64_t* numbers = (vuint64_t*)pageDesc->address;
					page.index = numbers[INDEX_FREEITEM_NEXTINITIALPAGE];

					if (numbers[INDEX_FREEITEM_FREEPAGEITEMS] != 0)
					{
						activeFreeItemPageIndex = freeItemPages.Count() - 1;
					}
				}

				if (activeFreeItemPageIndex == -1)
				{
					activeFreeItemPageIndex = 0;
				}
			}

			void FileFreePages::PushFreePage(BufferPage page)
			{
				BufferPage initialPage{freeItemPages[activeFreeItemPageIndex]};
				auto pageDesc = fileMapping->MapPage(initialPage);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileFreePages::PushFreePage(BufferPage)#Internal error: Failed to map the last active initial page.");
				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				vuint64_t& count = numbers[INDEX_FREEITEM_FREEPAGEITEMS];
				if (count == freeItemPageItemCount)
				{
					if (activeFreeItemPageIndex == freeItemPages.Count() - 1)
					{
						BufferPage newInitialPage{fileMapping->GetTotalPageCount()};
						numbers[INDEX_FREEITEM_NEXTINITIALPAGE] = newInitialPage.index;
						msync(numbers, pageSize, MS_SYNC);

						auto newPageDesc = fileMapping->MapPage(newInitialPage);
						CHECK_ERROR(newPageDesc != nullptr, L"vl::database::buffer_internal::FileFreePages::PushFreePage(BufferPage)#Internal error: Failed to create a new initial page.");
						numbers = (vuint64_t*)newPageDesc->address;
						memset(numbers, 0, pageSize);
						numbers[INDEX_FREEITEM_NEXTINITIALPAGE] = INDEX_INVALID;
						numbers[INDEX_FREEITEM_FREEPAGEITEMS] = 1;
						numbers[INDEX_FREEITEM_FREEPAGEITEMBEGIN] = page.index;
						CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileFreePages::PushFreePage(page)#Internal error: Failed to call msync.");
						freeItemPages.Add(newInitialPage.index);
						fileUseMasks->SetUseMask(newInitialPage, true);
					}
					else
					{
						BufferPage newInitialPage{freeItemPages[activeFreeItemPageIndex + 1]};
						auto newPageDesc = fileMapping->MapPage(newInitialPage);
						CHECK_ERROR(newPageDesc != nullptr, L"vl::database::buffer_internal::FileFreePages::PushFreePage(BufferPage)#Internal error: Failed to reuse a created initial page.");
						numbers = (vuint64_t*)newPageDesc->address;
						numbers[INDEX_FREEITEM_FREEPAGEITEMS] = 1;
						numbers[INDEX_FREEITEM_FREEPAGEITEMBEGIN] = page.index;
						CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileFreePages::PushFreePage(page)#Internal error: Failed to call msync.");
					}
					activeFreeItemPageIndex++;
				}
				else
				{
					numbers[INDEX_FREEITEM_FREEPAGEITEMBEGIN + count] = page.index;
					count++;
					CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileFreePages::PushFreePage(page)#Internal error: Failed to call msync.");
				}
			}

			BufferPage FileFreePages::PopFreePage()
			{
				BufferPage page = BufferPage::Invalid();
				BufferPage initialPage{freeItemPages[activeFreeItemPageIndex]};
				auto pageDesc = fileMapping->MapPage(initialPage);
				CHECK_ERROR(pageDesc != nullptr, L"vl::database::buffer_internal::FileFreePages::PopFreePage()#Internal error: Failed to map the last active initial page.");
				vuint64_t* numbers = (vuint64_t*)pageDesc->address;
				vuint64_t& count = numbers[INDEX_FREEITEM_FREEPAGEITEMS];

				if (count == 0 && initialPage.index == INDEX_PAGE_FREEITEM)
				{
					return page;
				}
				count--;
				page.index = numbers[INDEX_FREEITEM_FREEPAGEITEMBEGIN + count];
				CHECK_ERROR(msync(numbers, pageSize, MS_SYNC) != -1, L"vl::database::buffer_internal::FileFreePages::PopFreePage()#Internal error: Failed to call msync.");

				if (count == 0)
				{
					activeFreeItemPageIndex--;
					if (activeFreeItemPageIndex == -1)
					{
						activeFreeItemPageIndex = 0;
					}
				}
				return page;
			}

/***********************************************************************
FileBufferSource
***********************************************************************/

		FileBufferSource::FileBufferSource(BufferSource _source, volatile vuint64_t* _totalUsedPages, vuint64_t _pageSize, const WString& _fileName, int _fileDescriptor)
			:source(_source)
			,pageSize(_pageSize)
			,fileName(_fileName)
			,fileDescriptor(_fileDescriptor)
			,fileMapping(_pageSize, _fileDescriptor, _totalUsedPages)
			,fileUseMasks(_pageSize, _fileDescriptor)
			,fileFreePages(_pageSize)
		{
			indexPage.index = INDEX_PAGE_INDEX;
		}

		void FileBufferSource::InitializeEmptySource()
		{
			fileMapping.InitializeEmptySource();
			fileUseMasks.InitializeEmptySource(&fileMapping);
			fileFreePages.InitializeEmptySource(&fileMapping, &fileUseMasks);

			auto pageDesc = fileMapping.MapPage(BufferPage{INDEX_PAGE_INDEX});
			CHECK_ERROR(pageDesc != nullptr, L"vl::database::FileBufferSource::InitializeEmptySource()#Internal error: Failed to map INDEX_PAGE_INDEX.");

			fileUseMasks.SetUseMask(BufferPage{INDEX_PAGE_FREEITEM}, true);
			fileUseMasks.SetUseMask(BufferPage{INDEX_PAGE_USEMASK}, true);
			fileUseMasks.SetUseMask(BufferPage{INDEX_PAGE_INDEX}, true);
		}

		void FileBufferSource::InitializeExistingSource()
		{
			fileMapping.InitializeExistingSource();
			fileUseMasks.InitializeExistingSource(&fileMapping);
			fileFreePages.InitializeExistingSource(&fileMapping, &fileUseMasks);
		}

		void FileBufferSource::Unload()
		{
			fileMapping.UnmapAllPages();
			CloseFileForFileSource(fileDescriptor);
		}

		BufferSource FileBufferSource::GetBufferSource()
		{
			return source;
		}

		SpinLock& FileBufferSource::GetLock()
		{
			return lock;
		}

		WString FileBufferSource::GetFileName()
		{
			return fileName;
		}

		bool FileBufferSource::UnmapPage(BufferPage page)
		{
			return fileMapping.UnmapPage(page);
		}

		BufferPage FileBufferSource::GetIndexPage()
		{
			return indexPage;
		}

		BufferPage FileBufferSource::AllocatePage()
		{
			BufferPage page = fileFreePages.PopFreePage();
			if (!page.IsValid())
			{
				page = fileMapping.AppendPage();
			}
			if (page.IsValid())
			{
				fileUseMasks.SetUseMask(page, true);
			}
			return page;
		}

		bool FileBufferSource::FreePage(BufferPage page)
		{
			switch(page.index)
			{
				case INDEX_PAGE_FREEITEM:
				case INDEX_PAGE_USEMASK:
				case INDEX_PAGE_INDEX:
					return false;
			}

			if (!fileUseMasks.GetUseMask(page)) return false;
			if (fileMapping.GetMappedPageDesc(page))
			{
				if (!UnmapPage(page))
				{
					return false;
				}
			}
			fileFreePages.PushFreePage(page);
			fileUseMasks.SetUseMask(page, false);
			return true;
		}

		void* FileBufferSource::LockPage(BufferPage page)
		{
			if (page.index >= fileMapping.GetTotalPageCount())
			{
				return nullptr;
			}
			if (!fileUseMasks.GetUseMask(page)) return nullptr;
			if (auto pageDesc = fileMapping.MapPage(page))
			{
				if (pageDesc->locked) return nullptr;
				pageDesc->locked = true;
				return pageDesc->address;
			}
			else
			{
				return nullptr;
			}
		}

		bool FileBufferSource::UnlockPage(BufferPage page, void* buffer, PersistanceType persistanceType)
		{
			auto pageDesc = fileMapping.GetMappedPageDesc(page);
			if (!pageDesc) return false;
			if (pageDesc->address != buffer) return false;
			if (!pageDesc->locked) return false;

			switch (persistanceType)
			{
				case PersistanceType::NoChanging:
					break;
				case PersistanceType::Changed:
					pageDesc->dirty = true;
					break;
				case PersistanceType::ChangedAndPersist:
					msync(pageDesc->address, pageSize, MS_SYNC);
					pageDesc->dirty = false;
					break;
			}
			pageDesc->locked = false;
			return true;
		}

		void FileBufferSource::FillUnmapPageCandidates(collections::List<BufferPageTimeTuple>& pages, vint expectCount)
		{
			vint mappedCount = fileMapping.GetMappedPageCount();
			if (mappedCount == 0) return;

			Array<BufferPageTimeTuple> tuples(mappedCount);
			vint usedCount = 0;
			for (vint i = 0; i < mappedCount; i++)
			{
				auto key = fileMapping.GetMappedPage(i);
				auto value = fileMapping.GetMappedPageDesc(i);
				if (!value->locked)
				{
					BufferPage page{key};
					tuples[usedCount++] = BufferPageTimeTuple(source, page, value->lastAccessTime);
				}
			}

			if (tuples.Count() > 0)
			{
				SortLambda(&tuples[0], usedCount, [](const BufferPageTimeTuple& t1, const BufferPageTimeTuple& t2)
				{
					if (t1.f2 < t2.f2) return -1;
					else if (t1.f2 > t2.f2) return 1;
					else return 0;
				});

				vint copyCount = usedCount < expectCount ? usedCount : expectCount;
				for (vint i = 0; i < copyCount; i++)
				{
					pages.Add(tuples[i]);
				}
			}
		}

		int CreateNewFileForFileSource(const WString& fileName)
		{
			auto mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
			return open(wtoa(fileName).Buffer(), O_CREAT | O_TRUNC | O_RDWR, mode);
		}

		int OpenExistingFileForFileSource(const WString& fileName)
		{
			return open(wtoa(fileName).Buffer(), O_RDWR);
		}

		void CloseFileForFileSource(int fileDescriptor)
		{
			close(fileDescriptor);
		}

		IBufferSource* CreateFileSource(BufferSource source, volatile vuint64_t* totalUsedPages, vuint64_t pageSize, const WString& fileName, bool createNew)
		{
			int fileDescriptor = 0;
			if (createNew)
			{
				fileDescriptor = CreateNewFileForFileSource(fileName);
			}
			else
			{
				fileDescriptor = OpenExistingFileForFileSource(fileName);
			}

			if (fileDescriptor == -1)
			{
				return nullptr;
			}
			else
			{
				auto result = new FileBufferSource(source, totalUsedPages, pageSize, fileName, fileDescriptor);
				if (createNew)
				{
					result->InitializeEmptySource();
				}
				else
				{
					result->InitializeExistingSource();
				}
				return result;
			}
		}
	}
}

#undef INDEX_INVALID
#undef INDEX_PAGE_FREEITEM
#undef INDEX_PAGE_USEMASK
#undef INDEX_PAGE_INDEX
#undef INDEX_FREEITEM_NEXTINITIALPAGE
#undef INDEX_FREEITEM_FREEPAGEITEMS
#undef INDEX_FREEITEM_FREEPAGEITEMBEGIN
#undef INDEX_USEMASK_NEXTUSEMASKPAGE
#undef INDEX_USEMASK_USEMASKBEGIN


text:
/**
 * @file   FTAddMyTask.C
 * @author Freja Thoresen <freja.thoresen@cern.ch>
 *
 * @brief  Add Q-cummulant forward task to train
 *
 *
 * @ingroup pwglf_forward_scripts_tasks
 */
/**
 * @defgroup pwglf_forward_flow Flow
 *
 * Code to deal with flow
 *
 * @ingroup pwglf_forward_topical
 */
/**
 * Add Flow task to train
 *
 * @ingroup pwglf_forward_flow
 */
 // #include "AliForwardSettings.h"
 // #include "AliAnalysisDataContainer.h"
 // #include "AliAnalysisDataSlot.h"

AliAnalysisDataContainer* makeWeightContainer(TString nua_file, TString containerName){
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer* weights;
  if (nua_file.Contains("alien:")) {
    std::cout << "I-AddTaskForwardSecondaries: Connecting to alien" << std::endl;
    TGrid::Connect("alien:");
  }
  std::cout << nua_file << std::endl;
  TFile* file;
  file = TFile::Open(nua_file.Data(), "READ");

  if(!file) { printf("E-AddTaskForwardSecondaries: Input file with differential weights not found!\n"); return NULL; }

  TList* weights_list = new TList();
  weights_list->SetName("nuaWeights");

  TH3F* nuacentral = new TH3F();
  TH3F* nuaforward = new TH3F();

  file->GetObject("nuacentral", nuacentral);
  nuacentral->SetDirectory(0);
  nuacentral->SetNameTitle("nuacentral","nuacentral");

  file->GetObject("nuaforward", nuaforward);
  nuaforward->SetDirectory(0);
  nuaforward->SetNameTitle("nuaforward","nuaforward");
  file->Close();

  weights_list->Add(nuacentral);
  weights_list->Add(nuaforward);

  weights = mgr->CreateContainer(containerName,TList::Class(), AliAnalysisManager::kInputContainer,Form("%s", mgr->GetCommonFileName()));
  weights->SetData(weights_list);
  return weights;
}

void connectContainer(AliAnalysisDataContainer* container,AliForwardSecondariesTask* task){

  task->fSettings.nuacentral = static_cast<TH3F*>( static_cast<TList*>(container->GetData())->FindObject("nuacentral") );
  task->fSettings.nuaforward = static_cast<TH3F*>( static_cast<TList*>(container->GetData())->FindObject("nuaforward") );
  task->fSettings.nuacentral->SetDirectory(0);
  task->fSettings.nuaforward->SetDirectory(0);
}

AliAnalysisDataContainer* makeEmptyContainer(){
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer* weights;

  TList* weights_list = new TList();
  weights_list->SetName("empty");

  weights = mgr->CreateContainer("emptyContainer",TList::Class(), AliAnalysisManager::kInputContainer,Form("%s", mgr->GetCommonFileName()));

  return weights;
}

AliAnalysisTaskSE* AddTaskForwardSecondaries(TString taskname)
{
  std::cout << "AddTaskForwardSecondaries" << std::endl;

  // --- Get analysis manager ----------------------------------------
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    Fatal("","No analysis manager to connect to.");

  const char* name = Form("ForwardFlowQC");
  AliForwardSecondariesTask* task = new AliForwardSecondariesTask(name);
  TString resName = "Secondaries";

  //TString nua_file =  "/home/thoresen/Documents/PhD/plots/nua/Datasets/LHC17i2f/ESD/maxstrip0/fmdreco_tpcreco_runsz.root";
  TString nua_file = "/home/thoresen/Documents/PhD/plots/nua/Datasets/LHC17i2f/ESD/fmdreco_tpcreco_runsz.root";

  Bool_t doNUA = kTRUE;

  task->fSettings.fileName = resName;
  mgr->AddTask(task);

  AliAnalysisDataContainer *coutput_recon =
  mgr->CreateContainer(resName,
   AliForwardFlowResultStorage::Class(), //TList::Class(),
   AliAnalysisManager::kOutputContainer,
   mgr->GetCommonFileName());
  //task->fSettings.fDataType = task->fSettings.kRECON;
  mgr->ConnectOutput(task, 1, coutput_recon);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());

  AliAnalysisDataContainer* valid = (AliAnalysisDataContainer*)mgr->GetContainers()->FindObject("event_selection_xchange");
  task->ConnectInput(1,valid);

  if (doNUA){
    std::cout << "doing NUA" << std::endl;
    TObjArray* taskContainers = mgr->GetContainers();
    AliAnalysisDataContainer* weights;

    TObjArray *tx = nua_file.Tokenize("/");
    TObjArray *ty = ((TObjString *)(tx->At(tx->GetEntries()-1)))->String().Tokenize(".");
    TString nuaobject =  ((TObjString *)(ty->At(0)))->String();
    std::cout << "I-AddTaskForwardSecondaries: NUA container " << nuaobject << std::endl;

    weights = (AliAnalysisDataContainer*) taskContainers->FindObject(nuaobject);

    if (!weights) {
      std::cout << "I-AddTaskForwardSecondaries: " << nuaobject << " weights not defined - reading now. " << std::endl;
      weights = makeWeightContainer(nua_file,nuaobject);
    }
    connectContainer( weights, task);
  }

  return task;
}
/*
 * EOF
 *
 */

redpajama_set_name: RedPajamaGithub


text:
/*jshint node:true*/
'use strict';

var gulp = require('gulp');
// load all gulp modules in a 'plugin' object
var plugins = require('gulp-load-plugins')({lazy: true});
// command line options
var args = require('yargs').argv;
// gulp config file
var config = require('./gulp.config')();

gulp.task('default', ['help']);

// print available gulp tasks
gulp.task('help', plugins.taskListing);

// analyze code for potential issues
gulp.task('vet', function() {
  log('Performing code analysis using JSHint');
  return gulp
    // analyze all js files
    .src(config.alljs)
    // print processed files if verbose
    .pipe(plugins.if(args.verbose, plugins.print()))
    // analyze
    .pipe(plugins.jshint())
    // report
    .pipe(plugins.jshint.reporter('jshint-stylish', {verbose: true}))
    // fail task if code violations were found
    .pipe(plugins.jshint.reporter('fail'));
});

// run mocha tests
gulp.task('test', ['vet'], function() {
  return gulp
    .src(config.testjs)
    .pipe(plugins.mocha());
});

// git pre-commit hook
gulp.task('pre-commit', ['test']);

function log(msg) {
  plugins.util.log(msg);
}


text:
package guru.nidi.codeassert.dependency;

import guru.nidi.codeassert.model.UsingElement;

import java.util.*;
import java.util.Map.Entry;

import static java.util.Collections.emptyMap;

public class DependencyMap {
    private final Map<String, Map<String, Info>> map = new LinkedHashMap<>();

    public <T> void with(int specificity, UsingElement<T> from, UsingElement<T> to) {
        with(specificity, from.getName(), from.usedVia(to), to.getName());
    }

    DependencyMap with(int specificity, String from, Collection<String> vias, String to) {
        final Map<String, Info> deps = map.computeIfAbsent(from, k -> new HashMap<>());
        final Info info = deps.get(to);
        if (info == null) {
            deps.put(to, new Info(vias, specificity));
        } else {
            //TODO specificity?
            info.getVias().addAll(vias);
        }
        return this;
    }

    DependencyMap with(String from, DependencyMap other) {
        final Map<String, Info> infos = other.getDependencies(from);
        for (final Entry<String, Info> entry : infos.entrySet()) {
            final Info info = entry.getValue();
            with(info.getSpecificity(), from, info.getVias(), entry.getKey());
        }
        return this;
    }

    public DependencyMap without(int specificity, String from, String to) {
        final Map<String, Info> deps = map.get(from);
        if (deps != null) {
            final Info info = deps.get(to);
            if (info != null && specificity > info.specificity) {
                deps.remove(to);
                if (deps.isEmpty()) {
                    map.remove(from);
                }
            }
        }
        return this;
    }

    public DependencyMap without(DependencyMap other) {
        for (final Entry<String, Map<String, Info>> entry : other.map.entrySet()) {
            for (final Entry<String, Info> to : entry.getValue().entrySet()) {
                without(to.getValue().specificity, entry.getKey(), to.getKey());
            }
        }
        return this;
    }

    public void merge(DependencyMap deps) {
        for (final Entry<String, Map<String, Info>> entry : deps.map.entrySet()) {
            final Map<String, Info> ds = map.get(entry.getKey());
            if (ds == null) {
                map.put(entry.getKey(), entry.getValue());
            } else {
                ds.putAll(entry.getValue());
            }
        }
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public void clear() {
        map.clear();
    }

    public Set<String> getElements() {
        return map.keySet();
    }

    /**
     * @param name the name of the element
     * @return A map with all dependencies of a given package.
     * Key: package, Value: A set of all classes importing the package
     */
    public Map<String, Info> getDependencies(String name) {
        return map.getOrDefault(name, emptyMap());
    }

    public Info getDependency(String from, String to) {
        return getDependencies(from).get(to);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final DependencyMap that = (DependencyMap) o;

        return map.equals(that.map);

    }

    @Override
    public int hashCode() {
        return map.hashCode();
    }

    @Override
    public String toString() {
        return map.toString();
    }

    public static class Info {
        private final Set<String> vias;
        private final int specificity;

        Info(Collection<String> vias, int specificity) {
            this.vias = new HashSet<>(vias);
            this.specificity = specificity;
        }

        public Set<String> getVias() {
            return vias;
        }

        public int getSpecificity() {
            return specificity;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            final Info info = (Info) o;
            return vias.equals(info.vias);
        }

        @Override
        public int hashCode() {
            return vias.hashCode();
        }

        @Override
        public String toString() {
            return vias.toString();
        }
    }
}


text:
module RubyLint
  module Definition
    ##
    # The RubyObject class is the base definition class of ruby-lint. These so
    # called definition classes are used for storing information about Ruby
    # classes and instances. At their most basic form they are a mix between
    # {RubyLint::Node} and a lookup table.
    #
    # ruby-lint currently provides the following two definition classes:
    #
    # * {RubyLint::Definition::RubyObject}: the base definition class, used for
    #   most Ruby types and values.
    # * {RubyLint::Definition::RubyMethod} definition class that is used for
    #   methods exclusively.
    #
    # Using the RubyObject class one could create a definition for the String
    # class as following:
    #
    #     string  = RubyObject.new(:name => 'String', :type => :const)
    #     newline = RubyObject.new(
    #       :name  => 'NEWLINE',
    #       :type  => :const,
    #       :value => "\n"
    #     )
    #
    #     string.add(:const, newline.name, newline)
    #
    # For more information see the documentation of the corresponding methods.
    #
    # @!attribute [r] name
    #  @return [String] The name of the object.
    #
    # @!attribute [rw] value
    #  @return [Mixed] The value of the object.
    #
    # @!attribute [r] type
    #  @return [Symbol] The type of object, e.g. `:const`.
    #
    # @!attribute [r] definitions
    #  @return [Hash] Hash containing all child the definitions.
    #
    # @!attribute [rw] parents
    #  @return [Array] Array containing the parent definitions.
    #
    # @!attribute [rw] reference_amount
    #  @return [Numeric] The amount of times an object was referenced.
    #   Currently this is only used for variables.
    #
    # @!attribute [rw] instance_type
    #  @return [Symbol] Indicates if the object represents a class or an
    #   instance.
    #
    # @!attribute [r] update_parents
    #  @return [Array] A list of data types to also add to the parent
    #   definitions when adding an object to the current one.
    #
    # @!attribute [r] members_as_value
    #  @return [TrueClass|FalseClass] When set to `true` the {#value} getter
    #   returns a collection of the members instead of the manually defined
    #   value.
    #
    # @!attribute [r] line
    #  @return [Numeric] The line number of the definition.
    #
    # @!attribute [r] column
    #  @return [Numeric] The column number of the definition.
    #
    # @!attribute [r] file
    #  @return [String] The file path of the definition.
    #
    # @!attribute [r] inherit_self
    #  @return [TrueClass|FalseClass] When set to `false` child definitions
    #   created using `define_constant` do not inherit the current definition.
    #
    class RubyObject
      include VariablePredicates

      ##
      # Array containing items that should be looked up in the parent
      # definition if they're not found in the current one.
      #
      # @return [Array]
      #
      LOOKUP_PARENT = [
        :const,
        :cvar,
        :gvar,
        :instance_method,
        :ivar,
        :method
      ].freeze

      ##
      # String used to separate segments in a constant path.
      #
      # @return [String]
      #
      PATH_SEPARATOR = '::'.freeze

      ##
      # Array containing the valid data types that can be stored.
      #
      # @return [Array<Symbol>]
      #
      VALID_TYPES = [
        :arg,
        :blockarg,
        :const,
        :cvar,
        :gvar,
        :instance_method,
        :ivar,
        :kwoptarg,
        :lvar,
        :member,
        :method,
        :optarg,
        :restarg,
        :unknown
      ].freeze

      attr_reader :update_parents,
        :column,
        :definitions,
        :file,
        :inherit_self,
        :line,
        :members_as_value,
        :name,
        :type

      attr_accessor :instance_type, :parents, :reference_amount

      ##
      # Creates an object that represents an unknown value.
      #
      # @return [RubyLint::Definition::RubyObject]
      #
      def self.create_unknown
        return new(:type => :unknown, :name => 'unknown')
      end

      ##
      # @example
      #  string = RubyObject.new(:name => 'String', :type => :const)
      #
      # @param [Hash] options Hash containing additional options such as the
      #  parent definitions. For a list of available options see the
      #  corresponding getter/setter methods of this class.
      #
      # @yieldparam [RubyLint::Definition::RubyObject]
      #
      def initialize(options = {})
        @inherit_self = true

        options.each do |key, value|
          instance_variable_set("@#{key}", value)
        end

        @update_parents   ||= []
        @instance_type    ||= :class
        @parents          ||= []
        @reference_amount ||= 0

        @definitions = Hash.new { |hash, key| hash[key] = {} }
        @value       = nil if members_as_value

        after_initialize if respond_to?(:after_initialize)

        yield self if block_given?
      end

      ##
      # Returns the value of the definition. If `members_as_value` is set to
      # `true` the return value is a Hash containing the names and values of
      # each member.
      #
      # @return [Hash|RubyLint::Definition::RubyObject]
      #
      def value
        return members_as_value ? list(:member) : @value
      end

      ##
      # Sets the value of the definition.
      #
      # @param [Mixed] value
      #
      def value=(value)
        @value = value
      end

      ##
      # Adds the definition object to the current one.
      #
      # @see #add
      # @param [RubyLint::Definition::RubyObject] definition
      #
      def add_definition(definition)
        add(definition.type, definition.name, definition)
      end

      ##
      # Adds a new definition to the definitions list.
      #
      # @example
      #  string  = RubyObject.new(:name => 'String', :type => :const)
      #  newline = RubyObject.new(
      #    :name  => 'NEWLINE',
      #    :type  => :const,
      #    :value => "\n"
      #  )
      #
      #  string.add(newline.type, newline.name, newline)
      #
      # @param [#to_sym] type The type of definition to add.
      # @param [String] name The name of the definition.
      # @param [RubyLint::Definition::RubyObject] value
      #
      # @raise [TypeError] Raised when a value that is not a RubyObject
      #  instance (or a subclass of this class) is given.
      #
      # @raise [ArgumentError] Raised when the specified type was invalid.
      #
      def add(type, name, value)
        type = type.to_sym

        unless value.is_a?(RubyObject)
          raise TypeError, "Expected RubyObject but got #{value.class}"
        end

        unless VALID_TYPES.include?(type)
          raise ArgumentError, ":#{type} is not a valid type of data to add"
        end

        definitions[type][name] = value

        if update_parents.include?(type)
          update_parent_definitions(type, name, value)
        end
      end

      ##
      # Looks up a definition by the given type and name. If no data was found
      # this method will try to look it up in any parent definitions.
      #
      # If no definition was found `nil` will be returned.
      #
      # @example
      #  string  = RubyObject.new(:name => 'String', :type => :const)
      #  newline = RubyObject.new(
      #    :name  => 'NEWLINE',
      #    :type  => :const,
      #    :value => "\n"
      #  )
      #
      #  string.add(newline.type, newline.name, newline)
      #
      #  string.lookup(:const, 'NEWLINE') # => #<RubyLint::Definition...>
      #
      # @param [#to_sym] type
      # @param [String] name
      #
      # @param [TrueClass|FalseClass] lookup_parent Whether definitions should
      #  be looked up from parent definitions.
      #
      # @param [Array] exclude A list of definitions to skip when looking up
      #  parents. This list is used to prevent stack errors when dealing with
      #  recursive definitions. A good example of this is `Logger` and
      #  `Logger::Severity` which both inherit from each other.
      #
      # @return [RubyLint::Definition::RubyObject|NilClass]
      #
      def lookup(type, name, lookup_parent = true, exclude = [])
        type, name = prepare_lookup(type, name)
        found      = nil

        if defines?(type, name)
          found = definitions[type][name]

        # Look up the definition in the parent scope(s) (if any are set). This
        # takes the parents themselves also into account.
        elsif lookup_parent?(type) and lookup_parent
          parents.each do |parent|
            # If we've already processed the parent we'll skip it.
            next if exclude.include?(parent)

            parent_definition = determine_parent(parent, type, name, exclude)

            if parent_definition
              found = parent_definition
              break
            end
          end
        end

        return found
      end

      ##
      # Returns the definition for the given constant path.
      #
      # @example
      #  example.lookup_constant_path('A::B') # => #<RubyLint::Definition...>
      #
      # @param [String|Array<String>] path
      # @return [RubyLint::Definition::RubyObject]
      #
      def lookup_constant_path(path)
        constant = self
        path     = path.split(PATH_SEPARATOR) if path.is_a?(String)

        path.each do |segment|
          found = constant.lookup(:const, segment)

          found ? constant = found : return
        end

        return constant
      end

      ##
      # Mimics a method call by executing the method for the given name. This
      # method should be defined in the current definition.
      #
      # @param [String] name The name of the method.
      # @return [Mixed]
      #
      def call_method(name)
        method = lookup(method_call_type, name)

        unless method
          raise NoMethodError, "Undefined method #{name} for #{self.inspect}"
        end

        return method.call(self)
      end

      ##
      # Returns `true` if a method is defined, similar to `respond_to?`.
      #
      # @return [TrueClass|FalseClass]
      #
      def method_defined?(name)
        return has_definition?(method_call_type, name)
      end

      ##
      # Performs a method call on the current definition.
      #
      # If the return value of a method definition is set to a Proc (or any
      # other object that responds to `:call`) it will be called and passed the
      # current instance as an argument.
      #
      # TODO: add support for specifying method arguments.
      #
      # @param [RubyLint::Definition::RubyObject] context The context in which
      #  the method was called.
      # @return [Mixed]
      #
      def call(context = self)
        retval = respond_to?(:return_value) ? return_value : nil
        retval = retval.call(context) if retval.is_a?(Proc)

        return retval
      end

      ##
      # Returns `true` if the current definition list or one of the parents has
      # the specified definition.
      #
      # @example
      #  string.has_definition?(:instance_method, 'downcase') # => true
      #
      # @param [#to_sym] type
      # @param [String] name
      # @param [Array] exclude Parent definitions to exclude.
      # @return [TrueClass|FalseClass]
      #
      def has_definition?(type, name, exclude = [])
        type, name = prepare_lookup(type, name)

        if definitions.key?(type) and definitions[type].key?(name)
          return true

        elsif lookup_parent?(type)
          parents.each do |parent|
            next if exclude.include?(parent)

            return true if parent.has_definition?(type, name, exclude | [self])
          end
        end

        return false
      end

      ##
      # Determines the call types for methods called on the current definition.
      #
      # @return [Symbol]
      #
      def method_call_type
        return class? ? :method : :instance_method
      end

      ##
      # @return [TrueClass|FalseClass]
      #
      def class?
        return instance_type == :class
      end

      ##
      # @return [TrueClass|FalseClass]
      #
      def instance?
        return instance_type == :instance
      end

      ##
      # Checks if the specified definition is defined in the current object,
      # ignoring data in any parent definitions.
      #
      # @see RubyLint::Definition::RubyObject#has_definition?
      # @return [TrueClass|FalseClass]
      #
      def defines?(type, name)
        type, name = prepare_lookup(type, name)

        return definitions.key?(type) && definitions[type].key?(name)
      end

      ##
      # Returns a list of all the definitions for the specific type.  This list
      # excludes anything defined in parent definitions.
      #
      # @example
      #  string.list(:instance_method) # => [..., ..., ...]
      #
      # @param [#to_sym] type
      # @return [Array]
      #
      def list(type)
        type = type.to_sym

        return definitions.key?(type) ? definitions[type].values : []
      end

      ##
      # Returns the amount of definitions stored for a given type.
      #
      # @param [#to_sym] type
      # @return [Numeric]
      #
      def amount(type)
        return list(type).length
      end

      ##
      # Merges the definitions object `other` into the current one.
      #
      # @param [RubyLint::Definition::RubyObject] other
      #
      def merge(other)
        other.definitions.each do |type, values|
          values.each do |name, definition|
            definitions[type][name] = definition
          end
        end
      end

      ##
      # Copies all the definitions in `source` of type `type` into the current
      # definitions object.
      #
      # @param [RubyLint::Definition::RubyObject] source
      # @param [Symbol] source_type The type of definitions to copy from the
      #  source.
      # @param [Symbol] target_type The type to store the definitions under,
      #  set to the `source_type` value by default.
      #
      def copy(source, source_type, target_type = source_type)
        return unless source.definitions.key?(source_type)

        source.list(source_type).each do |definition|
          unless defines?(target_type, definition.name)
            add(target_type, definition.name, definition)
          end
        end
      end

      ##
      # Creates a new definition object based on the current one that
      # represents an instance of a Ruby value (instead of a class).
      #
      # @param [Hash] options Attributes to override in the new definition.
      # @return [RubyLint::Definition::RubyObject]
      #
      def instance(options = {})
        return shim(:instance_type => :instance)
      end

      ##
      # Creates a new definition that inherits from the current one, acting as
      # sort of a shim around the original one.
      #
      # @param [Hash] options Attributes to set in the new definition.
      # @return [RubyLint::Definition::RubyObject]
      #
      def shim(options = {})
        options = {
          :name          => name,
          :type          => type,
          :instance_type => instance_type,
          :value         => value,
          :parents       => [self]
        }.merge(options)

        return self.class.new(options)
      end

      ##
      # Changes the instance type of the current definition to `:instance`. If
      # you want to return a new definition use {#instance} instead.
      #
      def instance!
        @instance_type = :instance
      end

      ##
      # Returns `true` if the object was referenced more than once.
      #
      # @return [TrueClass|FalseClass]
      #
      def used?
        return reference_amount > 0
      end

      ##
      # Defines a new child constant.
      #
      # @example
      #  string.define_constant('NEWLINE')
      #
      # @param [String] name
      # @return [RubyLint::Definition::RubyObject]
      #
      def define_constant(name, &block)
        if name.include?(PATH_SEPARATOR)
          path       = name.split(PATH_SEPARATOR)
          target     = lookup_constant_path(path[0..-2])
          definition = target.define_constant(path[-1], &block)
        else
          definition = add_child_definition(:const, name, &block)
        end

        definition.define_self

        return definition
      end

      ##
      # Defines a new global variable in the current definition.
      #
      # @example
      #  string.define_global_variable('$name', '...')
      #
      # @param [String] name
      # @param [Mixed] value
      #
      def define_global_variable(name, value = self.class.create_unknown)
        return add_child_definition(:gvar, name, value)
      end

      ##
      # Defines a new class method.
      #
      # @example
      #  string.define_method(:new)
      #
      # @param [String] name
      # @return [RubyLint::Definition::RubyMethod]
      #
      def define_method(name, &block)
        return add_child_method(:method, name, &block)
      end

      ##
      # Defines a new instance method.
      #
      # @example
      #  string.define_instance_method(:gsub)
      #
      # @see RubyLint::Definition::RubyObject#define_method
      #
      def define_instance_method(name, &block)
        return add_child_method(:instance_method, name, &block)
      end

      ##
      # Helper method that makes it easier to provide the two constructor
      # methods `new` and `initialize`. The supplied block is yielded on both
      # method definitions.
      #
      # @example
      #  some_object.define_constructors do |method|
      #    method.argument('name')
      #  end
      #
      def define_constructors(&block)
        define_method('new', &block)
        define_instance_method('initialize', &block)
      end

      ##
      # Adds the object(s) to the list of parent definitions.
      #
      # @param [Array] definitions
      #
      def inherits(*definitions)
        self.parents.concat(definitions)
      end

      ##
      # @see {RubyLint::Definition::ConstantProxy#initialize}
      # @return [RubyLint::Definition::ConstantProxy]
      #
      def constant_proxy(name, registry = nil)
        return ConstantProxy.new(self, name, registry)
      end

      ##
      # Defines `self` on the current definition as both a class and instance
      # method.
      #
      def define_self
        if instance?
          self_instance = self
          self_class    = instance(:instance_type => :class)
        else
          self_instance = self.instance
          self_class    = self
        end

        define_method('self') do |method|
          method.returns(self_class)
        end

        define_instance_method('self') do |method|
          method.returns(self_instance)
        end
      end

      ##
      # Returns a pretty formatted String that shows some info about the
      # current definition.
      #
      # @return [String]
      #
      def inspect
        attributes = [
          %Q(@name="#{name}"),
          %Q(@type="#{type}"),
          %Q(@instance_type="#{instance_type}")
        ]

        # See <http://stackoverflow.com/a/2818916> for more info.
        address = (object_id << 1).to_s(16)

        return %Q(#<#{self.class}:0x#{address} #{attributes.join(' ')}>)
      end

      private

      ##
      # Updates each parent definition if it has an existing definition for hte
      # given type and name.
      #
      # @see #add
      #
      def update_parent_definitions(type, name, value)
        parents.each do |parent|
          parent.add(type, name, value) if parent.has_definition?(type, name)
        end
      end

      ##
      # Determines what parent definition to use.
      #
      # @param [RubyLint::Definition::RubyObject] parent
      # @param [Symbol] type
      # @param [String] name
      # @param [Array] exclude
      # @return [RubyLint::Definition::RubyObject]
      #
      def determine_parent(parent, type, name, exclude = [])
        if parent.type == type and parent.name == name
          parent_definition = parent
        else
          parent_definition = parent.lookup(type, name, true, exclude | [self])
        end

        return parent_definition
      end

      ##
      # Adds a new child definition to the current definition.
      #
      # @param [Symbol] type The definition type.
      # @param [String] name The name of the definition.
      # @param [Mixed] value
      # @return [RubyLint::Definition::RubyObject]
      #
      def add_child_definition(type, name, value = nil, &block)
        definition = self.class.new(
          :name    => name,
          :type    => type,
          :value   => value,
          :parents => inherit_self ? [self] : nil,
          &block
        )

        add(definition.type, definition.name, definition)

        return definition
      end

      ##
      # Adds a new child method to the current definition.
      #
      # @see RubyLint::Definition::RubyObject#add_child_definition
      #
      def add_child_method(type, name, &block)
        definition = RubyMethod.new(
          :name          => name,
          :type          => type,
          :parents       => [self],
          :instance_type => :instance,
          &block
        )

        add(definition.type, definition.name, definition)

        return definition
      end

      ##
      # Returns a boolean that indicates if the current definition type should
      # be looked up in a parent definition.
      #
      # @param  [Symbol] type The type of definition.
      # @return [Trueclass|FalseClass]
      #
      def lookup_parent?(type)
        return LOOKUP_PARENT.include?(type) && !parents.empty?
      end

      ##
      # Casts the type and name of data to look up to the correct values.
      #
      # @param [#to_sym] type
      # @param [#to_s] name
      # @return [Array]
      #
      def prepare_lookup(type, name)
        return type.to_sym, name.to_s
      end
    end # RubyObject
  end # Definition
end # RubyLint


text:
#include "tensorflow/core/framework/tensor_util.h"

#include <vector>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/stringpiece.h"

namespace tensorflow {
namespace tensor {

Tensor DeepCopy(const Tensor& other) {
  Tensor tmp = Tensor(other.dtype(), other.shape());
  if (DataTypeCanUseMemcpy(other.dtype())) {
    StringPiece other_data = other.tensor_data();

    // We use StringPiece as a convenient map over the tensor buffer,
    // but we cast the type to get to the underlying buffer to do the
    // copy.
    StringPiece tmp_data = tmp.tensor_data();
    memcpy(const_cast<char*>(tmp_data.data()), other_data.data(),
           other_data.size());
  } else {
    CHECK_EQ(DT_STRING, other.dtype());
    tmp.flat<string>() = other.flat<string>();
  }
  return tmp;
}

Tensor Concat(const gtl::ArraySlice<Tensor>& tensors) {
  CHECK_GT(tensors.size(), size_t{0});
  int64 total_dim0_size = 0;
  for (const Tensor& tensor : tensors) {
    CHECK_GT(tensor.dims(), 0);
    total_dim0_size += tensor.dim_size(0);
  }
  TensorShape shape = tensors[0].shape();
  shape.set_dim(0, total_dim0_size);
  Tensor result = Tensor(tensors[0].dtype(), shape);

  // We use StringPiece as a convenient map over the tensor buffer,
  // but we cast the type to get to the underlying buffer to do the
  // copy.
  StringPiece to_data = result.tensor_data();

  if (DataTypeCanUseMemcpy(result.dtype())) {
    int64 offset = 0;
    for (const Tensor& tensor : tensors) {
      StringPiece from_data = tensor.tensor_data();
      CHECK_LE(offset + from_data.size(), to_data.size());
      memcpy(const_cast<char*>(to_data.data()) + offset, from_data.data(),
             from_data.size());

      offset += from_data.size();
    }
  } else {
    CHECK_EQ(DT_STRING, result.dtype());
    string* to_strings =
        reinterpret_cast<string*>(const_cast<char*>(to_data.data()));

    int64 offset = 0;
    for (const Tensor& tensor : tensors) {
      auto from_strings = tensor.flat<string>();
      CHECK_LE(offset + tensor.NumElements(), result.NumElements());
      for (int i = 0; i < tensor.NumElements(); ++i) {
        to_strings[offset + i] = from_strings(i);
      }

      offset += tensor.NumElements();
    }
  }

  return result;
}

std::vector<Tensor> Split(const Tensor& tensor,
                          const gtl::ArraySlice<int64>& sizes) {
  CHECK_GT(tensor.dims(), 0);
  int64 total_size = 0;
  for (int64 size : sizes) {
    total_size += size;
  }
  CHECK_EQ(total_size, tensor.dim_size(0));

  std::vector<Tensor> result;

  StringPiece from_data = tensor.tensor_data();

  if (DataTypeCanUseMemcpy(tensor.dtype())) {
    int64 offset = 0;
    for (int64 size : sizes) {
      TensorShape shape = tensor.shape();
      shape.set_dim(0, size);
      result.emplace_back(tensor.dtype(), shape);
      Tensor* split = &result[result.size() - 1];

      // We use StringPiece as a convenient map over the tensor buffer,
      // but we cast the type to get to the underlying buffer to do the
      // copy.
      StringPiece to_data = split->tensor_data();
      CHECK_LE(offset + to_data.size(), from_data.size());
      memcpy(const_cast<char*>(to_data.data()), from_data.data() + offset,
             to_data.size());

      offset += to_data.size();
    }
  } else {
    CHECK_EQ(DT_STRING, tensor.dtype());
    auto from_strings = tensor.flat<string>();

    int64 offset = 0;
    for (int64 size : sizes) {
      TensorShape shape = tensor.shape();
      shape.set_dim(0, size);
      result.emplace_back(tensor.dtype(), shape);
      Tensor& split = result[result.size() - 1];
      string* to_strings = reinterpret_cast<string*>(
          const_cast<char*>(split.tensor_data().data()));

      CHECK_LE(offset + split.NumElements(), tensor.NumElements());
      for (int i = 0; i < split.NumElements(); ++i) {
        to_strings[i] = from_strings(offset + i);
      }

      offset += split.NumElements();
    }
  }

  return result;
}

}  // namespace tensor
}  // namespace tensorflow


text: export default fn => (...args) => !fn(...args);


text:
using System.Configuration;

namespace CommonProvider.ConfigSources.Xml.Configuration
{
    /// <summary>
    /// Represents a Types configuration element collection.
    /// </summary>
    public class TypeElementCollection : ConfigurationElementCollection
    {
        /// <summary>
        /// Creates a new Type configuration element.
        /// </summary>
        /// <returns>An instance of a Type configuration element.</returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new TypeElement();
        }

        /// <summary>
        /// Gets the unique identifier for a Type configuration element.
        /// </summary>
        /// <param name="element">The Type configuration element.</param>
        /// <returns>The unique identifier Type configuration element.</returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TypeElement)element).Name;
        }

        /// <summary>
        /// Adds a configuration element to the collection.
        /// </summary>
        /// <param name="element">The element to add.</param>
        internal void Add(TypeElement element)
        {
            this.BaseAdd(element);
        }

        /// <summary>
        /// Removes all configuration elements from the collection.
        /// </summary>
        internal void Clear()
        {
            this.BaseClear();
        }
    }
}


text:
#ifndef __PTHREAD_H__
#define __PTHREAD_H__

#include <rtthread.h>
#include <posix_types.h>

#define PTHREAD_KEY_MAX             8

#define PTHREAD_COND_INITIALIZER    {-1, 0}
#define PTHREAD_RWLOCK_INITIALIZER  {-1, 0}
#define PTHREAD_MUTEX_INITIALIZER   {-1, 0}

#define PTHREAD_CREATE_JOINABLE     0x00
#define PTHREAD_CREATE_DETACHED     0x01

#define PTHREAD_EXPLICIT_SCHED      0
#define PTHREAD_INHERIT_SCHED       1

typedef rt_thread_t pthread_t;
typedef long pthread_condattr_t;
typedef long pthread_rwlockattr_t;
typedef long pthread_mutexattr_t;
typedef long pthread_barrierattr_t;

typedef int pthread_key_t;
typedef int pthread_once_t;

enum
{
    PTHREAD_CANCEL_ASYNCHRONOUS = 0,
    PTHREAD_CANCEL_ENABLE,
    PTHREAD_CANCEL_DEFERRED,
    PTHREAD_CANCEL_DISABLE,
    PTHREAD_CANCELED
};

enum
{
    PTHREAD_MUTEX_NORMAL = 0,
    PTHREAD_MUTEX_RECURSIVE = 1,
    PTHREAD_MUTEX_ERRORCHECK = 2,
    PTHREAD_MUTEX_ERRORCHECK_NP = PTHREAD_MUTEX_ERRORCHECK,
    PTHREAD_MUTEX_RECURSIVE_NP  = PTHREAD_MUTEX_RECURSIVE,
    PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
};

/* init value for pthread_once_t */
#define PTHREAD_ONCE_INIT       0

enum
{
    PTHREAD_PRIO_INHERIT =0,
    PTHREAD_PRIO_NONE,
    PTHREAD_PRIO_PROTECT,
};

#define PTHREAD_PROCESS_PRIVATE  0
#define PTHREAD_PROCESS_SHARED   1

#define PTHREAD_SCOPE_PROCESS   0
#define PTHREAD_SCOPE_SYSTEM    1

struct pthread_attr
{
    void*       stack_base;
    rt_uint16_t stack_size;     /* stack size of thread */

    rt_uint8_t priority;        /* priority of thread */
    rt_uint8_t detachstate;     /* detach state */
    rt_uint8_t policy;          /* scheduler policy */
    rt_uint8_t inheritsched;    /* Inherit parent prio/policy */
};
typedef struct pthread_attr pthread_attr_t;

struct pthread_mutex
{
    pthread_mutexattr_t attr;
    struct rt_mutex lock;
};
typedef struct pthread_mutex pthread_mutex_t;

struct pthread_cond
{
    pthread_condattr_t attr;
    struct rt_semaphore sem;
};
typedef struct pthread_cond pthread_cond_t;

struct pthread_rwlock
{
    pthread_rwlockattr_t attr;

    pthread_mutex_t      rw_mutex;          /* basic lock on this struct */
    pthread_cond_t       rw_condreaders;    /* for reader threads waiting */
    pthread_cond_t       rw_condwriters;    /* for writer threads waiting */

    int rw_nwaitreaders;    /* the number of reader threads waiting */
    int rw_nwaitwriters;    /* the number of writer threads waiting */
    int rw_refcount;    /* 0: unlocked, -1: locked by writer, > 0 locked by n readers */
};
typedef struct pthread_rwlock pthread_rwlock_t;

/* spinlock implementation, (ADVANCED REALTIME THREADS)*/
struct pthread_spinlock
{
    int lock;
};
typedef struct pthread_spinlock pthread_spinlock_t;

struct pthread_barrier
{
    int count;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
};
typedef struct pthread_barrier pthread_barrier_t;

/* pthread thread interface */
int pthread_attr_destroy(pthread_attr_t *attr);
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int state);
int pthread_attr_getdetachstate(pthread_attr_t const *attr, int *state);
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);
int pthread_attr_getschedpolicy(pthread_attr_t const *attr, int *policy);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stack_size);
int pthread_attr_getstacksize(pthread_attr_t const *attr, size_t *stack_size);
int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stack_addr);
int pthread_attr_getstackaddr(pthread_attr_t const *attr, void **stack_addr);
int pthread_attr_setstack(pthread_attr_t *attr,
                          void           *stack_base,
                          size_t          stack_size);
int pthread_attr_getstack(pthread_attr_t const *attr,
                          void                **stack_base,
                          size_t               *stack_size);

int pthread_system_init(void);
int pthread_create (pthread_t *tid, const pthread_attr_t *attr,
    void *(*start) (void *), void *arg);

int pthread_detach (pthread_t thread);
int pthread_join (pthread_t thread, void **value_ptr);

rt_inline int pthread_equal (pthread_t t1, pthread_t t2)
{
    return t1 == t2;
}

rt_inline pthread_t pthread_self (void)
{
    return rt_thread_self();
}

void pthread_exit (void *value_ptr);
int pthread_once(pthread_once_t * once_control, void (*init_routine) (void));

/* pthread cleanup */
void pthread_cleanup_pop(int execute);
void pthread_cleanup_push(void (*routine)(void*), void *arg);

/* pthread cancel */
int pthread_cancel(pthread_t thread);
void pthread_testcancel(void);
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);

int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void));
int pthread_kill(pthread_t thread, int sig);

/* pthread mutex interface */
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);

int pthread_mutexattr_init(pthread_mutexattr_t *attr);
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int  pshared);
int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared);

/* pthread condition interface */
int pthread_condattr_destroy(pthread_condattr_t *attr);
int pthread_condattr_init(pthread_condattr_t *attr);

/* ADVANCED REALTIME feature in IEEE Std 1003.1, 2004 Edition */
int pthread_condattr_getclock(const pthread_condattr_t *attr,
                              clockid_t                *clock_id);
int pthread_condattr_setclock(pthread_condattr_t *attr,
                              clockid_t           clock_id);

int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t        *cond,
                           pthread_mutex_t       *mutex,
                           const struct timespec *abstime);

/* pthread rwlock interface */
int pthread_rwlockattr_init (pthread_rwlockattr_t *attr);
int pthread_rwlockattr_destroy (pthread_rwlockattr_t *attr);
int pthread_rwlockattr_getpshared (const pthread_rwlockattr_t *attr, int *pshared);
int pthread_rwlockattr_setpshared (pthread_rwlockattr_t *attr, int pshared);

int pthread_rwlock_init (pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr);
int pthread_rwlock_destroy (pthread_rwlock_t *rwlock);

int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock (pthread_rwlock_t *rwlock);

int pthread_rwlock_timedrdlock (pthread_rwlock_t *rwlock, const struct timespec *abstime);
int pthread_rwlock_timedwrlock (pthread_rwlock_t *rwlock, const struct timespec *abstime);

int pthread_rwlock_unlock (pthread_rwlock_t *rwlock);

int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock);

/* pthread spinlock interface */
int pthread_spin_init (pthread_spinlock_t *lock, int pshared);
int pthread_spin_destroy (pthread_spinlock_t *lock);

int pthread_spin_lock (pthread_spinlock_t * lock);
int pthread_spin_trylock (pthread_spinlock_t * lock);
int pthread_spin_unlock (pthread_spinlock_t * lock);

/* pthread barrier interface */
int pthread_barrierattr_destroy(pthread_barrierattr_t *attr);
int pthread_barrierattr_init(pthread_barrierattr_t *attr);
int pthread_barrierattr_getpshared(const pthread_barrierattr_t *attr, int *pshared);
int pthread_barrierattr_setpshared(pthread_barrierattr_t *attr, int pshared);

int pthread_barrier_destroy(pthread_barrier_t *barrier);
int pthread_barrier_init(pthread_barrier_t           *barrier,
                         const pthread_barrierattr_t *attr,
                         unsigned                     count);

int pthread_barrier_wait(pthread_barrier_t *barrier);

/*  Signal Generation and Delivery, P1003.1b-1993, p. 63
    NOTE: P1003.1c/D10, p. 34 adds sigev_notify_function and
          sigev_notify_attributes to the sigevent structure.  */
union sigval
{
    int    sival_int;    /* Integer signal value */
    void  *sival_ptr;    /* Pointer signal value */
};

struct sigevent
{
    int              sigev_notify;               /* Notification type */
    int              sigev_signo;                /* Signal number */
    union sigval     sigev_value;                /* Signal value */
    void           (*sigev_notify_function)( union sigval );
                                               /* Notification function */
    pthread_attr_t  *sigev_notify_attributes;    /* Notification Attributes */
};

/* posix clock and timer */
#define MILLISECOND_PER_SECOND  1000UL
#define MICROSECOND_PER_SECOND  1000000UL
#define NANOSECOND_PER_SECOND   1000000000UL

#define MILLISECOND_PER_TICK    (MILLISECOND_PER_SECOND / RT_TICK_PER_SECOND)
#define MICROSECOND_PER_TICK    (MICROSECOND_PER_SECOND / RT_TICK_PER_SECOND)
#define NANOSECOND_PER_TICK     (NANOSECOND_PER_SECOND  / RT_TICK_PER_SECOND)

#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME      0
#endif

int clock_getres  (clockid_t clockid, struct timespec *res);
int clock_gettime (clockid_t clockid, struct timespec *tp);
int clock_settime (clockid_t clockid, const struct timespec *tp);

#endif


text:
layout: post
date: 2016-07-31
title: "Jovani Sweetheart Blue Dress JVN33715 Sleeveless Sweep/Brush Train Mermaid/Trumpet"
category: Jovani
tags: [Jovani ,Jovani,Mermaid/Trumpet,Sweetheart,Sweep/Brush Train,Sleeveless]
---
### Jovani Sweetheart Blue Dress JVN33715
Just **$452.98**
###   Sleeveless Sweep/Brush Train Mermaid/Trumpet

BRANDS	Jovani

Silhouette	Mermaid/Trumpet

Neckline	Sweetheart

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/jovani-/38356-jovani-sweetheart-blue-dress-jvn33715.html](https://www.readybrides.com/en/jovani-/38356-jovani-sweetheart-blue-dress-jvn33715.html)


text:
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
    android:contentAuthority="@string/content_authority"
    android:accountType="@string/account_type"
    android:userVisible="false"
    android:supportsUploading="false"
    android:allowParallelSyncs="false"
    android:isAlwaysSyncable="true" />


text:
[void]$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Open file in explorer",{
    Use-OpenFileInExplorer
},"Ctrl+e")


text:
alias tls='tmux list-sessions'
alias tns='TERM=screen-256color-bce tmux -2 new -s'
alias tat='tmux attach -d -t'

# ruby-devenv through tmuxinator
alias rdev='tmuxinator ruby-devenv'


text:
package metric

import (
	"context"
	"flag"
	"fmt"
	"strconv"

	"github.com/vmware/govmomi/govc/flags"
	"github.com/vmware/govmomi/performance"
)

type PerformanceFlag struct {
	*flags.DatacenterFlag
	*flags.OutputFlag

	m *performance.Manager

	interval string
}

func NewPerformanceFlag(ctx context.Context) (*PerformanceFlag, context.Context) {
	f := &PerformanceFlag{}
	f.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
	f.OutputFlag, ctx = flags.NewOutputFlag(ctx)
	return f, ctx
}

func (f *PerformanceFlag) Register(ctx context.Context, fs *flag.FlagSet) {
	f.DatacenterFlag.Register(ctx, fs)
	f.OutputFlag.Register(ctx, fs)

	fs.StringVar(&f.interval, "i", "real", "Interval ID (real|day|week|month|year)")
}

func (f *PerformanceFlag) Process(ctx context.Context) error {
	if err := f.DatacenterFlag.Process(ctx); err != nil {
		return err
	}
	if err := f.OutputFlag.Process(ctx); err != nil {
		return err
	}

	return nil
}

func (f *PerformanceFlag) Manager(ctx context.Context) (*performance.Manager, error) {
	if f.m != nil {
		return f.m, nil
	}

	c, err := f.Client()
	if err != nil {
		return nil, err
	}

	f.m = performance.NewManager(c)

	f.m.Sort = true

	return f.m, err
}

func (f *PerformanceFlag) Interval(val int32) int32 {
	var interval int32

	if f.interval != "" {
		if i, ok := performance.Intervals[f.interval]; ok {
			interval = i
		} else {
			n, err := strconv.ParseUint(f.interval, 10, 32)
			if err != nil {
				panic(err)
			}
			interval = int32(n)
		}
	}

	if interval == 0 {
		if val == -1 {
			// realtime not supported
			return 300
		}

		return val
	}

	return interval
}

func (f *PerformanceFlag) ErrNotFound(name string) error {
	return fmt.Errorf("counter %q not found", name)
}