text:
#include "stdafx.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#if _WIN32
#include <process.h>
#include "../libbiokanga/commhdrs.h"
#else
#include <sys/mman.h>
#include <pthread.h>
#include "../libbiokanga/commhdrs.h"
#endif

#include "./biokanga.h"
#include "LocKMers.h"

CLocKMers::CLocKMers(void)
{
m_pSfxArray = NULL;
m_pBlockSeqBuff = NULL;
m_pMarkerBuff = NULL;
m_pMarkerLenDist = NULL;
m_hOutFile = -1;
m_hOutReadsFile = -1;
#ifdef _WIN32
InitializeSRWLock(&m_hRwLock);
#else
pthread_rwlock_init( &m_hRwLock,NULL);
#endif
Reset();
}

CLocKMers::~CLocKMers(void)
{
if(m_hOutFile != -1)
	close(m_hOutFile);
if(m_hOutReadsFile != -1)
	close(m_hOutReadsFile);
if(m_pSfxArray != NULL)
	delete m_pSfxArray;
if(m_pBlockSeqBuff != NULL)
	delete m_pBlockSeqBuff;
if(m_pMarkerBuff != NULL)
	delete m_pMarkerBuff;
if(m_pMarkerLenDist != NULL)
	delete m_pMarkerLenDist;

#ifndef _WIN32
pthread_rwlock_destroy(&m_hRwLock);
#endif
}

void
CLocKMers::Reset(bool bSync)
{
if(m_pSfxArray != NULL)
	{
	delete m_pSfxArray;
	m_pSfxArray = NULL;
	}
if(m_pBlockSeqBuff != NULL)
	{
	delete m_pBlockSeqBuff;
	m_pBlockSeqBuff = NULL;
	}

if(m_hOutFile != -1)
	{
	if(bSync)
#ifdef _WIN32
		_commit(m_hOutFile);
#else
		fsync(m_hOutFile);
#endif
	close(m_hOutFile);
	m_hOutFile = -1;
	}

if(m_hOutReadsFile != -1)
	{
	if(bSync)
#ifdef _WIN32
		_commit(m_hOutReadsFile);
#else
		fsync(m_hOutReadsFile);
#endif
	close(m_hOutReadsFile);
	m_hOutReadsFile = -1;
	}

if(m_pMarkerBuff != NULL)
	{
	delete m_pMarkerBuff;
	m_pMarkerBuff = NULL;
	}

if(m_pMarkerLenDist != NULL)
	{
	delete m_pMarkerLenDist;
	m_pMarkerLenDist = NULL;
	}

m_szDataset[0] = '\0';
m_szMarkerFile[0] = '\0';
m_szMarkerReadsFile[0] = '\0';
m_bKMerReads = false;
m_NumSfxEntries = 0;
m_NxtBlockSeqBuffOfs = 0;
m_BlockSeqBuffLen = 0;
m_AllocBlockSeqBuffSize = 0;
m_bInitSeqBuffering = true;
m_CurPartialCultivarID = 0;
m_CurPartialCultivarOfs = 0;
m_bAllEntrySeqsLoaded = false;
m_bAllBlocksReturned = false;
m_NumBlocks = 0;
m_NumKMers = 0;
m_NumPutativeKMers = 0;
m_NumAcceptedKMers = 0;
m_NumAcceptedExtdKMers = 0;
m_MarkerID = 0;
m_MarkerBuffOfs = 0;
m_AllocMarkerBuffSize = 0;
m_MaxMarkerLen = 0;
m_MinMarkerLen = 0;
m_szTargetCultivar[0] = '\0';
m_NumPartialCultivars = 0;
memset(m_PartialCultivars,0,sizeof(m_PartialCultivars));
}

// AcquireLock
// Aquire lock, either exclusive or read only, on class shared instance vars
void
CLocKMers::AcquireLock(bool bExclusive)
{
#ifdef _WIN32
if(bExclusive)
	AcquireSRWLockExclusive(&m_hRwLock);
else
	AcquireSRWLockShared(&m_hRwLock);
#else
if(bExclusive)
	pthread_rwlock_wrlock(&m_hRwLock);
else
	pthread_rwlock_rdlock(&m_hRwLock);
#endif
}

// ReleaseLock
// Release lock, must be exclusive or read only as used when AcquireLock was used
void
CLocKMers::ReleaseLock(bool bExclusive)
{
#ifdef _WIN32
if(bExclusive)
	ReleaseSRWLockExclusive(&m_hRwLock);
else
	ReleaseSRWLockShared(&m_hRwLock);
#else
pthread_rwlock_unlock(&m_hRwLock);
#endif
}

int
CLocKMers::ReportMarker(int MarkerLen,			// number of bases in marker sequence
			 etSeqBase *pMarkerSeq)				// marker sequence
{
int TruncMarkerLen;
char szMarkerSeq[cMaxExtKMerLen+1];				// additional for '\0' terminator

if(m_hOutFile == -1 || MarkerLen == 0 || pMarkerSeq == NULL || m_pMarkerBuff == NULL)	// better safe than sorry...
	return(0);

TruncMarkerLen = MarkerLen > cMaxExtKMerLen ? cMaxExtKMerLen : MarkerLen;
CSeqTrans::MapSeq2UCAscii(pMarkerSeq,TruncMarkerLen,szMarkerSeq);
AcquireLock(true);
if((m_MarkerBuffOfs + (2 * cMaxExtKMerLen)) > m_AllocMarkerBuffSize)
	{
	CUtility::SafeWrite(m_hOutFile,m_pMarkerBuff,m_MarkerBuffOfs);
	m_MarkerBuffOfs = 0;
	}
m_MarkerID += 1;
if(MarkerLen != TruncMarkerLen)					// if needed to clamp
	{
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"ReportMarker: Truncated overlength (%d) Marker%d down to length %d",MarkerLen,m_MarkerID,cMaxExtKMerLen);
	MarkerLen = cMaxExtKMerLen;
	}
m_MarkerBuffOfs += sprintf((char *)&m_pMarkerBuff[m_MarkerBuffOfs],">%sM%d %d|%d|%d\n%s\n",m_szTargetCultivar,m_MarkerID,TruncMarkerLen,m_KMerLen,m_MinHamming,szMarkerSeq);
m_pMarkerLenDist[TruncMarkerLen-1] += 1;
if(m_MaxMarkerLen < TruncMarkerLen)
	m_MaxMarkerLen = TruncMarkerLen;
if(m_MinMarkerLen == 0 || m_MinMarkerLen > TruncMarkerLen)
	m_MinMarkerLen = TruncMarkerLen;
ReleaseLock(true);
return(eBSFSuccess);
}

int
CLocKMers::ReportMarkerRead(int ReadLen,		// number of bases in read sequence
			 etSeqBase *pReadSeq)				// read sequence
{
int TruncMarkerLen;
char szMarkerSeq[cMaxExtKMerLen+1];				// additional for '\0' terminator

if(m_hOutReadsFile == -1 || ReadLen == 0 || pReadSeq == NULL || m_pMarkerBuff == NULL)	// better safe than sorry...
	return(0);

TruncMarkerLen = ReadLen > cMaxExtKMerLen ? cMaxExtKMerLen : ReadLen;
CSeqTrans::MapSeq2UCAscii(pReadSeq,TruncMarkerLen,szMarkerSeq);
AcquireLock(true);
if((m_MarkerBuffOfs + (2 * cMaxExtKMerLen)) > m_AllocMarkerBuffSize)
	{
	CUtility::SafeWrite(m_hOutReadsFile,m_pMarkerBuff,m_MarkerBuffOfs);
	m_MarkerBuffOfs = 0;
	}
m_MarkerID += 1;
if(ReadLen != TruncMarkerLen)					// if needed to clamp
	{
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"ReportMarkerRead: Truncated overlength (%d) Marker%d down to length %d",ReadLen,m_MarkerID,cMaxExtKMerLen);
	ReadLen = cMaxExtKMerLen;
	}
m_MarkerBuffOfs += sprintf((char *)&m_pMarkerBuff[m_MarkerBuffOfs],">%sS%d %d|%d|%d\n%s\n",m_szTargetCultivar,m_MarkerID,TruncMarkerLen,m_KMerLen,m_MinHamming,szMarkerSeq);
m_pMarkerLenDist[TruncMarkerLen-1] += 1;
if(m_MaxMarkerLen < TruncMarkerLen)
	m_MaxMarkerLen = TruncMarkerLen;
if(m_MinMarkerLen == 0 || m_MinMarkerLen > TruncMarkerLen)
	m_MinMarkerLen = TruncMarkerLen;
ReleaseLock(true);
return(eBSFSuccess);
}

int												// number of bases still unprocessed for K-mers in sequence buffer
CLocKMers::FillBlockSeqBuff(void)				// maximally fill sequence buffer
{
int CntNs;
int Idx;
int SeqLen;
int BlockSeqLen;
int NumUnprocessed;
tsPartialCultivar *pPartialCultivar;
UINT8 *pDstBase;
UINT8 *pSrcBase;

// only bother filling if sequence buffer getting lower than 3 * cBlockReqSize bases
if(!m_bAllEntrySeqsLoaded && (m_CurPartialCultivarID == 0 || m_CurPartialCultivarID > m_NumPartialCultivars))
	return(eBSFerrInternal);

NumUnprocessed = (int)m_BlockSeqBuffLen - (int)m_NxtBlockSeqBuffOfs;
if(m_bAllEntrySeqsLoaded || NumUnprocessed >= (3 * cBlockReqSize))
	return(NumUnprocessed);

if(m_NxtBlockSeqBuffOfs > 0)
	{
	memmove(m_pBlockSeqBuff,&m_pBlockSeqBuff[m_NxtBlockSeqBuffOfs],NumUnprocessed);
	m_NxtBlockSeqBuffOfs = 0;
	}
m_BlockSeqBuffLen = NumUnprocessed;

	// try to maximally fill buffer
pPartialCultivar = &m_PartialCultivars[m_CurPartialCultivarID - 1];
if(m_CurPartialCultivarOfs >= pPartialCultivar->EntryLen)		// ensure haven't already completed buffering sequences from this partial cultivar...
	{
	m_CurPartialCultivarOfs = 0;
	if(m_CurPartialCultivarID == m_NumPartialCultivars)			// no more partial cultivars to load sequences from?
		{
		m_CurPartialCultivarID = 0;
		m_bAllEntrySeqsLoaded = true;
		return(m_BlockSeqBuffLen);
		}
	m_CurPartialCultivarID += 1;								// try next partial cultivar
	m_pBlockSeqBuff[m_NxtBlockSeqBuffOfs++] = eBaseEOS;			// ensure current buffered sequence is terminated
	}

do {
	pPartialCultivar = &m_PartialCultivars[m_CurPartialCultivarID - 1];
	SeqLen = m_pSfxArray->GetSeq(pPartialCultivar->EntryID,m_CurPartialCultivarOfs,&m_pBlockSeqBuff[m_BlockSeqBuffLen],(m_AllocBlockSeqBuffSize - 10) - m_BlockSeqBuffLen);
	if(SeqLen > 0)			// loaded any sequence?
		{
		m_CurPartialCultivarOfs += (UINT32)SeqLen;
		m_BlockSeqBuffLen += (UINT32)SeqLen;
		if(m_CurPartialCultivarOfs >= pPartialCultivar->EntryLen)		// need to next load from another partial cultivar?
			{
			m_pBlockSeqBuff[m_BlockSeqBuffLen++] = eBaseEOS;			// ensure current buffered sequence is terminated
			m_CurPartialCultivarOfs = 0;
			if(m_CurPartialCultivarID == m_NumPartialCultivars)			// no more partial cultivars to load sequences from?
				{
				m_CurPartialCultivarID = 0;
				m_bAllEntrySeqsLoaded = true;
				}
			else
				m_CurPartialCultivarID += 1;								// try next partial cultivar
			}
		}
	else
		return(eBSFerrInternal);
	}
while(!m_bAllEntrySeqsLoaded && m_BlockSeqBuffLen < (m_AllocBlockSeqBuffSize - 10));

// any run of Ns or eBaseEOS's are assumed to be inter-sequence markers and are to be replaced by a single eBaseEOS
pDstBase = pSrcBase = m_pBlockSeqBuff;
BlockSeqLen = 0;
for(CntNs = 0, Idx = 0; Idx < (int)m_BlockSeqBuffLen; Idx++,pSrcBase++)
	{
	if(*pSrcBase == eBaseN || *pSrcBase == eBaseEOS)
		{
		CntNs += 1;
		continue;
		}
	if(CntNs > 0)
		{
		*pDstBase++ = eBaseEOS;
		BlockSeqLen += 1;
		CntNs = 0;
		}
	*pDstBase++ = *pSrcBase;
	BlockSeqLen += 1;
	}
if(CntNs)
	{
	*pDstBase++ = eBaseEOS;
	BlockSeqLen += 1;
	}

m_BlockSeqBuffLen = BlockSeqLen;
m_pBlockSeqBuff[m_BlockSeqBuffLen] = eBaseEOG;
m_NxtBlockSeqBuffOfs = 0;
return(m_BlockSeqBuffLen);
}

static UINT32 m_NumRetBlocks = 0;

int										    // returned block of concatenated sequences total length
CLocKMers::GetBlockSeqs(int MaxLength,		//  maximum total block length to return
						UINT8 *pBlockSeqs)	// copy block of sequences into this buffer
{
int MaxAvailBlockSize;
UINT8 *pSrcBase;
UINT8 *pDstBase;
UINT8 CurBase;
int CurRetLen;
int EOSRetLen;

if(m_pBlockSeqBuff == NULL || m_NumPartialCultivars == 0 || m_NumSfxEntries == 0)
	return(eBSFerrInternal);

AcquireLock(true);
if(m_bInitSeqBuffering)						// just starting and buffering requires initialisation?
	{
	m_NumRetBlocks = 0;
	m_NxtBlockSeqBuffOfs = 0;
	m_BlockSeqBuffLen = 0;
	m_bAllEntrySeqsLoaded = false;
	m_bAllBlocksReturned = false;
	m_CurPartialCultivarID = 1;		// start with this partial cultivar
	m_CurPartialCultivarOfs = 0;
	FillBlockSeqBuff();
	m_bInitSeqBuffering = false;
	if(!m_BlockSeqBuffLen)						// should alway be able to load initial sequences...
		{
		m_CurPartialCultivarOfs = 0;
		m_NxtBlockSeqBuffOfs = 0;
		m_BlockSeqBuffLen = 0;
		m_bAllEntrySeqsLoaded = true;
		m_bAllBlocksReturned = true;
		ReleaseLock(true);
		return(0);
		}
	}
else
	{
	if(m_bAllBlocksReturned || (m_bAllEntrySeqsLoaded && m_NxtBlockSeqBuffOfs >= m_BlockSeqBuffLen))	// have all partial cultivar chrom sequence blocks been returned for processing?
		{
		m_NxtBlockSeqBuffOfs = 0;
		m_BlockSeqBuffLen = 0;
		m_bInitSeqBuffering = false;
		m_bAllEntrySeqsLoaded = true;
		m_bAllBlocksReturned = true;
		ReleaseLock(true);
		return(0);
		}
	}

// determine the maximum potential size of block which could be returned
if(m_NxtBlockSeqBuffOfs < m_BlockSeqBuffLen)
	MaxAvailBlockSize = m_BlockSeqBuffLen - m_NxtBlockSeqBuffOfs;
else
	MaxAvailBlockSize = 0;

// is buffer getting low, if so then try to top up
if(!m_bAllEntrySeqsLoaded && MaxAvailBlockSize < (2 * MaxLength))
	{
	FillBlockSeqBuff();
	if(m_BlockSeqBuffLen == 0)					// sequence buffer still empty even after trying to top it up?
		{
		m_CurPartialCultivarOfs = 0;
		m_NxtBlockSeqBuffOfs = 0;
		m_BlockSeqBuffLen = 0;
		m_bAllEntrySeqsLoaded = true;
		m_bAllBlocksReturned = true;
		ReleaseLock(true);
		return(0);
		}
	}

// ensure returned blocks must contain complete rather than partial sequences
pSrcBase = &m_pBlockSeqBuff[m_NxtBlockSeqBuffOfs];
// slough any initial eBaseEOS's
while(m_NxtBlockSeqBuffOfs < m_BlockSeqBuffLen && (CurBase = *pSrcBase) == eBaseEOS)
	{
	pSrcBase += 1;
	m_NxtBlockSeqBuffOfs += 1;
	}

// check if removing initial eBaseEOS's has emptied buffer
if(*pSrcBase == eBaseEOG || m_NxtBlockSeqBuffOfs == m_BlockSeqBuffLen)
	{
	m_CurPartialCultivarOfs = 0;
	m_NxtBlockSeqBuffOfs = 0;
	m_BlockSeqBuffLen = 0;
	m_bAllEntrySeqsLoaded = true;
	m_bAllBlocksReturned = true;
	ReleaseLock(true);
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"GetBlockSeqs: At block %d, removing eBaseEOSs emptied buffer",m_NumRetBlocks);
	return(0);
	}

// buffer not empty return upto MaxLength bases ensuring last returned sequence is not a partial sequence
pDstBase = pBlockSeqs;
CurRetLen = 0;
EOSRetLen = 0;
while((CurBase = *pSrcBase++) != eBaseEOG)
	{
	CurRetLen += 1;
	*pDstBase++ = CurBase;
	if(CurBase == eBaseEOS)
		EOSRetLen = CurRetLen;
	if(CurRetLen == MaxLength)
		break;
	}

m_NxtBlockSeqBuffOfs += EOSRetLen;
if(EOSRetLen == 0)
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"GetBlockSeqs: At block %d, EOSRetLen:0 CurRetLen:%d MaxLength: %d",m_NumRetBlocks,CurRetLen,MaxLength);
else
	m_NumRetBlocks += 1;
ReleaseLock(true);
return(EOSRetLen);
}

bool	// returns true if suffix array entry identifier is for a pseudo-chromosome which is part of the target cultivar
CLocKMers::IsTargetCultivar(int EntryID)		// suffix array entry identifier
{
return(LocTargetCultivar(EntryID) == NULL ? false : true);
}

tsPartialCultivar *				// NULL if EntryID not a targeted cultivar
CLocKMers::LocTargetCultivar(int EntryID)	// suffix array entry identifier
{
int Idx;
tsPartialCultivar *pPartialCultivar;
pPartialCultivar = m_PartialCultivars;
for(Idx = 0; Idx < m_NumPartialCultivars; Idx++, pPartialCultivar++)
	if(pPartialCultivar->EntryID == EntryID)
		return(pPartialCultivar);
return(NULL);
}

UINT32												// returns number of accepted cultivar specific extended K-mers
CLocKMers::GetKMerProcProgress(UINT32 *pNumBlocks,	// number of blocks processed
					INT64 *pNumKMers,				// these blocks contain this number of K-mers
					UINT32 *pNumPutativeKMers,		// putatively - before check for Hamming - there are this number of unique K-mers mapping to target cultivar
					UINT32 *pNumAcceptedKMers)		// after Hamming check this number of K-mers have been accepted
{
UINT32 NumAcceptedExtdKMers;
AcquireLock(true);
if(pNumBlocks != NULL)
	*pNumBlocks = m_NumBlocks;
if(pNumKMers != NULL)
	*pNumKMers = m_NumKMers;
if(pNumPutativeKMers != NULL)
	*pNumPutativeKMers = m_NumPutativeKMers;
if(pNumAcceptedKMers != NULL)
	*pNumAcceptedKMers = m_NumAcceptedKMers;
NumAcceptedExtdKMers = m_NumAcceptedExtdKMers;
ReleaseLock(true);
return(NumAcceptedExtdKMers);
}

int
CLocKMers::MarkersCallback(void *pThis,UINT32 EntryID,etSeqBase *pSeq)
{

return(0);
}

int
CLocKMers::LocKMers(etPMode PMode,				// processing mode - defaults to 0
		  int KMerLen,					// this length K-mers
	  	  int PrefixLen,				// inter-cultivar shared prefix length
		  int SuffixLen,				// cultivar specific suffix length
		  int MinWithPrefix,			// minimum number of cultivars required to have the shared prefix
		  int MinHamming,				// must be at least this Hamming away from any other K-mer in other cultivars
		  char *pszCultivarName,		// targeted cultivar name for which K-mer markers are required
		  int NumPartialCultivars,		// there are this many pseudo chromosomes for targeted cultivar for which K-mer markers are required
		  char *ppszPartialCultivars[],	// pseudo chromosome names which identify targeted cultivar
		  char *pszSfxPseudoGenome,		// contains pregenerated suffix over psuedochromosomes for each cultivar
		  char *pszMarkerFile,			// output potential markers to this file
		  char *pszMarkerReadsFile,		// optionally output reads containing potential markers to this file
		  int NumThreads)				// max number of threads allowed
{
int Rslt;
int Idx;
UINT32 NumBlocks;
INT64 NumKMers;
UINT32 NumPutativeKMers;
UINT32 NumAcceptedKMers;
UINT32 NumAcceptedExtdKMers;
tsPartialCultivar *pPartialCultivar;

Reset();

m_PMode = PMode;
m_KMerLen = KMerLen;
m_PrefixLen = PrefixLen;
m_SuffixLen = SuffixLen;
m_MinWithPrefix = MinWithPrefix;

m_MinHamming = MinHamming;
m_NumThreads = NumThreads;
strncpy(m_szMarkerFile,pszMarkerFile,sizeof(m_szMarkerFile));
m_szMarkerFile[sizeof(m_szMarkerFile)-1] = '\0';
if(pszMarkerReadsFile != NULL && pszMarkerReadsFile[0] != '\0')
	{
	m_bKMerReads = true;
	strncpy(m_szMarkerReadsFile,pszMarkerReadsFile,sizeof(m_szMarkerReadsFile));
	m_szMarkerReadsFile[sizeof(m_szMarkerReadsFile)-1] = '\0';
	}
else
	{
	m_bKMerReads = false;
	m_szMarkerReadsFile[0] = '\0';
	}
strncpy(m_szTargetCultivar,pszCultivarName,sizeof(m_szTargetCultivar));
m_szTargetCultivar[sizeof(m_szTargetCultivar)-1] = '\0';
m_NumPartialCultivars = NumPartialCultivars;
pPartialCultivar = m_PartialCultivars;
for(Idx = 0; Idx < NumPartialCultivars; Idx++,pPartialCultivar++)
	{
	pPartialCultivar->PartialCultivarID = 0;
	pPartialCultivar->EntryID = 0;
	pPartialCultivar->EntryLen = 0;
	strncpy(pPartialCultivar->szEntryName,ppszPartialCultivars[Idx],sizeof(pPartialCultivar->szEntryName));
	pPartialCultivar->szEntryName[sizeof(pPartialCultivar->szEntryName)-1] = '\0';
	}

// sort so can check for duplicate cultivar pseudo-chromosome
if(NumPartialCultivars > 1)
	{
	qsort(m_PartialCultivars,NumPartialCultivars,sizeof(tsPartialCultivar),sortpartcultnames);
	pPartialCultivar = m_PartialCultivars;
	for(Idx = 0; Idx < NumPartialCultivars-1; Idx++,pPartialCultivar++)
		if(!stricmp(pPartialCultivar->szEntryName,pPartialCultivar[1].szEntryName))
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Duplicate partial cultivar pseudo-chromosome name : '%s'",pPartialCultivar->szEntryName);
			return(eBSFerrParams);
			}
	}

// allocate buffers
if((m_pMarkerBuff = new UINT8 [cMarkerSeqBuffSize])==NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Unable to allocate (%d bytes) for marker buffering",cMarkerSeqBuffSize);
	Reset();
	return(eBSFerrMem);
	}
m_AllocMarkerBuffSize = cMarkerSeqBuffSize;

if((m_pMarkerLenDist = new UINT32 [cMaxExtKMerLen])==NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Unable to allocate (%d bytes) for marker length distributions",sizeof(UINT32) * cMaxExtKMerLen);
	Reset();
	return(eBSFerrMem);
	}

if((m_pBlockSeqBuff = new UINT8 [cConcatSeqBuffSize])==NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Unable to allocate (%d bytes) for sequence buffering",cConcatSeqBuffSize);
	Reset();
	return(eBSFerrMem);
	}
m_AllocBlockSeqBuffSize = cConcatSeqBuffSize;

if((m_pSfxArray = new CSfxArrayV3)==NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Unable to instantiate instance of CSfxArrayV3");
	Reset();
	return(eBSFerrObj);
	}

if((Rslt = m_pSfxArray->Open(pszSfxPseudoGenome))!=eBSFSuccess)
	{
	while(m_pSfxArray->NumErrMsgs())
		gDiagnostics.DiagOut(eDLFatal,gszProcName,m_pSfxArray->GetErrMsg());
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open input bioseq suffix array file '%s'",pszSfxPseudoGenome);
	Reset();
	return(Rslt);
	}

// report to user some sfx array metadata for user conformation the targeted assembly is correct
strcpy(m_szDataset,m_pSfxArray->GetDatasetName());
if(m_pSfxArray->IsSOLiD())
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to process SOLiD colorspace suffix array file '%s'",pszSfxPseudoGenome);
	Reset();
	return(eBSFerrRefDataset);
	}
tsSfxHeaderV3 SfxHeader;
m_pSfxArray->GetSfxHeader(&SfxHeader);
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Psuedo-assembly Name: '%s' Descr: '%s' Title: '%s' Version: %d",
					 m_szDataset,SfxHeader.szDescription,SfxHeader.szTitle,SfxHeader.Version);
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Assembly has blocks: %d, max block size: %llu",SfxHeader.NumSfxBlocks,SfxHeader.SfxBlockSize);

// ensure assembly and suffix array has been fully loaded into memory
int CurBlockID = 1;		// currently only single block supported
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Loading genome assembly suffix array...");
if((Rslt=m_pSfxArray->SetTargBlock(CurBlockID))<0)
	{
	while(m_pSfxArray->NumErrMsgs())
		gDiagnostics.DiagOut(eDLFatal,gszProcName,m_pSfxArray->GetErrMsg());
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Fatal: unable to load assembly suffix array");
	return(Rslt);
	}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Assembly suffix array loaded");

// ensure that all the targeted pseudo-chromosomes are in the suffix array, and that there are other chromosomes (other species) in addition to those targeted
// at same time the pseudo-chromosome ID's and lengths are retreived
m_NumSfxEntries = m_pSfxArray->GetNumEntries();
if(m_NumSfxEntries < 1)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"No entries in '%s'",pszSfxPseudoGenome);
	Reset();
	return(eBSFerrEntry);
	}
if(m_NumSfxEntries <= m_NumPartialCultivars)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Only %d entries in '%s', expected additional ( > %d) to targeted cultivar partial pseudo-chromosomes ",m_NumSfxEntries,pszSfxPseudoGenome,m_NumPartialCultivars);
	Reset();
	return(eBSFerrEntry);
	}
pPartialCultivar = m_PartialCultivars;
for(Idx = 0; Idx < NumPartialCultivars; Idx++,pPartialCultivar++)
	{
	if((pPartialCultivar->EntryID = m_pSfxArray->GetIdent(pPartialCultivar->szEntryName)) < 1)
		{
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Unable to locate '%s' in '%s'",pPartialCultivar->szEntryName,pszSfxPseudoGenome);
		Reset();
		return(eBSFerrEntry);
		}
	pPartialCultivar->PartialCultivarID = Idx+1;
	m_CultChromIDs[Idx] = pPartialCultivar->EntryID;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Located target cultivar pseudo-chrom '%s' in '%s'",pPartialCultivar->szEntryName,pszSfxPseudoGenome);
	pPartialCultivar->EntryLen = m_pSfxArray->GetSeqLen(pPartialCultivar->EntryID);
	}

// now report the non-targeted chrom names whilst populating m_AllCultivars[]
int EntryID;
char szSfxEntryName[100];
tsCultivar *pCultivar;
tsPartialCultivar *pPartial;
pCultivar = m_AllCultivars;

for(EntryID = 1; EntryID <= m_NumSfxEntries; EntryID++, pCultivar++)
	{
	pCultivar->Status = 0;
	m_pSfxArray->GetIdentName(EntryID,sizeof(szSfxEntryName),szSfxEntryName);
	pCultivar->Cultivar.EntryID = EntryID;
	strncpy(pCultivar->Cultivar.szEntryName,szSfxEntryName,sizeof(pCultivar->Cultivar.szEntryName));
	pCultivar->Cultivar.szEntryName[sizeof(pCultivar->Cultivar.szEntryName)-1] = '\0';
	pCultivar->Cultivar.EntryLen = m_pSfxArray->GetSeqLen(EntryID);
	if((pPartial = LocTargetCultivar(EntryID))!=NULL)
		{
		pCultivar->Cultivar.PartialCultivarID = pPartial->PartialCultivarID;
		continue;
		}
	pCultivar->Cultivar.PartialCultivarID = 0;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"   Processing K-mers against non-target pseudo-chromosome '%s'",szSfxEntryName);
	}

if(PMode == ePMPrefixKMers && (m_MinWithPrefix == 0 || m_MinWithPrefix > (m_NumSfxEntries - NumPartialCultivars)))
	m_MinWithPrefix = m_NumSfxEntries - NumPartialCultivars;

// looks good to go so create/truncate output marker sequence file
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Truncating/Creating output multi-fasta marker file '%s'",m_szMarkerFile);
#ifdef _WIN32
m_hOutFile = open(m_szMarkerFile,O_CREATETRUNC );
#else
if((m_hOutFile = open(m_szMarkerFile,O_RDWR | O_CREAT,S_IREAD | S_IWRITE))!=-1)
    if(ftruncate(m_hOutFile,0)!=0)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to truncate %s - %s",m_szMarkerFile,strerror(errno));
			Reset();
			return(eBSFerrCreateFile);
			}
#endif

if(m_hOutFile < 0)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Process: unable to create/truncate output file '%s'",m_szMarkerFile);
	m_hOutFile = -1;
	Reset();
	return(eBSFerrCreateFile);
	}

// user also wanting K-mer marker containing reads to be reported?
if(m_bKMerReads)
	{
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Truncating/Creating output marker containing multi-fasta reads file '%s'",m_szMarkerReadsFile);
	#ifdef _WIN32
	m_hOutReadsFile = open(m_szMarkerReadsFile,O_CREATETRUNC );
	#else
	if((m_hOutReadsFile = open(m_szMarkerReadsFile,O_RDWR | O_CREAT,S_IREAD | S_IWRITE))!=-1)
		if(ftruncate(m_hOutReadsFile,0)!=0)
				{
				gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to truncate %s - %s",m_szMarkerReadsFile,strerror(errno));
				Reset();
				return(eBSFerrCreateFile);
				}
	#endif

	if(m_hOutReadsFile < 0)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Process: unable to create/truncate output marker containing multi-fasta reads file '%s'",m_szMarkerReadsFile);
		m_hOutReadsFile = -1;
		Reset();
		return(eBSFerrCreateFile);
		}
	}

memset(m_pMarkerLenDist,0,sizeof(UINT32) * cMaxExtKMerLen);
m_bInitSeqBuffering = true;

// TIME TO PLAY!!!!
#ifdef TRYCULTIVARMARKERS
UINT32 EntryIDs[50];
int EntryIDIdx;
pCultivar = m_AllCultivars;
for(EntryIDIdx = 0; EntryIDIdx < m_NumSfxEntries; EntryIDIdx++, pCultivar++)
	{
	pCultivar->Status = 0;
	EntryIDs[EntryIDIdx] = pCultivar->Cultivar.EntryID;
	}
m_pSfxArray->LocateMultiCultivarMarkers(30,30,m_NumSfxEntries,EntryIDs,this,MarkersCallback);

// END OF TIME TO PLAY
#endif

tsKMerThreadPars WorkerThreads[cMaxWorkerThreads];			// allow for max possible user configured number of threads
int ThreadIdx;

// initialise and startup K-mer processing worker threads
memset(WorkerThreads,0,sizeof(WorkerThreads));
for(ThreadIdx = 0; ThreadIdx < m_NumThreads; ThreadIdx++)
	{
	WorkerThreads[ThreadIdx].ThreadIdx = ThreadIdx + 1;
	WorkerThreads[ThreadIdx].pThis = this;
	WorkerThreads[ThreadIdx].pBlockSeqs = new UINT8 [cBlockReqSize];
	WorkerThreads[ThreadIdx].AllocBlockSeqsSize = cBlockReqSize;
#ifdef _WIN32
	WorkerThreads[ThreadIdx].threadHandle = (HANDLE)_beginthreadex(NULL,0x0fffff,KMerThreadStart,&WorkerThreads[ThreadIdx],0,&WorkerThreads[ThreadIdx].threadID);
#else
	WorkerThreads[ThreadIdx].threadRslt =	pthread_create (&WorkerThreads[ThreadIdx].threadID , NULL , KMerThreadStart , &WorkerThreads[ThreadIdx] );
#endif
	}

// allow threads a few seconds to startup
#ifdef _WIN32
	Sleep(10000);
#else
	sleep(10);
#endif

// let user know that this K-mer processing process is working hard...
NumAcceptedExtdKMers = GetKMerProcProgress(&NumBlocks,&NumKMers,&NumPutativeKMers, &NumAcceptedKMers);
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Progress - K-Mers processed: %lld, Cultivar specific : %u, Hamming retained: %u, Accepted: %u",NumKMers,NumPutativeKMers, NumAcceptedKMers,NumAcceptedExtdKMers);

// wait for all threads to have completed
for(ThreadIdx = 0; ThreadIdx < m_NumThreads; ThreadIdx++)
	{
#ifdef _WIN32
	while(WAIT_TIMEOUT == WaitForSingleObject( WorkerThreads[ThreadIdx].threadHandle, 60000 * 10))
		{
		NumAcceptedExtdKMers = GetKMerProcProgress(&NumBlocks,&NumKMers,&NumPutativeKMers, &NumAcceptedKMers);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Progress - K-Mers processed: %lld, Cultivar specific : %u, Hamming retained: %u, Accepted: %u",NumKMers,NumPutativeKMers, NumAcceptedKMers,NumAcceptedExtdKMers);
		}
	CloseHandle( WorkerThreads[ThreadIdx].threadHandle);
#else
	struct timespec ts;
	int JoinRlt;
	clock_gettime(CLOCK_REALTIME, &ts);
	ts.tv_sec += 60 * 10;
	while((JoinRlt = pthread_timedjoin_np(WorkerThreads[ThreadIdx].threadID, NULL, &ts)) != 0)
		{
		NumAcceptedExtdKMers = GetKMerProcProgress(&NumBlocks,&NumKMers,&NumPutativeKMers, &NumAcceptedKMers);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Progress - K-Mers processed: %lld, Cultivar specific : %u, Hamming retained: %u, Accepted: %u",NumKMers,NumPutativeKMers, NumAcceptedKMers,NumAcceptedExtdKMers);
		ts.tv_sec += 60;
		}
#endif
	if(WorkerThreads[ThreadIdx].pBlockSeqs!=NULL)
		{
		delete WorkerThreads[ThreadIdx].pBlockSeqs;
		WorkerThreads[ThreadIdx].pBlockSeqs = NULL;
		}
	}

NumAcceptedExtdKMers = GetKMerProcProgress(&NumBlocks,&NumKMers,&NumPutativeKMers, &NumAcceptedKMers);
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Completed - K-Mers processed: %lld, Cultivar specific : %u, Hamming retained: %u, Accepted: %u",NumKMers,NumPutativeKMers, NumAcceptedKMers,NumAcceptedExtdKMers);

if(gProcessingID > 0)
	{
	gSQLiteSummaries.AddResult(gProcessingID,(char *)"Kmers",ePTInt64,sizeof(NumKMers),"Processed",&NumKMers);
	gSQLiteSummaries.AddResult(gProcessingID,(char *)"Kmers",ePTUint32,sizeof(NumPutativeKMers),"Cultivar",&NumPutativeKMers);
	gSQLiteSummaries.AddResult(gProcessingID,(char *)"Kmers",ePTUint32,sizeof(NumAcceptedKMers),"HammingRetained",&NumAcceptedKMers);
	gSQLiteSummaries.AddResult(gProcessingID,(char *)"Kmers",ePTUint32,sizeof(NumAcceptedExtdKMers),"Accepted",&NumAcceptedExtdKMers);
	}

if(m_hOutFile != -1)
	{
	if(m_MarkerBuffOfs)
		CUtility::SafeWrite(m_hOutFile,m_pMarkerBuff,m_MarkerBuffOfs);
#ifdef _WIN32
	_commit(m_hOutFile);
#else
	fsync(m_hOutFile);
#endif
	close(m_hOutFile);
	m_hOutFile = -1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Closed output multi-fasta marker file '%s'",m_szMarkerFile);
	}

gDiagnostics.DiagOut(eDLInfo,gszProcName,"Number of reported markers: %u",m_MarkerID);
if(m_MarkerID)
	{
	// log the marker length distributions
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Marker length distribution");
	if(m_MinMarkerLen)
		for(Idx = m_MinMarkerLen; Idx <= m_MaxMarkerLen; Idx++)
			{
			gDiagnostics.DiagOut(eDLInfo,gszProcName,"Length: %d Count: %u",Idx,m_pMarkerLenDist[Idx-1]);
			if(gProcessingID)
				gSQLiteSummaries.AddResultXY(gProcessingID,(char *)"Markers",ePTInt32,sizeof(Idx),"Length",&Idx,ePTInt32,sizeof(m_pMarkerLenDist[Idx-1]),"Cnt",&m_pMarkerLenDist[Idx-1]);
			}
	else
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Length: %d Count: 0",m_KMerLen);
	}

// user requested marker containing reads also be reported?
if(m_bKMerReads)
	{
	bool bMarkerRead;
	int CultID;
	tsPartialCultivar *pCult;
	UINT8 *pSeq;
	UINT8 *pMarkStart;
	UINT8 SeqBase;
	UINT32 Loci;
	UINT32 ReadLen;

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Writing reads containing markers to '%s'",m_szMarkerReadsFile);
	m_MarkerID = 0;
	m_MarkerBuffOfs = 0;
	m_MinMarkerLen = 0;
	m_MaxMarkerLen = 0;

	memset(m_pMarkerLenDist,0,sizeof(UINT32) * cMaxExtKMerLen);
	pCult = m_PartialCultivars;
	for(CultID = 1; CultID <= m_NumPartialCultivars; CultID++,pCult++)
		{
		bMarkerRead = false;
		ReadLen = 0;
		pSeq = (UINT8 *)m_pSfxArray->GetPtrSeq(pCult->EntryID,0);
		pMarkStart = pSeq;
		for(Loci = 0; Loci < pCult->EntryLen; Loci++)
			{
			SeqBase = *pSeq++;
			if((SeqBase & 0x0f) > eBaseT || Loci == pCult->EntryLen-1)
				{
				if(bMarkerRead)
					{
					// write to file this read which starts at pMarkStart and is of length ReadLen
					ReportMarkerRead(ReadLen,pMarkStart);
					bMarkerRead = false;
					}
				pMarkStart = pSeq;
				ReadLen = 0;
				continue;
				}
			ReadLen += 1;
			if((SeqBase >> 4) & 0x02)	// marked as containing K-mer marker?
				bMarkerRead = true;
			}
		}

	if(m_hOutReadsFile != -1)
		{
		if(m_MarkerBuffOfs)
			CUtility::SafeWrite(m_hOutReadsFile,m_pMarkerBuff,m_MarkerBuffOfs);
#ifdef _WIN32
		_commit(m_hOutReadsFile);
#else
		fsync(m_hOutReadsFile);
#endif
		close(m_hOutReadsFile);
		m_hOutReadsFile = -1;
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Closed output reads containing marker multi-fasta reads file '%s'",m_szMarkerReadsFile);
		}

		// log the marker reads length distributions
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Number of reported reads containing markers: %u",m_MarkerID);
	if(m_MarkerID)
		{
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Marker containing reads length distribution");
		if(m_MinMarkerLen)
			for(Idx = m_MinMarkerLen; Idx <= m_MaxMarkerLen; Idx++)
				{
				gDiagnostics.DiagOut(eDLInfo,gszProcName,"Length: %d Count: %u",Idx,m_pMarkerLenDist[Idx-1]);
				if(gProcessingID)
					gSQLiteSummaries.AddResultXY(gProcessingID,(char *)"MarkerReads",ePTInt32,sizeof(Idx),"Length",&Idx,ePTInt32,sizeof(m_pMarkerLenDist[Idx-1]),"Cnt",&m_pMarkerLenDist[Idx-1]);
				}
		else
			gDiagnostics.DiagOut(eDLInfo,gszProcName,"Length: %d Count: 0",m_KMerLen);
		}
	}

Reset();
return(eBSFSuccess);
}

// Thread startup
#ifdef WIN32
unsigned int __stdcall CLocKMers::KMerThreadStart(void *args)
{
#else
void * CLocKMers::KMerThreadStart(void *args)
{
#endif
tsKMerThreadPars *pArgs = (tsKMerThreadPars *)args;
pArgs->pThis->LocateSpeciesUniqueKMers(pArgs);
#ifdef WIN32
ExitThread(1);
#else
return NULL;
#endif
}

int							// marking reads containing the identified marker, both sense and antisense reads marked
CLocKMers::MarkContainingReads(int MarkKMerLen,						// marker is of this length
							   etSeqBase *pMarkStartKMerBase)		// marker sequence
{
UINT8 RevCplKMerSeq[cMaxKMerLen+1];
INT64 PrevHitIdx;
INT64 NxtHitIdx;
UINT32 TargHitID;
UINT32 TargHitLoci;

memmove(RevCplKMerSeq,pMarkStartKMerBase,MarkKMerLen);
CSeqTrans::ReverseComplement(MarkKMerLen,RevCplKMerSeq);

PrevHitIdx = 0;
while((NxtHitIdx = m_pSfxArray->IterateExacts(pMarkStartKMerBase,MarkKMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
	{
	m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,0x02);
	PrevHitIdx = NxtHitIdx;
	}

PrevHitIdx = 0;
pMarkStartKMerBase = RevCplKMerSeq;
while((NxtHitIdx = m_pSfxArray->IterateExacts(pMarkStartKMerBase,MarkKMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
	{
	m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,0x02);
	PrevHitIdx = NxtHitIdx;
	}

return(eBSFSuccess);
}

int
CLocKMers::LocateSpeciesUniqueKMers(tsKMerThreadPars *pPars)
{
UINT8 RevCplKMer[cMaxKMerLen+1];			// to hold reverse compliment of current K-mer being processed
UINT8 PrefixedCultivars[cMaxTargCultivarChroms];
int SubSeqsLen;
int StartIdx;
int	MarkStartIdx;
etSeqBase *pMarkStartKMerBase;
int	MarkKMerLen;
int CurSeqLen;
INT64 PrevHitIdx;
INT64 NxtHitIdx;
INT64 RcplHitIdx;
UINT32 TargHitID;
UINT32 TargHitLoci;
UINT32 RcplTargHitID;
UINT32 RcplTargHitLoci;
UINT32 NumBlocks;
INT64 NumKMers;
UINT32 NumPutativeKMers;
UINT32 NumAcceptedKMers;
UINT32 NumAcceptedExtdKMers;
int MatchesOthers;

int NumCultsPrefixed;

etSeqBase *pStartKMerBase;
etSeqBase *pEndKMerBase;

bool bTargHit;
bool bNonTargHit;
bool bIsDup;
int LociFlags;

int Cntr = 0;
NumPutativeKMers = 0;
NumAcceptedKMers = 0;
NumAcceptedExtdKMers = 0;
NumBlocks = 0;
NumKMers = 0;
while((SubSeqsLen=GetBlockSeqs(pPars->AllocBlockSeqsSize - 1,pPars->pBlockSeqs)) > 0)  // -1 because a eBaseEOG will be later appended
	{
	if(NumBlocks++ > 3)			// could report more frequently but as long as reporting a few times a minute then that's enough
		{
		AcquireLock(true);
		m_NumBlocks += NumBlocks;
		m_NumKMers += NumKMers;
		m_NumPutativeKMers += NumPutativeKMers;
		m_NumAcceptedKMers += NumAcceptedKMers;
		m_NumAcceptedExtdKMers += NumAcceptedExtdKMers;
		ReleaseLock(true);
		NumBlocks = 0;
		NumKMers = 0;
		NumPutativeKMers = 0;
		NumAcceptedKMers = 0;
		NumAcceptedExtdKMers = 0;
		}

	if(SubSeqsLen <= m_KMerLen)    // blocks returned will always be terminated by eBaseEOS hence <= compare
		continue;

	pPars->pBlockSeqs[SubSeqsLen] = eBaseEOG;

		// processing here on subsequences
	pEndKMerBase = pPars->pBlockSeqs;
	do {
		pStartKMerBase = pEndKMerBase;
		CurSeqLen = 0;
		while(*pEndKMerBase++ <= eBaseT)		// ensure K-mers do not contain any eBaseN's (should have already been removed) or eBaseEOS's
			CurSeqLen += 1;
		if(CurSeqLen < m_KMerLen)
			continue;

		MarkKMerLen = 0;
		for(StartIdx = 0; StartIdx <= CurSeqLen - m_KMerLen; StartIdx++, pStartKMerBase++)
			{
			NumKMers += 1;
			bTargHit = false;
			bNonTargHit = false;
			bIsDup = false;
			PrevHitIdx = 0;
			NxtHitIdx = 0;
			RcplHitIdx = 0;
			memmove(RevCplKMer,pStartKMerBase,m_KMerLen);
			CSeqTrans::ReverseComplement(m_KMerLen,RevCplKMer);
			while((NxtHitIdx = m_pSfxArray->IterateExacts(pStartKMerBase,m_KMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
				{
				if(!PrevHitIdx && IsTargetCultivar(TargHitID))
					{
					RcplHitIdx = m_pSfxArray->IterateExacts(RevCplKMer,m_KMerLen,0,&RcplTargHitID,&RcplTargHitLoci);
					if(RcplHitIdx != 0)
						LociFlags = m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,RcplTargHitID,RcplTargHitLoci,0x01);
					else
						LociFlags = m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,0x01);
					// check if already known that any previously processed K-mer hits this loci; if so this K-mer is a duplicate or revcpl of already processed K-mer
					if(LociFlags & 0x011)
						{
						bIsDup = true;			// treat as dup even though may have been revcpl
						break;
						}
					}

				if(IsTargetCultivar(TargHitID))			// was hit onto any of the target cultivar pseudo-chroms?
					bTargHit = true;
				else
					{
					bNonTargHit = true;
					break;
					}
				PrevHitIdx = NxtHitIdx;
				}
			if(bNonTargHit || bIsDup)
				continue;

			PrevHitIdx = RcplHitIdx;
			while((NxtHitIdx = m_pSfxArray->IterateExacts(RevCplKMer,m_KMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
				{
				if(IsTargetCultivar(TargHitID))
					bTargHit = true;
				else
					{
					bNonTargHit = true;
					break;
					}
				PrevHitIdx = NxtHitIdx;
				}
			if(bNonTargHit || !bTargHit)
				continue;

			// this is a unique K-mer which only exists in the target species
			NumPutativeKMers += 1;

			// check if this K-mer is at least the minimum requested Hammings away from any K-mer in any of the other species
			MatchesOthers = 0;
			if(m_MinHamming > 1)
				{
				MatchesOthers = m_pSfxArray->MatchesOtherChroms(m_NumPartialCultivars, m_CultChromIDs, m_MinHamming - 1, m_KMerLen,pStartKMerBase);
				if(!MatchesOthers)
					MatchesOthers = m_pSfxArray->MatchesOtherChroms(m_NumPartialCultivars, m_CultChromIDs, m_MinHamming - 1, m_KMerLen,  RevCplKMer);
				}

			// if unable to match allowing subs in other cultivars then this K-mer is putatively accepted
			// if must share prefix sequence with other cultivars then check this condition can be met
			if(!MatchesOthers)
				{
				NumAcceptedKMers += 1;											// accepted on Hammings...

				if(m_PMode == ePMPrefixKMers && m_PrefixLen)					// if must share prefix sequence with other cultivars then check this condition can be met
					{
					PrevHitIdx = 0;
					NumCultsPrefixed = 0;
					memset(PrefixedCultivars,0,sizeof(PrefixedCultivars[0]) * m_NumSfxEntries);
					while(NumCultsPrefixed < m_MinWithPrefix && ((NxtHitIdx = m_pSfxArray->IterateExacts(pStartKMerBase,m_PrefixLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0))
						{
						PrevHitIdx = NxtHitIdx;
						if(IsTargetCultivar(TargHitID))				// not interested in self hits onto targeted cultivars
							continue;
						// is this a new cultivar not previously seen..
						if(!PrefixedCultivars[TargHitID-1])
							{
							PrefixedCultivars[TargHitID-1] = 1;
							NumCultsPrefixed += 1;
							}
						}
					if(NumCultsPrefixed < m_MinWithPrefix)
						{
						// retry with reverse complemented prefix sequence
						PrevHitIdx = 0;
						while(NumCultsPrefixed < m_MinWithPrefix && ((NxtHitIdx = m_pSfxArray->IterateExacts(RevCplKMer,m_PrefixLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0))
							{
							PrevHitIdx = NxtHitIdx;
							if(IsTargetCultivar(TargHitID))				// not interested in self hits onto targeted cultivars
								continue;
							// is this a new cultivar not previously seen..
							if(!PrefixedCultivars[TargHitID-1])
								{
								PrefixedCultivars[TargHitID-1] = 1;
								NumCultsPrefixed += 1;
								}
							}
						if(NumCultsPrefixed < m_MinWithPrefix)
							continue;
						}
					}

				if(m_bKMerReads)
					MarkContainingReads(m_KMerLen,pStartKMerBase);

				// report K-mers of m_KMerLen only?
				if(m_PMode != ePMExtdKMers)
					{
					ReportMarker(m_KMerLen,pStartKMerBase);
					NumAcceptedExtdKMers+=1;
					continue;
					}

				// if would be a an extension of previous accepted then extend
				if((MarkKMerLen && (StartIdx > (MarkStartIdx + 1))))
					{
					ReportMarker(MarkKMerLen,pMarkStartKMerBase);
					NumAcceptedExtdKMers += 1;
					MarkKMerLen = 0;
					}
				if(MarkKMerLen == 0)
					{
					MarkKMerLen = m_KMerLen;
					pMarkStartKMerBase = pStartKMerBase;
					}
				else
					MarkKMerLen += 1;
				MarkStartIdx = StartIdx;
				}
			}
		if(m_PMode == ePMExtdKMers && MarkKMerLen)
			{
			ReportMarker(MarkKMerLen,pMarkStartKMerBase);
			NumAcceptedExtdKMers += 1;
			MarkKMerLen = 0;
			}
		}
	while(*pEndKMerBase != eBaseEOG);
	}

AcquireLock(true);
m_NumBlocks += NumBlocks;
m_NumKMers += NumKMers;
m_NumPutativeKMers += NumPutativeKMers;
m_NumAcceptedKMers += NumAcceptedKMers;
m_NumAcceptedExtdKMers += NumAcceptedExtdKMers;
ReleaseLock(true);
return(eBSFSuccess);
}

// LocateSharedUniqueKMers
// locate all unique K-mers of specified length which are common to all cultivars
int
CLocKMers::LocateSharedUniqueKMers(tsKMerThreadPars *pPars)
{
UINT8 RevCplKMer[cMaxKMerLen+1];			// to hold reverse compliment of current K-mer being processed

int SubSeqsLen;
int StartIdx;
int	MarkStartIdx;
etSeqBase *pMarkStartKMerBase;
int	MarkKMerLen;
int CurSeqLen;
INT64 PrevHitIdx;
INT64 NxtHitIdx;
INT64 RcplHitIdx;
UINT32 TargHitID;
UINT32 TargHitLoci;
UINT32 RcplTargHitID;
UINT32 RcplTargHitLoci;
UINT32 NumBlocks;
INT64 NumKMers;
UINT32 NumPutativeKMers;
UINT32 NumAcceptedKMers;
UINT32 NumAcceptedExtdKMers;
int MatchesOthers;

etSeqBase *pStartKMerBase;
etSeqBase *pEndKMerBase;

bool bTargHit;
bool bNonTargHit;
bool bIsDup;
int LociFlags;

int Cntr = 0;
NumPutativeKMers = 0;
NumAcceptedKMers = 0;
NumAcceptedExtdKMers = 0;
NumBlocks = 0;
NumKMers = 0;
while((SubSeqsLen=GetBlockSeqs(pPars->AllocBlockSeqsSize - 1,pPars->pBlockSeqs)) > 0)  // -1 because a eBaseEOG will be later appended
	{
	if(NumBlocks++ > 3)			// could report more frequently but as long as reporting a few times a minute then that's enough
		{
		AcquireLock(true);
		m_NumBlocks += NumBlocks;
		m_NumKMers += NumKMers;
		m_NumPutativeKMers += NumPutativeKMers;
		m_NumAcceptedKMers += NumAcceptedKMers;
		m_NumAcceptedExtdKMers += NumAcceptedExtdKMers;
		ReleaseLock(true);
		NumBlocks = 0;
		NumKMers = 0;
		NumPutativeKMers = 0;
		NumAcceptedKMers = 0;
		NumAcceptedExtdKMers = 0;
		}

	if(SubSeqsLen <= m_KMerLen)    // blocks returned will always be terminated by eBaseEOS hence <= compare
		continue;

	pPars->pBlockSeqs[SubSeqsLen] = eBaseEOG;

		// processing here on subsequences
	pEndKMerBase = pPars->pBlockSeqs;
	do {
		pStartKMerBase = pEndKMerBase;
		CurSeqLen = 0;
		while(*pEndKMerBase++ <= eBaseT)		// ensure K-mers do not contain any eBaseN's (should have already been removed) or eBaseEOS's
			CurSeqLen += 1;
		if(CurSeqLen < m_KMerLen)
			continue;

		MarkKMerLen = 0;
		for(StartIdx = 0; StartIdx <= CurSeqLen - m_KMerLen; StartIdx++, pStartKMerBase++)
			{
			NumKMers += 1;
			bTargHit = false;
			bNonTargHit = false;
			bIsDup = false;
			PrevHitIdx = 0;
			NxtHitIdx = 0;
			RcplHitIdx = 0;
			memmove(RevCplKMer,pStartKMerBase,m_KMerLen);
			CSeqTrans::ReverseComplement(m_KMerLen,RevCplKMer);
			while((NxtHitIdx = m_pSfxArray->IterateExacts(pStartKMerBase,m_KMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
				{
				if(!PrevHitIdx && IsTargetCultivar(TargHitID))
					{
					RcplHitIdx = m_pSfxArray->IterateExacts(RevCplKMer,m_KMerLen,0,&RcplTargHitID,&RcplTargHitLoci);
					if(RcplHitIdx != 0)
						LociFlags = m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,RcplTargHitID,RcplTargHitLoci,0x01);
					else
						LociFlags = m_pSfxArray->SetBaseFlags(TargHitID,TargHitLoci,0x01);
					// check if already known that any previously processed K-mer hits this loci; if so this K-mer is a duplicate or revcpl of already processed K-mer
					if(LociFlags & 0x011)
						{
						bIsDup = true;			// treat as dup even though may have been revcpl
						break;
						}
					}

				if(IsTargetCultivar(TargHitID))			// was hit onto any of the target cultivar pseudo-chroms?
					bTargHit = true;
				else
					{
					bNonTargHit = true;
					break;
					}
				PrevHitIdx = NxtHitIdx;
				}
			if(bNonTargHit || bIsDup)
				continue;

			PrevHitIdx = RcplHitIdx;
			while((NxtHitIdx = m_pSfxArray->IterateExacts(RevCplKMer,m_KMerLen,PrevHitIdx,&TargHitID,&TargHitLoci)) > 0)
				{
				if(IsTargetCultivar(TargHitID))
					bTargHit = true;
				else
					{
					bNonTargHit = true;
					break;
					}
				PrevHitIdx = NxtHitIdx;
				}
			if(bNonTargHit || !bTargHit)
				continue;

			// this is a unique K-mer which only exists in the target species
			NumPutativeKMers += 1;

			// check if this K-mer is at least the minimum requested Hammings away from any K-mer in any of the other species
			MatchesOthers = 0;
			if(m_MinHamming > 1)
				{
				MatchesOthers = m_pSfxArray->MatchesOtherChroms(m_NumPartialCultivars, m_CultChromIDs, m_MinHamming - 1, m_KMerLen,pStartKMerBase);
				if(!MatchesOthers)
					MatchesOthers = m_pSfxArray->MatchesOtherChroms(m_NumPartialCultivars, m_CultChromIDs, m_MinHamming - 1, m_KMerLen,  RevCplKMer);
				}

			// if unable to match allowing subs in other cultivars then this K-mer is accepted
			if(!MatchesOthers)
				{
				NumAcceptedKMers += 1;

				if(m_bKMerReads)
					MarkContainingReads(m_KMerLen,pStartKMerBase);

				// report K-mers of m_KMerLen only?
				if(m_PMode == ePMNoExtdKMers)
					{
					ReportMarker(m_KMerLen,pStartKMerBase);
					NumAcceptedExtdKMers+=1;
					continue;
					}

				// if would be a an extension of previous accepted then extend
				if((MarkKMerLen && (StartIdx > (MarkStartIdx + 1))))
					{
					ReportMarker(MarkKMerLen,pMarkStartKMerBase);
					NumAcceptedExtdKMers += 1;
					MarkKMerLen = 0;
					}
				if(MarkKMerLen == 0)
					{
					MarkKMerLen = m_KMerLen;
					pMarkStartKMerBase = pStartKMerBase;
					}
				else
					MarkKMerLen += 1;
				MarkStartIdx = StartIdx;
				}
			}
		if(m_PMode == ePMExtdKMers && MarkKMerLen)
			{
			ReportMarker(MarkKMerLen,pMarkStartKMerBase);
			NumAcceptedExtdKMers += 1;
			MarkKMerLen = 0;
			}
		}
	while(*pEndKMerBase != eBaseEOG);
	}

AcquireLock(true);
m_NumBlocks += NumBlocks;
m_NumKMers += NumKMers;
m_NumPutativeKMers += NumPutativeKMers;
m_NumAcceptedKMers += NumAcceptedKMers;
m_NumAcceptedExtdKMers += NumAcceptedExtdKMers;
ReleaseLock(true);
return(eBSFSuccess);
}

// used when sorting cultivar partial pseudo-chrom names
int
CLocKMers::sortpartcultnames(const void *pEl1,const void *pEl2)
{
tsPartialCultivar *p1 = (tsPartialCultivar *)pEl1;
tsPartialCultivar *p2 = (tsPartialCultivar *)pEl2;
return(stricmp(p1->szEntryName,p2->szEntryName));
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../../../../spec_helper')

describe Palani::Frontend::Templating::MenusHelper do

  describe "menu" do
  end

end

redpajama_set_name: RedPajamaGithub


text:
import { CompileDirectiveMetadata } from '../compile_metadata';
import * as o from '../output/output_ast';
import * as t from '../template_parser/template_ast';
export declare class CompiledAnimation {
    name: string;
    statesMapStatement: o.Statement;
    statesVariableName: string;
    fnStatement: o.Statement;
    fnVariable: o.Expression;
    constructor(name: string, statesMapStatement: o.Statement, statesVariableName: string, fnStatement: o.Statement, fnVariable: o.Expression);
}
export declare class AnimationCompiler {
    compileComponent(component: CompileDirectiveMetadata, template: t.TemplateAst[]): CompiledAnimation[];
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace MS.Internal.Interop
{
  internal partial interface IStream
  {
    #region Methods and constructors
    void Commit(int commitFlags);

    void CopyTo(IStream targetStream, long bytesToCopy, IntPtr refToNumBytesRead, IntPtr refToNumBytesWritten);

    void LockRegion(long offset, long sizeInBytes, int lockType);

    void Read(IntPtr bufferBase, int sizeInBytes, IntPtr refToNumBytesRead);

    void Revert();

    void Seek(long offset, int origin, IntPtr refToNewOffsetNullAllowed);

    void SetSize(long newSize);

    void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG statStructure, int statFlag);

    void UnlockRegion(long offset, long sizeInBytes, int lockType);

    void Write(IntPtr bufferBase, int sizeInBytes, IntPtr refToNumBytesWritten);
    #endregion
  }
}


text:
<?php

class Doghouse_Carousel_Model_Group extends Mage_Core_Model_Abstract
{

    /**
     * Event prefix for easier listening to save/load before/after events
     * @var string
     */
    protected $_eventPrefix = 'dhcarousel_group';

    /**
     * Construct carousel group.
     */
    protected function _construct()
    {
        $this->_init('dhcarousel/group');
    }

    /**
     * Deal with clearing this specific carousels cache
     *
     * @return $this
     */
    protected function _beforeSave()
    {
        $tag = array(Doghouse_Carousel_Block_Carousel::CACHE_GROUP . '_' . $this->getId());
        mage::helper('dhcarousel')->clearCache($tag);
        return $this;
    }
}


text:
var EventEmitter = require("events");
var RTCUtils = require("./RTCUtils.js");
var LocalStream = require("./LocalStream.js");
var DataChannels = require("./DataChannels");
var MediaStream = require("./MediaStream.js");
var DesktopSharingEventTypes
    = require("../../service/desktopsharing/DesktopSharingEventTypes");
var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
var RTCEvents = require("../../service/RTC/RTCEvents.js");
var XMPPEvents = require("../../service/xmpp/XMPPEvents");
var UIEvents = require("../../service/UI/UIEvents");

var eventEmitter = new EventEmitter();

function getMediaStreamUsage()
{
    var result = {
        audio: true,
        video: true
    };

    /** There are some issues with the desktop sharing
     * when this property is enabled.
     * WARNING: We must change the implementation to start video/audio if we
     * receive from the focus that the peer is not muted.

     var isSecureConnection = window.location.protocol == "https:";

    if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
    {
        result = {
            audio: false,
            video: false
        };

    }
    **/

    return result;
}

var RTC = {
    rtcUtils: null,
    devices: {
        audio: true,
        video: true
    },
    localStreams: [],
    remoteStreams: {},
    localAudio: null,
    localVideo: null,
    addStreamListener: function (listener, eventType) {
        eventEmitter.on(eventType, listener);
    },
    addListener: function (type, listener) {
        eventEmitter.on(type, listener);
    },
    removeStreamListener: function (listener, eventType) {
        if(!(eventType instanceof StreamEventTypes))
            throw "Illegal argument";

        eventEmitter.removeListener(eventType, listener);
    },
    createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {

        var localStream =  new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
        //in firefox we have only one stream object
        if(this.localStreams.length == 0 ||
            this.localStreams[0].getOriginalStream() != stream)
            this.localStreams.push(localStream);
        if(isMuted === true)
            localStream.setMute(false);

        if(type == "audio")
        {
            this.localAudio = localStream;
        }
        else
        {
            this.localVideo = localStream;
        }
        var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
        if(change)
            eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;

        eventEmitter.emit(eventType, localStream, isMuted);
        return localStream;
    },
    removeLocalStream: function (stream) {
        for(var i = 0; i < this.localStreams.length; i++)
        {
            if(this.localStreams[i].getOriginalStream() === stream) {
                delete this.localStreams[i];
                return;
            }
        }
    },
    createRemoteStream: function (data, sid, thessrc) {
        var remoteStream = new MediaStream(data, sid, thessrc,
            this.getBrowserType(), eventEmitter);
        var jid = data.peerjid || APP.xmpp.myJid();
        if(!this.remoteStreams[jid]) {
            this.remoteStreams[jid] = {};
        }
        this.remoteStreams[jid][remoteStream.type]= remoteStream;
        eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
        return remoteStream;
    },
    getBrowserType: function () {
        return this.rtcUtils.browser;
    },
    getPCConstraints: function () {
        return this.rtcUtils.pc_constraints;
    },
    getUserMediaWithConstraints:function(um, success_callback,
                                         failure_callback, resolution,
                                         bandwidth, fps, desktopStream)
    {
        return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
            failure_callback, resolution, bandwidth, fps, desktopStream);
    },
    attachMediaStream:  function (element, stream) {
        this.rtcUtils.attachMediaStream(element, stream);
    },
    getStreamID:  function (stream) {
        return this.rtcUtils.getStreamID(stream);
    },
    getVideoSrc: function (element) {
        return this.rtcUtils.getVideoSrc(element);
    },
    setVideoSrc: function (element, src) {
        this.rtcUtils.setVideoSrc(element, src);
    },
    dispose: function() {
        if (this.rtcUtils) {
            this.rtcUtils = null;
        }
    },
    stop:  function () {
        this.dispose();
    },
    start: function () {
        var self = this;
        APP.desktopsharing.addListener(
            function (stream, isUsingScreenStream, callback) {
                self.changeLocalVideo(stream, isUsingScreenStream, callback);
            }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
        APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
            for(var i = 0; i < changedStreams.length; i++) {
                var type = changedStreams[i].type;
                if (type != "audio") {
                    var peerStreams = self.remoteStreams[jid];
                    if(!peerStreams)
                        continue;
                    var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
                    if(!videoStream)
                        continue;
                    videoStream.setVideoType(changedStreams[i].type);
                }
            }
        });
        APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
            DataChannels.init(event.peerconnection, eventEmitter);
        });
        APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
            DataChannels.handleSelectedEndpointEvent);
        APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
            DataChannels.handlePinnedEndpointEvent);
        this.rtcUtils = new RTCUtils(this);
        this.rtcUtils.obtainAudioAndVideoPermissions(
            null, null, getMediaStreamUsage());
    },
    muteRemoteVideoStream: function (jid, value) {
        var stream;

        if(this.remoteStreams[jid] &&
            this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
        {
            stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
        }

        if(!stream)
            return true;

        if (value != stream.muted) {
            stream.setMute(value);
            return true;
        }
        return false;
    },
    switchVideoStreams: function (new_stream) {
        this.localVideo.stream = new_stream;

        this.localStreams = [];

        //in firefox we have only one stream object
        if (this.localAudio.getOriginalStream() != new_stream)
            this.localStreams.push(this.localAudio);
        this.localStreams.push(this.localVideo);
    },
    changeLocalVideo: function (stream, isUsingScreenStream, callback) {
        var oldStream = this.localVideo.getOriginalStream();
        var type = (isUsingScreenStream? "screen" : "video");
        var localCallback = callback;
        if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
        {
            localCallback = function() {
                APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
                callback();
            };
        }
        var videoStream = this.rtcUtils.createStream(stream, true);
        this.localVideo = this.createLocalStream(videoStream, "video", true, type);
        // Stop the stream to trigger onended event for old stream
        oldStream.stop();
        APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
    },
    changeLocalAudio: function (stream, callback) {
        var oldStream = this.localAudio.getOriginalStream();
        var newStream = this.rtcUtils.createStream(stream);
        this.localAudio = this.createLocalStream(newStream, "audio", true);
        // Stop the stream to trigger onended event for old stream
        oldStream.stop();
        APP.xmpp.switchStreams(newStream, oldStream, callback, true);
    },
    /**
     * Checks if video identified by given src is desktop stream.
     * @param videoSrc eg.
     * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
     * @returns {boolean}
     */
    isVideoSrcDesktop: function (jid) {
        if(!jid)
            return false;
        var isDesktop = false;
        var stream = null;
        if (APP.xmpp.myJid() === jid) {
            // local video
            stream = this.localVideo;
        } else {
            var peerStreams = this.remoteStreams[jid];
            if(!peerStreams)
                return false;
            stream = peerStreams[MediaStreamType.VIDEO_TYPE];
        }

        if(stream)
            isDesktop = (stream.videoType === "screen");

        return isDesktop;
    },
    setVideoMute: function(mute, callback, options) {
        if(!this.localVideo)
            return;

        if (mute == APP.RTC.localVideo.isMuted())
        {
            APP.xmpp.sendVideoInfoPresence(mute);
            if(callback)
                callback(mute);
        }
        else
        {
            APP.RTC.localVideo.setMute(!mute);
            APP.xmpp.setVideoMute(
                mute,
                callback,
                options);
        }
    },
    setDeviceAvailability: function (devices) {
        if(!devices)
            return;
        if(devices.audio === true || devices.audio === false)
            this.devices.audio = devices.audio;
        if(devices.video === true || devices.video === false)
            this.devices.video = devices.video;
        eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
    }
};

module.exports = RTC;


text:
import test from 'ava';
import detectBadges from '../../';

test('coveralls: coveralls.io', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';

    const badge = detectBadges(`https://coveralls.io/repos/${user}/${repo}/badge.svg`)[0];

    t.is(badge.urls.original, `https://coveralls.io/repos/${user}/${repo}/badge.svg`);
    t.is(badge.urls.service, `https://coveralls.io/repos/${user}/${repo}/badge.svg`);
    t.is(badge.urls.shields, `https://img.shields.io/coveralls/${user}/${repo}.svg`);
    t.is(badge.urls.content, `https://img.shields.io/coveralls/${user}/${repo}.json`);
    t.is(badge.info.service, 'coveralls');
    t.is(badge.info.type, 'coverage');
});

test('coveralls: coveralls.io (with branch)', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';
    const branch = 'master';

    const badge = detectBadges(`https://coveralls.io/repos/${user}/${repo}/badge.svg?branch=${branch}`)[0];

    t.is(badge.urls.original, `https://coveralls.io/repos/${user}/${repo}/badge.svg?branch=${branch}`);
    t.is(badge.urls.service, `https://coveralls.io/repos/${user}/${repo}/badge.svg?branch=${branch}`);
    t.is(badge.urls.shields, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.svg`);
    t.is(badge.urls.content, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.json`);
    t.is(badge.info.service, 'coveralls');
    t.is(badge.info.type, 'coverage');
    t.deepEqual(badge.info.modifiers, { branch: 'master' });
});

test('coveralls: coveralls.io (with service)', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';
    const branch = 'master';

    const badge = detectBadges(`https://coveralls.io/repos/github/${user}/${repo}/badge.svg?branch=${branch}`)[0];

    t.is(badge.urls.original, `https://coveralls.io/repos/github/${user}/${repo}/badge.svg?branch=${branch}`);
    t.is(badge.urls.service, `https://coveralls.io/repos/github/${user}/${repo}/badge.svg?branch=${branch}`);
    t.is(badge.urls.shields, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.svg`);
    t.is(badge.urls.content, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.json`);
    t.is(badge.info.service, 'coveralls');
    t.is(badge.info.type, 'coverage');
    t.deepEqual(badge.info.modifiers, { branch: 'master' });
});

test('coveralls: shields.io', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';

    const badge = detectBadges(`https://img.shields.io/coveralls/${user}/${repo}.svg`)[0];

    t.is(badge.urls.original, `https://img.shields.io/coveralls/${user}/${repo}.svg`);
    t.is(badge.urls.service, `https://coveralls.io/repos/${user}/${repo}/badge.svg`);
    t.is(badge.urls.shields, `https://img.shields.io/coveralls/${user}/${repo}.svg`);
    t.is(badge.urls.content, `https://img.shields.io/coveralls/${user}/${repo}.json`);
    t.is(badge.info.service, 'coveralls');
    t.is(badge.info.type, 'coverage');
});

test('coveralls: shields.io (with branch)', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';
    const branch = 'master';

    const badge = detectBadges(`https://img.shields.io/coveralls/${user}/${repo}/${branch}.svg`)[0];

    t.is(badge.urls.original, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.svg`);
    t.is(badge.urls.service, `https://coveralls.io/repos/${user}/${repo}/badge.svg?branch=${branch}`);
    t.is(badge.urls.shields, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.svg`);
    t.is(badge.urls.content, `https://img.shields.io/coveralls/${user}/${repo}/${branch}.json`);
    t.is(badge.info.service, 'coveralls');
    t.is(badge.info.type, 'coverage');
    t.deepEqual(badge.info.modifiers, { branch: 'master' });
});

test('coveralls: not a valid coveralls url', t => {
    const user = 'IndigoUnited';
    const repo = 'js-promtie';

    t.falsy(detectBadges(`https://coveralls.com/repos/${user}/${repo}/badge.svg`)[0]);
});


text:
{-# LANGUAGE OverloadedStrings #-}

module Duckling.Volume.PT.Corpus
  ( corpus ) where

import Data.String
import Prelude

import Duckling.Locale
import Duckling.Resolve
import Duckling.Volume.Types
import Duckling.Testing.Types

corpus :: Corpus
corpus = (testContext {locale = makeLocale PT Nothing}, testOptions, allExamples)

allExamples :: [Example]
allExamples = concat
  [ examples (simple Millilitre 250)
             [ "250 mililitros"
             , "250ml"
             , "250 ml"
             ]
  , examples (simple Litre 2)
             [ "2 litros"
             ]
  , examples (simple Gallon 1)
             [ "1 galão"
             ]
  , examples (simple Gallon 3)
             [ "3 galões"
             ]
  , examples (simple Hectolitre 3)
             [ "3 hectolitros"
             ]
  , examples (simple Litre 0.5)
             [ "meio litro"
             ]
  ]


text:
namespace Exception {
	class BaseException abstract :public std::exception, public BaseClass {
	public:
		BaseException() :std::exception() {}
		virtual wchar_t* GetDescription() const;
		static const wchar_t* DescriptionFormat;
	};
	// Some unexpected error occured in the program.
	// This means that there's some bugs in the program.
	class UnexpectedErrorException :public BaseException {
	public:
		explicit UnexpectedErrorException(_In_ const char* const file, _In_ const int line) :FileName(file), LineNumber(line) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const int LineNumber;
		static const wchar_t* DescriptionFormat;
	};
	// An external API call failed.
	class ExternalAPIErrorException :public BaseException {
	public:
		explicit ExternalAPIErrorException(_In_ const char* const file, _In_ const int line, _In_opt_ const char* const library_name, _In_ const char* const function_name) :FileName(file), LineNumber(line), LibraryName(library_name), FunctionName(function_name) {}
		explicit ExternalAPIErrorException(_In_ const char* const file, _In_ const int line, _In_ const char* const function_name) :FileName(file), LineNumber(line), LibraryName(nullptr), FunctionName(function_name) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const int LineNumber;
		const char* const LibraryName;
		const char* const FunctionName;
		static const wchar_t* DescriptionFormat_Lib;
		static const wchar_t* DescriptionFormat_NoLib;
	};
	// A parameter is invalid.
	class InvalidParameterException :public BaseException {
	public:
		explicit InvalidParameterException(_In_ const char* const file, _In_ const char* const func, _In_ const unsigned char parameter_index) :FileName(file), FunctionName(func), ParameterIndex(parameter_index) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const char* const FunctionName;
		const unsigned char ParameterIndex;
		static const wchar_t* DescriptionFormat;
	};
	// Thread initialization failure.
	class ThreadInitializationFailureException :public BaseException {
	public:
		explicit ThreadInitializationFailureException(_In_ const char* const file, _In_ const int line, _In_ const HANDLE hthread) :FileName(file), LineNumber(line), ThreadHandle(hthread) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const int LineNumber;
		const HANDLE ThreadHandle;
		static const wchar_t* DescriptionFormat;
	};
	// Window initialization failure.
	class WindowInitializationFailureException :public BaseException {
	public:
		explicit WindowInitializationFailureException(_In_ const char* const file, _In_ const int line, _In_ const wchar_t* const window_class_name) :FileName(file), LineNumber(line), WindowClassName(window_class_name) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const int LineNumber;
		const wchar_t* const WindowClassName;
		static const wchar_t* DescriptionFormat;
	};
	// Control error.
	class ControlErrorException :public BaseException {
	public:
		explicit ControlErrorException(_In_ const char* const file, _In_ const int line, _In_ const wchar_t* const window_class_name) :FileName(file), LineNumber(line), WindowClassName(window_class_name) {}
		virtual wchar_t* GetDescription() const;
		const char* const FileName;
		const int LineNumber;
		const wchar_t* const WindowClassName;
		static const wchar_t* DescriptionFormat;
	};
}


text:
goog.module('proto.im.integration.MessageEqualityTest');
goog.setTestOnly();

const MessageA = goog.require('improto.protobuf.contrib.immutablejs.protos.MessageA');
const MessageB = goog.require('improto.protobuf.contrib.immutablejs.protos.MessageB');
const testSuite = goog.require('goog.testing.testSuite');
const {assertEqualsForProto} = goog.require('proto.im.proto_asserts');

class MessageEqualityTest {
  testEqualsForStructurallySameMessage() {
    const protoA = MessageA.newBuilder().setFoo('Foo').build();
    const protoB = MessageB.newBuilder().setFoo('Foo').build();
    const otherProtoA = MessageA.newBuilder().setFoo('Foo').build();
    const otherProtoB = MessageB.newBuilder().setFoo('Foo').build();

    assertEqualsForProto(protoA, protoA);
    assertEqualsForProto(protoB, protoB);
    assertEqualsForProto(protoA, otherProtoA);
    assertEqualsForProto(protoB, otherProtoB);
    // Makes sure that messages with the same structure are not seen as equal
    assertFalse(protoA.equals(protoB));
  }
}

testSuite(new MessageEqualityTest());


text:
<component name="libraryTable">
  <library name="Maven: com.codahale.metrics:metrics-servlets:3.0.2">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/codahale/metrics/metrics-servlets/3.0.2/metrics-servlets-3.0.2.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/codahale/metrics/metrics-servlets/3.0.2/metrics-servlets-3.0.2-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/codahale/metrics/metrics-servlets/3.0.2/metrics-servlets-3.0.2-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package org.dbflute.erflute.db.impl.mysql;

import java.sql.SQLException;

import org.dbflute.erflute.editor.model.dbexport.db.PreTableExportManager;

public class MySQLPreTableExportManager extends PreTableExportManager {

    @Override
    protected String dropForeignKeys() throws SQLException {
        StringBuilder ddl = new StringBuilder();
        ddl.append("SET SESSION FOREIGN_KEY_CHECKS=0;\r\n\r\n");

        return ddl.toString();
    }

    @Override
    protected void prepareNewNames() {
    }
}


text:
package com.agileapes.powerpack.tree.description.evaluator;

import com.agileapes.powerpack.tree.Node;

import java.util.List;

public interface NodeEvaluatorFactory {

    void register(NodeDescriptionEvaluator evaluator);

    boolean evaluate(String name, Node node, List<String> parameters);

}


text:
package cc.eevee.hellodjinni;

import android.app.Application;

public class MyApplication extends Application {

    static {
        try {
            System.loadLibrary("hellodjinni_jni");
        } catch (UnsatisfiedLinkError e) {
            System.err.println("Native code library failed to load.\n" + e);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
    <meta name="title" content="404 Page not found">
    <meta name="description" content="">
    <meta name="keywords" content="">

    <meta name="og:title" content="404 Page not found">
    <meta name="og:url" content="https://twitter.github.io/404.html">

    <meta name="og:description" content="">

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="https://twitter.github.io/404.html" />
    <meta name="twitter:title" content="404 Page not found" />
    <meta name="twitter:description" content="" />

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta http-equiv='Expires' content='0'>
    <meta http-equiv='Pragma' content='no-cache'>
    <meta http-equiv='Cache-Control' content='no-cache'>
    <meta http-equiv='imagetoolbar' content='no'>

    <title>404 Page not found</title>
    <link rel="shortcut icon" type="image/png" href="/assets/favicon.ico"/>

    <link rel="stylesheet" href="/css/feather-core.css"/>
    <link rel="stylesheet" href="/css/feather-component-grid.css"/>
    <link rel="stylesheet" href="/css/feather-component-button.css"/>

    <link rel="stylesheet" href="/css/main.css"/>

            Twitter Open Source

Twitter Open Source

                Twitter Open Source

                Projects

                #Squad

              Year in Review

                Blog

                GitHub

404

Page not found :(

ProTip: Make sure you don't have a trailing slash in the URL

                <button onclick="location.href='\/projects'" type="button" class="Button Button--large">Explore Projects</button>

                    About

                Let's go Twitter
                Careers

                    Blogs

                Open Source
                Engineering
                Developer

                    Developers

                Documentation
                Forums
                Communities

                © 2018 Twitter, Inc.

                Cookies

                Privacy

                Terms and Conditions


text:
var db=require('../dbconnection'); //reference of dbconnection.js

var Vesselinfo={

getAllvesselinfo:function(callback){

return db.query("Select * from vessel_info limit 10",callback);

},
 getAllVesselinfoByTime:function(date,callback){

 var sql = "select bb.* from (select a.mmsi,a.tipe,c.lon,c.lat,c.hdt,c.sog,c.last_posdate, a.name, a.callsign from vessel_info a inner join ( select * from ( select * from ( select mmsi,last_posdate, lat,lon,sog,hdt,cog, CASE mmsi WHEN @curType THEN @curRank := @curRank + 1 ELSE @curRank := 1 AND @curType := mmsi END AS rank from vessel_track a, (SELECT @curRank := 0, @curType := '') r where last_posdate > DATE_SUB(STR_TO_DATE(?,'%Y-%m-%d %H:%i:%s'),INTERVAL 9 HOUR) and last_posdate < DATE_SUB(STR_TO_DATE(?,'%Y-%m-%d %H:%i:%s'), INTERVAL 7 HOUR) ORDER BY MMSI, last_posdate desc ) x where x.rank = 1 ) dd ) c on c.mmsi=a.mmsi and a.callsign in (SELECT callsign FROM pertamina_ship)) bb LEFT JOIN vessel_type b ON (bb.tipe = b.tipe_name)order by bb.mmsi asc,bb.last_posdate asc";

return db.query(sql,[date, date],callback);
 },
 getAllVesselinfoByTimeAndMMSI:function(date,mmsi,callback){

 var sql = "select bb.* from (select a.mmsi,a.tipe,c.lon,c.lat,c.hdt,c.sog,c.last_posdate, a.name, a.callsign from vessel_info a inner join ( select * from ( select * from ( select mmsi,last_posdate, lat,lon,sog,hdt,cog, CASE mmsi WHEN @curType THEN @curRank := @curRank + 1 ELSE @curRank := 1 AND @curType := mmsi END AS rank from vessel_track a, (SELECT @curRank := 0, @curType := '') r where last_posdate > DATE_SUB(STR_TO_DATE(?,'%Y-%m-%d %H:%i:%s'),INTERVAL 9 HOUR) and last_posdate < DATE_SUB(STR_TO_DATE(?,'%Y-%m-%d %H:%i:%s'), INTERVAL 7 HOUR) ORDER BY MMSI, last_posdate desc ) x where x.rank = 1 ) dd ) c on c.mmsi=a.mmsi and a.mmsi = ? and a.callsign in (SELECT callsign FROM pertamina_ship)) bb LEFT JOIN vessel_type b ON (bb.tipe = b.tipe_name)order by bb.mmsi asc,bb.last_posdate asc";

return db.query(sql,[date, date, mmsi],callback);
 },
 addVesselinfo:function(Vesselinfo,callback){
 return db.query("Insert into Vesselinfo values(?,?,?)",[Vesselinfo.Id,Vesselinfo.Title,Vesselinfo.Status],callback);
 },
 deleteVesselinfo:function(id,callback){
  return db.query("delete from Vesselinfo where Id=?",[id],callback);
 },
 updateVesselinfo:function(id,Vesselinfo,callback){
  return db.query("update Vesselinfo set Title=?,Status=? where Id=?",[Vesselinfo.Title,Vesselinfo.Status,id],callback);
 }

};
 module.exports=Vesselinfo;


text:
namespace TwitchLiveCounter {
    partial class Taskbar {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            this.components = new System.ComponentModel.Container();
            this.btnUpdateNow = new System.Windows.Forms.Button();
            this.btnSettings = new System.Windows.Forms.Button();
            this.tmrUpdate = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // btnUpdateNow
            //
            this.btnUpdateNow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnUpdateNow.Location = new System.Drawing.Point(13, 119);
            this.btnUpdateNow.Name = "btnUpdateNow";
            this.btnUpdateNow.Size = new System.Drawing.Size(227, 23);
            this.btnUpdateNow.TabIndex = 0;
            this.btnUpdateNow.Text = "Update Now";
            this.btnUpdateNow.UseVisualStyleBackColor = true;
            this.btnUpdateNow.Click += new System.EventHandler(this.btnUpdateNow_Click);
            //
            // btnSettings
            //
            this.btnSettings.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnSettings.Location = new System.Drawing.Point(13, 90);
            this.btnSettings.Name = "btnSettings";
            this.btnSettings.Size = new System.Drawing.Size(227, 23);
            this.btnSettings.TabIndex = 1;
            this.btnSettings.Text = "Settings";
            this.btnSettings.UseVisualStyleBackColor = true;
            this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click);
            //
            // tmrUpdate
            //
            this.tmrUpdate.Tick += new System.EventHandler(this.tmrUpdate_Tick);
            //
            // Taskbar
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(252, 154);
            this.Controls.Add(this.btnSettings);
            this.Controls.Add(this.btnUpdateNow);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "Taskbar";
            this.Text = "Taskbar";
            this.Deactivate += new System.EventHandler(this.closeform);
            this.Load += new System.EventHandler(this.Taskbar_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnUpdateNow;
        private System.Windows.Forms.Button btnSettings;
        private System.Windows.Forms.Timer tmrUpdate;
    }
}


text:
<?php

/*
 * This file is part of Mannequin.
 *
 * (c) 2017 Last Call Media, Rob Bayliss <rob@lastcallmedia.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace LastCall\Mannequin\Core;

use LastCall\Mannequin\Core\Asset\AssetManager;
use LastCall\Mannequin\Core\Asset\AssetManagerInterface;
use LastCall\Mannequin\Core\Asset\RequestContextContext;
use LastCall\Mannequin\Core\Config\ConfigInterface;
use LastCall\Mannequin\Core\DependencyInjection\ContainerInterface;
use LastCall\Mannequin\Core\Discovery\ChainDiscovery;
use LastCall\Mannequin\Core\Discovery\DiscoveryInterface;
use LastCall\Mannequin\Core\Engine\DelegatingEngine;
use LastCall\Mannequin\Core\MimeType\ExtensionMimeTypeGuesser;
use LastCall\Mannequin\Core\Snapshot\Camera;
use LastCall\Mannequin\Core\Snapshot\CameraInterface;
use LastCall\Mannequin\Core\Ui\Controller\ManifestController;
use LastCall\Mannequin\Core\Ui\Controller\RenderController;
use LastCall\Mannequin\Core\Ui\Controller\StaticFileController;
use LastCall\Mannequin\Core\Ui\ManifestBuilder;
use LastCall\Mannequin\Core\Variable\VariableResolver;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\NullLogger;
use Silex\Application;
use Silex\EventListener\LogListener;
use Silex\Provider\ServiceControllerServiceProvider;
use Symfony\Component\Asset\PackageInterface;
use Symfony\Component\Asset\PathPackage;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * DI/Kernel class for Mannequin.
 *
 * NB: This class is likely to change rapidly.  Wherever possible, type hint
 * to ContainerInterface rather than this class, and never rely on the
 * Silex/Pimple ArrayAccess getters/setters.
 */
class Mannequin extends Application implements ContainerInterface
{
    public function __construct(ConfigInterface $config, array $values = [])
    {
        $values += [
            'logger' => function () {
                return new NullLogger();
            },
        ];
        parent::__construct($values);
        $this['config'] = $config;
        $this['commands'] = function () use ($config) {
            $commands = [];
            foreach ($this->getExtensions() as $extension) {
                $commands = array_merge($commands, $extension->getCommands());
            }

            return $commands;
        };

        $this['log.listener'] = function () {
            return new LogListener($this['logger']);
        };
        $this['cache_dir'] = function () use ($config) {
            return sprintf('%s/mannequin/%s', sys_get_temp_dir(), $config->getCachePrefix());
        };
        $this['cache'] = function () {
            return new FilesystemAdapter('', 0, $this['cache_dir'].'/cache');
        };

        $this['manifest.builder'] = function () {
            $this->flush();

            return new ManifestBuilder($this['url_generator']);
        };
        $this['ui'] = function () {
            return $this['config']->getUi();
        };
        $this['engine'] = function () {
            $engines = [];
            foreach ($this->getExtensions() as $extension) {
                $engines = array_merge($engines, $extension->getEngines());
            }

            return new DelegatingEngine($engines);
        };
        $this['discovery'] = function () {
            $discoverers = [];
            foreach ($this->getExtensions() as $extension) {
                $discoverers = array_merge($discoverers, $extension->getDiscoverers());
            }

            return new ChainDiscovery($discoverers, $this['dispatcher'], $this['logger']);
        };

        $this['asset.package'] = function () {
            return new PathPackage(
                '',
                new StaticVersionStrategy(time()),
                new RequestContextContext($this['request_context'])
            );
        };

        $this['asset.manager'] = function () use ($config) {
            return new AssetManager(
                $config->getAssets(),
                $config->getDocroot()
            );
        };

        $this['variable.resolver'] = function () {
            $expressionLanguage = new ExpressionLanguage();
            foreach ($this->getExtensions() as $extension) {
                if ($extension instanceof ExpressionFunctionProviderInterface) {
                    $expressionLanguage->registerProvider($extension);
                }
            }

            return new VariableResolver($expressionLanguage, $this);
        };
        $this['metadata_parser'] = function () {
            return new YamlMetadataParser();
        };
        $this['renderer'] = function () {
            return new ComponentRenderer(
                $this['engine'],
                $this['dispatcher']
            );
        };
        $this['camera'] = function () {
            return new Camera(
                $this->getManifestBuilder(),
                $this->getRenderer(),
                $this->getUrlGenerator(),
                $this->getConfig()->getUi(),
                $this['logger']
            );
        };

        $this->register(new ServiceControllerServiceProvider());
        $this['controller.static'] = function () {
            return new StaticFileController($this['ui'], $this['asset.manager']);
        };
        $this['controller.manifest'] = function () {
            return new ManifestController(
                $this['manifest.builder'],
                $this['discovery']->discover()
            );
        };
        $this['controller.render'] = function () {
            $collection = $this['discovery']->discover();

            return new RenderController(
                $collection,
                $this['renderer'],
                $this['ui']
            );
        };

        $this->get('/', 'controller.static:indexAction')->bind('index');
        $this->get('/manifest.json', 'controller.manifest:getManifestAction')
            ->bind('manifest');
        $this->get(
            '/m-render/{component}/{sample}.html',
            'controller.render:renderAction'
        )->bind('component_render');
        $this->get(
            '/m-source/raw/{component}.txt',
            'controller.render:renderSourceAction'
        )->bind('component_render_source_raw');
        $this->get(
            '/m-source/html/{component}/{sample}.txt',
            'controller.render:renderRawAction'
        )->bind('component_render_raw');
        $this->match('/{name}', 'controller.static:staticAction')
            ->bind('static')
            ->value('name', 'index.html')
            ->assert('name', '.+');
    }

    public function boot()
    {
        $this['dispatcher']->addSubscriber($this['log.listener']);
        // Guess file extensions for CSS and JS files.
        MimeTypeGuesser::getInstance()->register(
            new ExtensionMimeTypeGuesser()
        );
        foreach ($this->getExtensions() as $extension) {
            $extension->register($this);
        }
        foreach ($this->getExtensions() as $extension) {
            $extension->subscribe($this['dispatcher']);
        }

        return parent::boot();
    }

    public function getMetadataParser(): YamlMetadataParser
    {
        return $this['metadata_parser'];
    }

    public function getVariableResolver(): VariableResolver
    {
        return $this['variable.resolver'];
    }

    public function getAssetPackage(): PackageInterface
    {
        return $this['asset.package'];
    }

    public function getAssetManager(): AssetManagerInterface
    {
        return $this['asset.manager'];
    }

    public function getUrlGenerator(): UrlGeneratorInterface
    {
        return $this['url_generator'];
    }

    public function getManifestBuilder(): ManifestBuilder
    {
        return $this['manifest.builder'];
    }

    public function getDiscovery(): DiscoveryInterface
    {
        return $this['discovery'];
    }

    public function getRenderer(): ComponentRenderer
    {
        return $this['renderer'];
    }

    public function getCamera(): CameraInterface
    {
        return $this['camera'];
    }

    public function getConfig(): ConfigInterface
    {
        return $this['config'];
    }

    public function getCache(): CacheItemPoolInterface
    {
        return $this['cache'];
    }

    public function getCacheDir(): string
    {
        return $this['cache_dir'];
    }

    public function isDebug(): bool
    {
        return (bool) $this['debug'];
    }

    public function has($id)
    {
        return $this->offsetExists($id);
    }

    /**
     * @return \LastCall\Mannequin\Core\Extension\ExtensionInterface[]
     */
    private function getExtensions()
    {
        return $this['config']->getExtensions();
    }
}


text:
<?php namespace Mix359\RolesCommands\Console;

use Ultraware\Roles\Models\Permission;
use Illuminate\Console\Command;

class ListpermissionsCommand extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'roles:listpermissions';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'List the permissions in the database';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		$headers = ["Id","Name","Slug","Description"];
		$permissionModel = config('roles.models.permission');
		$permissions = $permissionModel::all(['id','name','slug','description']);
		$this->table($headers, $permissions);
	}
}


text:
Sacred Texts
Sagas and Legends
English Folklore
Index
Previous
Next

ST NEOT AND THE FOX.

 One
day the holy hermit was standing in his bath chanting the Psalms, when he
heard the sound of huntsmen approaching.

Whether the saint feared, ridicule or
ill-treatment, we know not; but certainly he left some psalms unsung that
day, and hastily gathering up his clothes, he fled to his cell.

In his haste the good man lost his shoe, and a
hungry fox having escaped the hunters, came to the spring to drink. Having
quenched the fever of thirst, and being hungry, he spied the saint's shoe, and
presently ate it. The hermit despatched his servant to look for his shoe; and,
lo, he found the fox cast into a deep sleep, and the thongs of the shoe hanging
out of his vile mouth. Of  course the shoe was pulled out of his stomach, and restored to the saint.

Next: St Neot and the Doe