text:
	#include "portal_util_shared.h"
#endif

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

// Use this to disable caching and other optimizations in senses
#define DEBUG_SENSES 1

#ifdef DEBUG_SENSES
#define AI_PROFILE_SENSES(tag) AI_PROFILE_SCOPE(tag)
#else
#define AI_PROFILE_SENSES(tag) ((void)0)
#endif

const float AI_STANDARD_NPC_SEARCH_TIME = .25;
const float AI_EFFICIENT_NPC_SEARCH_TIME = .35;
const float AI_HIGH_PRIORITY_SEARCH_TIME = 0.15;
const float AI_MISC_SEARCH_TIME  = 0.45;

//-----------------------------------------------------------------------------

CAI_SensedObjectsManager g_AI_SensedObjectsManager;

//-----------------------------------------------------------------------------

#pragma pack(push)
#pragma pack(1)

struct AISightIterVal_t
{
	char  array;
	short iNext;
	char  SeenArray;
};

#pragma pack(pop)

//=============================================================================
//
// CAI_Senses
//
//=============================================================================

BEGIN_SIMPLE_DATADESC( CAI_Senses )

	DEFINE_FIELD( m_LookDist,			FIELD_FLOAT	),
	DEFINE_FIELD( m_LastLookDist, 	FIELD_FLOAT	),
	DEFINE_FIELD( m_TimeLastLook, 	FIELD_TIME	),
	DEFINE_FIELD( m_iSensingFlags, FIELD_INTEGER ),
	//								m_iAudibleList		(no way to save?)
	DEFINE_UTLVECTOR(m_SeenHighPriority, FIELD_EHANDLE ),
	DEFINE_UTLVECTOR(m_SeenNPCs, 		FIELD_EHANDLE ),
	DEFINE_UTLVECTOR(m_SeenMisc, 		FIELD_EHANDLE ),
	//								m_SeenArrays		(not saved, rebuilt)

	// Could fold these three and above timer into one concept, but would invalidate savegames
	DEFINE_FIELD( m_TimeLastLookHighPriority, 	FIELD_TIME	),
	DEFINE_FIELD( m_TimeLastLookNPCs, 	FIELD_TIME	),
	DEFINE_FIELD( m_TimeLastLookMisc, 	FIELD_TIME	),

END_DATADESC()

//-----------------------------------------------------------------------------

bool CAI_Senses::CanHearSound( CSound *pSound )
{
	if ( pSound->m_hOwner.Get() == GetOuter() )
		return false;

	if( GetOuter()->GetState() == NPC_STATE_SCRIPT && pSound->IsSoundType( SOUND_DANGER ) )
	{
		// For now, don't hear danger in scripted sequences. This probably isn't a
		// good long term solution, but it makes the Bank Exterior work better.
		return false;
	}

	if ( GetOuter()->IsInAScript() )
		return false;

	// @TODO (toml 10-18-02): what about player sounds and notarget?
	float flHearDistanceSq = pSound->Volume() * GetOuter()->HearingSensitivity();
	flHearDistanceSq *= flHearDistanceSq;
	if( pSound->GetSoundOrigin().DistToSqr( GetOuter()->EarPosition() ) <= flHearDistanceSq )
	{
		return GetOuter()->QueryHearSound( pSound );
	}

	return false;
}

//-----------------------------------------------------------------------------
// Listen - npcs dig through the active sound list for
// any sounds that may interest them. (smells, too!)

void CAI_Senses::Listen( void )
{
	m_iAudibleList = SOUNDLIST_EMPTY;

	int iSoundMask = GetOuter()->GetSoundInterests();

	if ( iSoundMask != SOUND_NONE && !(GetOuter()->HasSpawnFlags(SF_NPC_WAIT_TILL_SEEN)) )
	{
		int	iSound = CSoundEnt::ActiveList();

		while ( iSound != SOUNDLIST_EMPTY )
		{
			CSound *pCurrentSound = CSoundEnt::SoundPointerForIndex( iSound );

			if ( pCurrentSound	&& (iSoundMask & pCurrentSound->SoundType()) && CanHearSound( pCurrentSound ) )
			{
	 			// the npc cares about this sound, and it's close enough to hear.
				pCurrentSound->m_iNextAudible = m_iAudibleList;
				m_iAudibleList = iSound;
			}

			iSound = pCurrentSound->NextSound();
		}
	}

	GetOuter()->OnListened();
}

//-----------------------------------------------------------------------------

bool CAI_Senses::ShouldSeeEntity( CBaseEntity *pSightEnt )
{
	if ( pSightEnt == GetOuter() || !pSightEnt->IsAlive() )
		return false;

	if ( pSightEnt->IsPlayer() && ( pSightEnt->GetFlags() & FL_NOTARGET ) )
		return false;

	// don't notice anyone waiting to be seen by the player
	if ( pSightEnt->m_spawnflags & SF_NPC_WAIT_TILL_SEEN )
		return false;

	if ( !pSightEnt->CanBeSeenBy( GetOuter() ) )
		return false;

	if ( !GetOuter()->QuerySeeEntity( pSightEnt, true ) )
		return false;

	return true;
}

//-----------------------------------------------------------------------------

bool CAI_Senses::CanSeeEntity( CBaseEntity *pSightEnt )
{
	return ( GetOuter()->FInViewCone( pSightEnt ) && GetOuter()->FVisible( pSightEnt ) );
}

#ifdef PORTAL
bool CAI_Senses::CanSeeEntityThroughPortal( const CProp_Portal *pPortal, CBaseEntity *pSightEnt )
{
	return GetOuter()->FVisibleThroughPortal( pPortal, pSightEnt );
}
#endif

//-----------------------------------------------------------------------------

bool CAI_Senses::DidSeeEntity( CBaseEntity *pSightEnt ) const
{
	AISightIter_t iter;
	CBaseEntity *pTestEnt;

	pTestEnt = GetFirstSeenEntity( &iter );

	while( pTestEnt )
	{
		if ( pSightEnt == pTestEnt )
			return true;
		pTestEnt = GetNextSeenEntity( &iter );
	}
	return false;
}

//-----------------------------------------------------------------------------

void CAI_Senses::NoteSeenEntity( CBaseEntity *pSightEnt )
{
	pSightEnt->m_pLink = GetOuter()->m_pLink;
	GetOuter()->m_pLink = pSightEnt;
}

//-----------------------------------------------------------------------------

bool CAI_Senses::WaitingUntilSeen( CBaseEntity *pSightEnt )
{
	if ( GetOuter()->m_spawnflags & SF_NPC_WAIT_TILL_SEEN )
	{
		if ( pSightEnt->IsPlayer() )
		{
			CBasePlayer *pPlayer = ToBasePlayer( pSightEnt );
			Vector zero =  Vector(0,0,0);
			// don't link this client in the list if the npc is wait till seen and the player isn't facing the npc
			if ( pPlayer
				// && pPlayer->FVisible( GetOuter() )
				&& pPlayer->FInViewCone( GetOuter() )
				&& FBoxVisible( pSightEnt, static_cast<CBaseEntity*>(GetOuter()), zero ) )
			{
				// player sees us, become normal now.
				GetOuter()->m_spawnflags &= ~SF_NPC_WAIT_TILL_SEEN;
				return false;
			}
		}
		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------

bool CAI_Senses::SeeEntity( CBaseEntity *pSightEnt )
{
	GetOuter()->OnSeeEntity( pSightEnt );

	// insert at the head of my sight list
	NoteSeenEntity( pSightEnt );

	return true;
}

//-----------------------------------------------------------------------------

CBaseEntity *CAI_Senses::GetFirstSeenEntity( AISightIter_t *pIter, seentype_t iSeenType ) const
{
	COMPILE_TIME_ASSERT( sizeof( AISightIter_t ) == sizeof( AISightIterVal_t ) );

	AISightIterVal_t *pIterVal = (AISightIterVal_t *)pIter;

	// If we're searching for a specific type, start in that array
	pIterVal->SeenArray = (char)iSeenType;
	int iFirstArray = ( iSeenType == SEEN_ALL ) ? 0 : iSeenType;

	for ( int i = iFirstArray; i < ARRAYSIZE( m_SeenArrays ); i++ )
	{
		if ( m_SeenArrays[i]->Count() != 0 )
		{
			pIterVal->array = i;
			pIterVal->iNext = 1;
			return (*m_SeenArrays[i])[0];
		}
	}

	(*pIter) = (AISightIter_t)(-1);
	return NULL;
}

//-----------------------------------------------------------------------------

CBaseEntity *CAI_Senses::GetNextSeenEntity( AISightIter_t *pIter ) const
{
	if ( ((int)*pIter) != -1 )
	{
		AISightIterVal_t *pIterVal = (AISightIterVal_t *)pIter;

		for ( int i = pIterVal->array;  i < ARRAYSIZE( m_SeenArrays ); i++ )
		{
			for ( int j = pIterVal->iNext; j < m_SeenArrays[i]->Count(); j++ )
			{
				if ( (*m_SeenArrays[i])[j].Get() != NULL )
				{
					pIterVal->array = i;
					pIterVal->iNext = j+1;
					return (*m_SeenArrays[i])[j];
				}
			}
			pIterVal->iNext = 0;

			// If we're searching for a specific type, don't move to the next array
			if ( pIterVal->SeenArray != SEEN_ALL )
				break;
		}
		(*pIter) = (AISightIter_t)(-1);
	}
	return NULL;
}

//-----------------------------------------------------------------------------

void CAI_Senses::BeginGather()
{
	// clear my sight list
	GetOuter()->m_pLink = NULL;
}

//-----------------------------------------------------------------------------

void CAI_Senses::EndGather( int nSeen, CUtlVector<EHANDLE> *pResult )
{
	pResult->SetCount( nSeen );
	if ( nSeen )
	{
		CBaseEntity *pCurrent = GetOuter()->m_pLink;
		for (int i = 0; i < nSeen; i++ )
		{
			Assert( pCurrent );
			(*pResult)[i].Set( pCurrent );
			pCurrent = pCurrent->m_pLink;
		}
		GetOuter()->m_pLink = NULL;
	}
}

//-----------------------------------------------------------------------------
// Look - Base class npc function to find enemies or
// food by sight. iDistance is distance ( in units ) that the
// npc can see.
//
// Sets the sight bits of the m_afConditions mask to indicate
// which types of entities were sighted.
// Function also sets the Looker's m_pLink
// to the head of a link list that contains all visible ents.
// (linked via each ent's m_pLink field)
//

void CAI_Senses::Look( int iDistance )
{
	if ( m_TimeLastLook != gpGlobals->curtime || m_LastLookDist != iDistance )
	{
		//-----------------------------

		LookForHighPriorityEntities( iDistance );
		LookForNPCs( iDistance);
		LookForObjects( iDistance );

		//-----------------------------

		m_LastLookDist = iDistance;
		m_TimeLastLook = gpGlobals->curtime;
	}

	GetOuter()->OnLooked( iDistance );
}

//-----------------------------------------------------------------------------

bool CAI_Senses::Look( CBaseEntity *pSightEnt )
{
	if ( WaitingUntilSeen( pSightEnt ) )
		return false;

	if ( ShouldSeeEntity( pSightEnt ) && CanSeeEntity( pSightEnt ) )
	{
		return SeeEntity( pSightEnt );
	}
	return false;
}

#ifdef PORTAL
bool CAI_Senses::LookThroughPortal( const CProp_Portal *pPortal, CBaseEntity *pSightEnt )
{
	if ( WaitingUntilSeen( pSightEnt ) )
		return false;

	if ( ShouldSeeEntity( pSightEnt ) && CanSeeEntityThroughPortal( pPortal, pSightEnt ) )
	{
		return SeeEntity( pSightEnt );
	}
	return false;
}
#endif

//-----------------------------------------------------------------------------

int CAI_Senses::LookForHighPriorityEntities( int iDistance )
{
	int nSeen = 0;
	if ( gpGlobals->curtime - m_TimeLastLookHighPriority > AI_HIGH_PRIORITY_SEARCH_TIME )
	{
		AI_PROFILE_SENSES(CAI_Senses_LookForHighPriorityEntities);
		m_TimeLastLookHighPriority = gpGlobals->curtime;

		BeginGather();

		float distSq = ( iDistance * iDistance );
		const Vector &origin = GetAbsOrigin();

		// Players
		for ( int i = 1; i <= gpGlobals->maxClients; i++ )
		{
			CBaseEntity *pPlayer = UTIL_PlayerByIndex( i );

			if ( pPlayer )
			{
				if ( origin.DistToSqr(pPlayer->GetAbsOrigin()) < distSq && Look( pPlayer ) )
				{
					nSeen++;
				}
#ifdef PORTAL
				else
				{
					CProp_Portal *pPortal = GetOuter()->FInViewConeThroughPortal( pPlayer );
					if ( pPortal && UTIL_Portal_DistanceThroughPortalSqr( pPortal, origin, pPlayer->GetAbsOrigin() ) < distSq && LookThroughPortal( pPortal, pPlayer ) )
					{
						nSeen++;
					}
				}
#endif
			}
		}

		EndGather( nSeen, &m_SeenHighPriority );
    }
    else
    {
    	for ( int i = m_SeenHighPriority.Count() - 1; i >= 0; --i )
    	{
    		if ( m_SeenHighPriority[i].Get() == NULL )
    			m_SeenHighPriority.FastRemove( i );
    	}
    	nSeen = m_SeenHighPriority.Count();
    }

	return nSeen;
}

//-----------------------------------------------------------------------------

int CAI_Senses::LookForNPCs( int iDistance )
{
	bool bRemoveStaleFromCache = false;
	float distSq = ( iDistance * iDistance );
	const Vector &origin = GetAbsOrigin();
	AI_Efficiency_t efficiency = GetOuter()->GetEfficiency();
	float timeNPCs = ( efficiency < AIE_VERY_EFFICIENT ) ? AI_STANDARD_NPC_SEARCH_TIME : AI_EFFICIENT_NPC_SEARCH_TIME;
	if ( gpGlobals->curtime - m_TimeLastLookNPCs > timeNPCs )
	{
		AI_PROFILE_SENSES(CAI_Senses_LookForNPCs);

		m_TimeLastLookNPCs = gpGlobals->curtime;

		if ( efficiency < AIE_SUPER_EFFICIENT )
		{
			int i, nSeen = 0;

			BeginGather();

			CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs();

			for ( i = 0; i < g_AI_Manager.NumAIs(); i++ )
			{
				if ( ppAIs[i] != GetOuter() && ( ppAIs[i]->ShouldNotDistanceCull() || origin.DistToSqr(ppAIs[i]->GetAbsOrigin()) < distSq ) )
				{
					if ( Look( ppAIs[i] ) )
					{
						nSeen++;
					}
				}
			}

			EndGather( nSeen, &m_SeenNPCs );

			return nSeen;
		}

		bRemoveStaleFromCache = true;
		// Fall through
	}

    for ( int i = m_SeenNPCs.Count() - 1; i >= 0; --i )
    {
    	if ( m_SeenNPCs[i].Get() == NULL )
		{
    		m_SeenNPCs.FastRemove( i );
		}
		else if ( bRemoveStaleFromCache )
		{
			if ( ( !((CAI_BaseNPC *)m_SeenNPCs[i].Get())->ShouldNotDistanceCull() &&
				   origin.DistToSqr(m_SeenNPCs[i]->GetAbsOrigin()) > distSq ) ||
				 !Look( m_SeenNPCs[i] ) )
			{
	    		m_SeenNPCs.FastRemove( i );
			}
		}
    }

    return m_SeenNPCs.Count();
}

//-----------------------------------------------------------------------------

int CAI_Senses::LookForObjects( int iDistance )
{
	const int BOX_QUERY_MASK = FL_OBJECT;
	int	nSeen = 0;

	if ( gpGlobals->curtime - m_TimeLastLookMisc > AI_MISC_SEARCH_TIME )
	{
		AI_PROFILE_SENSES(CAI_Senses_LookForObjects);
		m_TimeLastLookMisc = gpGlobals->curtime;

		BeginGather();

		float distSq = ( iDistance * iDistance );
		const Vector &origin = GetAbsOrigin();
		int iter;
		CBaseEntity *pEnt = g_AI_SensedObjectsManager.GetFirst( &iter );
		while ( pEnt )
		{
			if ( pEnt->GetFlags() & BOX_QUERY_MASK )
			{
				if ( origin.DistToSqr(pEnt->GetAbsOrigin()) < distSq && Look( pEnt) )
				{
					nSeen++;
				}
			}
			pEnt = g_AI_SensedObjectsManager.GetNext( &iter );
		}

		EndGather( nSeen, &m_SeenMisc );
	}
    else
    {
    	for ( int i = m_SeenMisc.Count() - 1; i >= 0; --i )
    	{
    		if ( m_SeenMisc[i].Get() == NULL )
    			m_SeenMisc.FastRemove( i );
    	}
    	nSeen = m_SeenMisc.Count();
    }

	return nSeen;
}

//-----------------------------------------------------------------------------

float CAI_Senses::GetTimeLastUpdate( CBaseEntity *pEntity )
{
	if ( !pEntity )
		return 0;
	if ( pEntity->IsPlayer() )
		return m_TimeLastLookHighPriority;
	if ( pEntity->IsNPC() )
		return m_TimeLastLookNPCs;
	return m_TimeLastLookMisc;
}

//-----------------------------------------------------------------------------

CSound* CAI_Senses::GetFirstHeardSound( AISoundIter_t *pIter )
{
	int iFirst = GetAudibleList();

	if ( iFirst == SOUNDLIST_EMPTY )
	{
		*pIter = NULL;
		return NULL;
	}

	*pIter = (AISoundIter_t)iFirst;
	return CSoundEnt::SoundPointerForIndex( iFirst );
}

//-----------------------------------------------------------------------------

CSound* CAI_Senses::GetNextHeardSound( AISoundIter_t *pIter )
{
	if ( !*pIter )
		return NULL;

	int iCurrent = (int)*pIter;

	Assert( iCurrent != SOUNDLIST_EMPTY );
	if ( iCurrent == SOUNDLIST_EMPTY )
	{
		*pIter = NULL;
		return NULL;
	}

	iCurrent = CSoundEnt::SoundPointerForIndex( iCurrent )->m_iNextAudible;
	if ( iCurrent == SOUNDLIST_EMPTY )
	{
		*pIter = NULL;
		return NULL;
	}

	*pIter = (AISoundIter_t)iCurrent;
	return CSoundEnt::SoundPointerForIndex( iCurrent );
}

//-----------------------------------------------------------------------------

CSound *CAI_Senses::GetClosestSound( bool fScent, int validTypes, bool bUsePriority )
{
	float flBestDist = MAX_COORD_RANGE*MAX_COORD_RANGE;// so first nearby sound will become best so far.
	float flDist;
	int iBestPriority = SOUND_PRIORITY_VERY_LOW;

	AISoundIter_t iter;

	CSound *pResult = NULL;
	CSound *pCurrent = GetFirstHeardSound( &iter );

	Vector earPosition = GetOuter()->EarPosition();

	while ( pCurrent )
	{
		if ( ( !fScent && pCurrent->FIsSound() ) ||
			 ( fScent && pCurrent->FIsScent() ) )
		{
			if( pCurrent->IsSoundType( validTypes ) && !GetOuter()->ShouldIgnoreSound( pCurrent ) )
			{
				if( !bUsePriority || GetOuter()->GetSoundPriority(pCurrent) >= iBestPriority )
				{
					flDist = ( pCurrent->GetSoundOrigin() - earPosition ).LengthSqr();

					if ( flDist < flBestDist )
					{
						pResult = pCurrent;
						flBestDist = flDist;

						iBestPriority = GetOuter()->GetSoundPriority(pCurrent);
					}
				}
			}
		}

		pCurrent = GetNextHeardSound( &iter );
	}

	return pResult;
}

//-----------------------------------------------------------------------------

void CAI_Senses::PerformSensing( void )
{
	AI_PROFILE_SCOPE	(CAI_BaseNPC_PerformSensing);

	// -----------------
	//  Look
	// -----------------
	if( !HasSensingFlags(SENSING_FLAGS_DONT_LOOK) )
		Look( m_LookDist );

	// ------------------
	//  Listen
	// ------------------
	if( !HasSensingFlags(SENSING_FLAGS_DONT_LISTEN) )
		Listen();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void CAI_SensedObjectsManager::Init()
{
	CBaseEntity *pEnt = NULL;
	while ( ( pEnt = gEntList.NextEnt( pEnt ) ) != NULL )
	{
		OnEntitySpawned( pEnt );
	}

	gEntList.AddListenerEntity( this );
}

//-----------------------------------------------------------------------------

void CAI_SensedObjectsManager::Term()
{
	gEntList.RemoveListenerEntity( this );
	m_SensedObjects.RemoveAll();
}

//-----------------------------------------------------------------------------

CBaseEntity *CAI_SensedObjectsManager::GetFirst( int *pIter )
{
	if ( m_SensedObjects.Count() )
	{
		*pIter = 1;
		return m_SensedObjects[0];
	}

	*pIter = 0;
	return NULL;
}

//-----------------------------------------------------------------------------

CBaseEntity *CAI_SensedObjectsManager::GetNext( int *pIter )
{
	int i = *pIter;
	if ( i && i < m_SensedObjects.Count() )
	{
		(*pIter)++;
		return m_SensedObjects[i];
	}

	*pIter = 0;
	return NULL;
}

//-----------------------------------------------------------------------------

void CAI_SensedObjectsManager::OnEntitySpawned( CBaseEntity *pEntity )
{
	if ( ( pEntity->GetFlags() & FL_OBJECT ) && !pEntity->IsPlayer() && !pEntity->IsNPC() )
	{
		m_SensedObjects.AddToTail( pEntity );
	}
}

//-----------------------------------------------------------------------------

void CAI_SensedObjectsManager::OnEntityDeleted( CBaseEntity *pEntity )
{
	if ( ( pEntity->GetFlags() & FL_OBJECT ) && !pEntity->IsPlayer() && !pEntity->IsNPC() )
	{
		int i = m_SensedObjects.Find( pEntity );
		if ( i != m_SensedObjects.InvalidIndex() )
			m_SensedObjects.FastRemove( i );
	}
}

void CAI_SensedObjectsManager::AddEntity( CBaseEntity *pEntity )
{
	if ( m_SensedObjects.Find( pEntity ) != m_SensedObjects.InvalidIndex() )
		return;

	// We shouldn't be adding players or NPCs to this list
	Assert( !pEntity->IsPlayer() && !pEntity->IsNPC() );

	// Add the object flag so it gets removed when it dies
	pEntity->AddFlag( FL_OBJECT );
	m_SensedObjects.AddToTail( pEntity );
}

//=============================================================================


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/**
 * @var yii\web\View $this
 * @var common\models\User $model
 * @var yii\widgets\ActiveForm $form
 */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'status_id')->dropDownList($model->statusList, [ 'prompt' => 'Выберите статус' ]);?>

    <?= $form->field($model, 'role_id')->dropDownList($model->roleList, [ 'prompt' => 'Выберите роль' ]);?>

    <?= $form->field($model, 'user_type_id')->dropDownList($model->userTypeList, [ 'prompt' => 'Выберите тип' ]);?>

    <?= $form->field($model, 'username')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => 255]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Создать' : 'Редактировать',
            ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

redpajama_set_name: RedPajamaGithub


text:
@extends('vi-kon.bootstrap::modal.modal')

<?php $onlyContent = true ?>

@section('title')

    @lang('wiki::auth/login.modal.login.title')
@overwrite

@section('body')

        @lang('wiki::auth/login.modal.login.form.alert.success.content')

@overwrite

@section('append')

@append


text:
package org.apache.syncope.core.persistence.jpa.dao;

import java.util.List;
import javax.persistence.TypedQuery;
import org.apache.syncope.common.lib.types.TaskType;
import org.apache.syncope.core.persistence.api.dao.NotificationDAO;
import org.apache.syncope.core.persistence.api.dao.TaskDAO;
import org.apache.syncope.core.persistence.api.entity.Implementation;
import org.apache.syncope.core.persistence.api.entity.MailTemplate;
import org.apache.syncope.core.persistence.api.entity.Notification;
import org.apache.syncope.core.persistence.api.entity.task.Task;
import org.apache.syncope.core.persistence.jpa.entity.JPANotification;
import org.springframework.transaction.annotation.Transactional;

public class JPANotificationDAO extends AbstractDAO<Notification> implements NotificationDAO {

    protected final TaskDAO taskDAO;

    public JPANotificationDAO(final TaskDAO taskDAO) {
        this.taskDAO = taskDAO;
    }

    @Transactional(readOnly = true)
    @Override
    public Notification find(final String key) {
        return entityManager().find(JPANotification.class, key);
    }

    @Transactional(readOnly = true)
    @Override
    public List<Notification> findByTemplate(final MailTemplate template) {
        TypedQuery<Notification> query = entityManager().createQuery(
                "SELECT e FROM " + JPANotification.class.getSimpleName() + " e "
                + "WHERE e.template=:template", Notification.class);
        query.setParameter("template", template);
        return query.getResultList();
    }

    @Override
    public List<Notification> findByRecipientsProvider(final Implementation recipientsProvider) {
        TypedQuery<Notification> query = entityManager().createQuery(
                "SELECT e FROM " + JPANotification.class.getSimpleName()
                + " e WHERE e.recipientsProvider=:recipientsProvider", Notification.class);
        query.setParameter("recipientsProvider", recipientsProvider);

        return query.getResultList();
    }

    @Transactional(readOnly = true)
    @Override
    public List<Notification> findAll() {
        TypedQuery<Notification> query = entityManager().createQuery(
                "SELECT e FROM " + JPANotification.class.getSimpleName() + " e", Notification.class);
        return query.getResultList();
    }

    @Override
    public Notification save(final Notification notification) {
        ((JPANotification) notification).list2json();
        return entityManager().merge(notification);
    }

    @Override
    public void delete(final String key) {
        Notification notification = find(key);
        if (notification == null) {
            return;
        }

        taskDAO.findAll(
                TaskType.NOTIFICATION, null, notification, null, null, -1, -1, List.of()).
                stream().map(Task::getKey).forEach(this::delete);

        entityManager().remove(notification);
    }
}


text:
CREATE TABLE IF NOT EXISTS `{{ index .Options "Namespace" }}instances` (
  `id` varchar(255) NOT NULL,
  `uuid` varchar(255) DEFAULT NULL,
  `raw_base_config` longtext,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
package org.gradle.platform.base.internal;

import org.gradle.platform.base.BinarySpec;

public interface BinarySpecInternal extends BinarySpec {
    BinaryNamingScheme getNamingScheme();

    boolean isLegacyBinary();
}


text:
<?php namespace Schickling\Backup\Databases;

use Schickling\Backup\Console;

class SqliteDatabase implements DatabaseInterface
{
	protected $console;
	protected $databaseFile;

	public function __construct(Console $console, $databaseFile)
	{
		$this->console = $console;
		$this->databaseFile = $databaseFile;
	}

	public function dump($destinationFile)
	{
		$command = sprintf('cp %s %s',
			escapeshellarg($this->databaseFile),
			escapeshellarg($destinationFile)
		);

		return $this->console->run($command);
	}

	public function restore($sourceFile)
	{
		$command = sprintf('cp -f %s %s',
			escapeshellarg($sourceFile),
			escapeshellarg($this->databaseFile)
		);

		return $this->console->run($command);
	}

	public function getFileExtension()
	{
		return 'sqlite';
	}
}


text:
package org.outburstframework.runner;

import static org.junit.Assert.assertEquals;

import org.apache.commons.cli.CommandLine;
import org.junit.Before;
import org.junit.Test;
import org.outburstframework.runner.ui.cli.CommandLineOptions;

public class CommandLineOptionsTest {

	private CommandLineOptions commandLineOptions;
	private CommandLine options;

	@Before
	public void setUp()
	{
		String[] args=new String[] {
			"-t=org.outburstframework.runner.CommandLineOptionsTest",
			"-r=1000"
		};

		commandLineOptions = new CommandLineOptions();
		options = commandLineOptions.parseOptions(args);
	}

	@Test
	public void testPrintHelp() {
		commandLineOptions.printHelp();
	}

	@Test
	public void testParameter()
	{
		assertEquals("org.outburstframework.runner.CommandLineOptionsTest", options.getOptionValue("t"));
	}

}


text:
import type { Prisma } from '@dg/api/server/generated';
import stravaClient from '@dg/api/server/networkClients/stravaClient';
import type { StravaDetailedActivity } from '@dg/api/types/StravaDetailedActivity';
import paredStravaActivity from './paredStravaActivity';

/**
 * Fetches an activity id from Strava's API. Use sparingly! Cuts into small API
 * budget. When in doubt, fall back to DB.
 */
const fetchStravaActivityFromApi = async (id: number) => {
  const activity = await stravaClient.fetch<StravaDetailedActivity & Prisma.JsonObject>(
    `activities/${id}`,
  );
  if (activity.status !== 200) {
    return null;
  }
  const allData = await activity.json();
  return paredStravaActivity(allData);
};

export default fetchStravaActivityFromApi;


text:
A template-based, LLVM-enabled pretty-printer.

# Usage

Include `repr.hpp` in your project and use the template function `repr()` to
convert anything into an `std::string`. If you include the file after any
LLVM header it will support LLVM classes automagically.

# Features

 * Uses a set of heuristics to find a good human-readable representation.
 * Supports all containers that implement `begin()` and `end()`.
 * Prints label names of LLVM basic blocks instead of their contents.
 * Will work on anything that implements an `ostream` or `llvm::raw_ostream`
   `operator<<`.
 * Automatically follows pointers (including smart pointers) but doesn't
   dereference null pointers (prints `nullptr` instead).
 * Prints containers of characters like strings, this supporting many of the
   different crazy string-like objects.
 * Can be also used in non-LLVM projects.

# Example

Following C++14 code:

```cpp
#include <vector>
#include <map>
#include <memory>
#include <repr.hpp>

int main()
{
    std::map<const char*, std::unique_ptr<std::vector<int>>> stl_madness;
    (void)stl_madness["empty"];
    auto uptr = std::make_unique<std::vector<int>>();
    uptr->push_back(1);
    uptr->push_back(2);
    uptr->push_back(3);
    stl_madness["one_two_three"] = std::move(uptr);
    std::cout << repr(stl_madness) << std::endl;
}
```

prints:

```
{"empty": nullptr, "one_two_three": [1, 2, 3]}
```


text:
package com.android.grafika;

import android.graphics.SurfaceTexture;
import android.opengl.EGLContext;
import android.opengl.GLES20;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.android.grafika.gles.EglCore;
import com.android.grafika.gles.FullFrameRect;
import com.android.grafika.gles.Texture2dProgram;
import com.android.grafika.gles.WindowSurface;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * Encode a movie from frames rendered from an external texture image.
 *

 * The object wraps an encoder running on a dedicated thread.  The various control messages
 * may be sent from arbitrary threads (typically the app UI thread).  The encoder thread
 * manages both sides of the encoder (feeding and draining); the only external input is
 * the GL texture.
 *

 * The design is complicated slightly by the need to create an EGL context that shares state
 * with a view that gets restarted if (say) the device orientation changes.  When the view
 * in question is a GLSurfaceView, we don't have full control over the EGL context creation
 * on that side, so we have to bend a bit backwards here.
 *

 * To use:
 *

 *
create TextureMovieEncoder object
 *
create an EncoderConfig
 *
call TextureMovieEncoder#startRecording() with the config
 *
call TextureMovieEncoder#setTextureId() with the texture object that receives frames
 *
for each frame, after latching it with SurfaceTexture#updateTexImage(),
 *     call TextureMovieEncoder#frameAvailable().
 *

 *
 * TODO: tweak the API (esp. textureId) so it's less awkward for simple use cases.
 */
public class TextureMovieEncoder implements Runnable {
    private static final String TAG = MainActivity.TAG;
    private static final boolean VERBOSE = false;

    private static final int MSG_START_RECORDING = 0;
    private static final int MSG_STOP_RECORDING = 1;
    private static final int MSG_FRAME_AVAILABLE = 2;
    private static final int MSG_SET_TEXTURE_ID = 3;
    private static final int MSG_UPDATE_SHARED_CONTEXT = 4;
    private static final int MSG_QUIT = 5;

    // ----- accessed exclusively by encoder thread -----
    protected WindowSurface mInputWindowSurface;
    protected EglCore mEglCore;
    protected FullFrameRect mFullScreen;
    protected int mTextureId;
    protected int mFrameNum;
    protected VideoEncoderCore mVideoEncoder;

    // ----- accessed by multiple threads -----
    protected volatile EncoderHandler mHandler;

    private Object mReadyFence = new Object();      // guards ready/running
    private boolean mReady;
    private boolean mRunning;

    /**
     * Encoder configuration.
     *

     * Object is immutable, which means we can safely pass it between threads without
     * explicit synchronization (and don't need to worry about it getting tweaked out from
     * under us).
     *

     * TODO: make frame rate and iframe interval configurable?  Maybe use builder pattern
     *       with reasonable defaults for those and bit rate.
     */
    public static class EncoderConfig {
        final File mOutputFile;
        final int mWidth;
        final int mHeight;
        final int mBitRate;
        final EGLContext mEglContext;

        public EncoderConfig(File outputFile, int width, int height, int bitRate,
                EGLContext sharedEglContext) {
            mOutputFile = outputFile;
            mWidth = width;
            mHeight = height;
            mBitRate = bitRate;
            mEglContext = sharedEglContext;
        }

        @Override
        public String toString() {
            return "EncoderConfig: " + mWidth + "x" + mHeight + " @" + mBitRate +
                    " to '" + mOutputFile.toString() + "' ctxt=" + mEglContext;
        }
    }

    /**
     * Tells the video recorder to start recording.  (Call from non-encoder thread.)
     *

     * Creates a new thread, which will create an encoder using the provided configuration.
     *

     * Returns after the recorder thread has started and is ready to accept Messages.  The
     * encoder may not yet be fully configured.
     */
    public void startRecording(EncoderConfig config) {
        Log.d(TAG, "Encoder: startRecording()");
        synchronized (mReadyFence) {
            if (mRunning) {
                Log.w(TAG, "Encoder thread already running");
                return;
            }
            mRunning = true;
            new Thread(this, "TextureMovieEncoder").start();
            while (!mReady) {
                try {
                    mReadyFence.wait();
                } catch (InterruptedException ie) {
                    // ignore
                }
            }
        }

        mHandler.sendMessage(mHandler.obtainMessage(MSG_START_RECORDING, config));
    }

    /**
     * Tells the video recorder to stop recording.  (Call from non-encoder thread.)
     *

     * Returns immediately; the encoder/muxer may not yet be finished creating the movie.
     *

     * TODO: have the encoder thread invoke a callback on the UI thread just before it shuts down
     * so we can provide reasonable status UI (and let the caller know that movie encoding
     * has completed).
     */
    public void stopRecording() {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_STOP_RECORDING));
        mHandler.sendMessage(mHandler.obtainMessage(MSG_QUIT));
        // We don't know when these will actually finish (or even start).  We don't want to
        // delay the UI thread though, so we return immediately.
    }

    /**
     * Returns true if recording has been started.
     */
    public boolean isRecording() {
        synchronized (mReadyFence) {
            return mRunning;
        }
    }

    /**
     * Tells the video recorder to refresh its EGL surface.  (Call from non-encoder thread.)
     */
    public void updateSharedContext(EGLContext sharedContext) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_SHARED_CONTEXT, sharedContext));
    }

    /**
     * Tells the video recorder that a new frame is available.  (Call from non-encoder thread.)
     *

     * This function sends a message and returns immediately.  This isn't sufficient -- we
     * don't want the caller to latch a new frame until we're done with this one -- but we
     * can get away with it so long as the input frame rate is reasonable and the encoder
     * thread doesn't stall.
     *

     * TODO: either block here until the texture has been rendered onto the encoder surface,
     * or have a separate "block if still busy" method that the caller can execute immediately
     * before it calls updateTexImage().  The latter is preferred because we don't want to
     * stall the caller while this thread does work.
     */
    public void frameAvailable(SurfaceTexture st) {
        synchronized (mReadyFence) {
            if (!mReady) {
                return;
            }
        }

        float[] transform = new float[16];      // TODO - avoid alloc every frame
        st.getTransformMatrix(transform);
        long timestamp = st.getTimestamp();
        if (timestamp == 0) {
            // Seeing this after device is toggled off/on with power button.  The
            // first frame back has a zero timestamp.
            //
            // MPEG4Writer thinks this is cause to abort() in native code, so it's very
            // important that we just ignore the frame.
            Log.w(TAG, "HEY: got SurfaceTexture with timestamp of zero");
            return;
        }

        mHandler.sendMessage(mHandler.obtainMessage(MSG_FRAME_AVAILABLE,
                (int) (timestamp >> 32), (int) timestamp, transform));
    }

    /**
     * Tells the video recorder what texture name to use.  This is the external texture that
     * we're receiving camera previews in.  (Call from non-encoder thread.)
     *

     * TODO: do something less clumsy
     */
    public void setTextureId(int id) {
        synchronized (mReadyFence) {
            if (!mReady) {
                return;
            }
        }
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TEXTURE_ID, id, 0, null));
    }

    /**
     * Encoder thread entry point.  Establishes Looper/Handler and waits for messages.
     *

     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // Establish a Looper for this thread, and define a Handler for it.
        Looper.prepare();
        synchronized (mReadyFence) {
            mHandler = new EncoderHandler(this);
            mReady = true;
            mReadyFence.notify();
        }
        Looper.loop();

        Log.d(TAG, "Encoder thread exiting");
        synchronized (mReadyFence) {
            mReady = mRunning = false;
            mHandler = null;
        }
    }

    /**
     * Handles encoder state change requests.  The handler is created on the encoder thread.
     */
    protected static class EncoderHandler extends Handler {
        private WeakReference<TextureMovieEncoder> mWeakEncoder;

        public EncoderHandler(TextureMovieEncoder encoder) {
            mWeakEncoder = new WeakReference<TextureMovieEncoder>(encoder);
        }

        @Override  // runs on encoder thread
        public void handleMessage(Message inputMessage) {
            int what = inputMessage.what;
            Object obj = inputMessage.obj;

            TextureMovieEncoder encoder = mWeakEncoder.get();
            if (encoder == null) {
                Log.w(TAG, "EncoderHandler.handleMessage: encoder is null");
                return;
            }

            switch (what) {
                case MSG_START_RECORDING:
                    encoder.handleStartRecording((EncoderConfig) obj);
                    break;
                case MSG_STOP_RECORDING:
                    encoder.handleStopRecording();
                    break;
                case MSG_FRAME_AVAILABLE:
                    long timestamp = (((long) inputMessage.arg1) << 32) |
                            (((long) inputMessage.arg2) & 0xffffffffL);
                    encoder.handleFrameAvailable((float[]) obj, timestamp);
                    break;
                case MSG_SET_TEXTURE_ID:
                    encoder.handleSetTexture(inputMessage.arg1);
                    break;
                case MSG_UPDATE_SHARED_CONTEXT:
                    encoder.handleUpdateSharedContext((EGLContext) inputMessage.obj);
                    break;
                case MSG_QUIT:
                    Looper.myLooper().quit();
                    break;
                default:
                    throw new RuntimeException("Unhandled msg what=" + what);
            }
        }
    }

    /**
     * Starts recording.
     */
    private void handleStartRecording(EncoderConfig config) {
        Log.d(TAG, "handleStartRecording " + config);
        mFrameNum = 0;
        prepareEncoder(config.mEglContext, config.mWidth, config.mHeight, config.mBitRate,
                config.mOutputFile);
    }

    /**
     * Handles notification of an available frame.
     *

     * The texture is rendered onto the encoder's input surface, along with a moving
     * box (just because we can).
     *

     * @param transform The texture transform, from SurfaceTexture.
     * @param timestampNanos The frame's timestamp, from SurfaceTexture.
     */
    protected void handleFrameAvailable(float[] transform, long timestampNanos) {
        if (VERBOSE) Log.d(TAG, "handleFrameAvailable tr=" + transform);
        mVideoEncoder.drainEncoder(false);
        mFullScreen.drawFrame(mTextureId, transform);

        drawBox(mFrameNum++);

        mInputWindowSurface.setPresentationTime(timestampNanos);
        mInputWindowSurface.swapBuffers();
    }

    /**
     * Handles a request to stop encoding.
     */
    protected void handleStopRecording() {
        Log.d(TAG, "handleStopRecording");
        mVideoEncoder.drainEncoder(true);
        releaseEncoder();
    }

    /**
     * Sets the texture name that SurfaceTexture will use when frames are received.
     */
    private void handleSetTexture(int id) {
        //Log.d(TAG, "handleSetTexture " + id);
        mTextureId = id;
    }

    /**
     * Tears down the EGL surface and context we've been using to feed the MediaCodec input
     * surface, and replaces it with a new one that shares with the new context.
     *

     * This is useful if the old context we were sharing with went away (maybe a GLSurfaceView
     * that got torn down) and we need to hook up with the new one.
     */
    private void handleUpdateSharedContext(EGLContext newSharedContext) {
        Log.d(TAG, "handleUpdatedSharedContext " + newSharedContext);

        // Release the EGLSurface and EGLContext.
        mInputWindowSurface.releaseEglSurface();
        mFullScreen.release(false);
        mEglCore.release();

        // Create a new EGLContext and recreate the window surface.
        mEglCore = new EglCore(newSharedContext, EglCore.FLAG_RECORDABLE);
        mInputWindowSurface.recreate(mEglCore);
        mInputWindowSurface.makeCurrent();

        // Create new programs and such for the new context.
        mFullScreen = new FullFrameRect(
                new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT));
    }

    private void prepareEncoder(EGLContext sharedContext, int width, int height, int bitRate,
            File outputFile) {
        try {
            mVideoEncoder = new VideoEncoderCore(width, height, bitRate, outputFile);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        mEglCore = new EglCore(sharedContext, EglCore.FLAG_RECORDABLE);
        mInputWindowSurface = new WindowSurface(mEglCore, mVideoEncoder.getInputSurface(), true);
        mInputWindowSurface.makeCurrent();

        mFullScreen = new FullFrameRect(
                new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT));
    }

    private void releaseEncoder() {
        mVideoEncoder.release();
        if (mInputWindowSurface != null) {
            mInputWindowSurface.release();
            mInputWindowSurface = null;
        }
        if (mFullScreen != null) {
            mFullScreen.release(false);
            mFullScreen = null;
        }
        if (mEglCore != null) {
            mEglCore.release();
            mEglCore = null;
        }
    }

    /**
     * Draws a box, with position offset.
     */
    private void drawBox(int posn) {
        final int width = mInputWindowSurface.getWidth();
        int xpos = (posn * 4) % (width - 50);
        GLES20.glEnable(GLES20.GL_SCISSOR_TEST);
        GLES20.glScissor(xpos, 0, 100, 100);
        GLES20.glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
    }
}


text: A Simple JDBC Result Set to Java Object Mapper


text:
package com.smartbear.ready.plugin.template;

import com.eviware.soapui.plugins.PluginAdapter;
import com.eviware.soapui.plugins.PluginConfiguration;

@PluginConfiguration(groupId = "com.smartbear.ready.plugins",
        name = "Ready! API Plugin Template", version = "1.0",
        autoDetect = true, description = "A Sample Ready! API Plugin",
        infoUrl = "https://github.com/smartbear/ready-api-plugin-template")
public class PluginConfig extends PluginAdapter {
}


text:
This plugin writes to a [GroundWork Monitor][1] instance. Plugin only supports
GW8+

[1]: https://www.gwos.com/product/groundwork-monitor/

## Configuration

```toml
# Send telegraf metrics to GroundWork Monitor
[[outputs.groundwork]]
  ## URL of your groundwork instance.
  url = "https://groundwork.example.com"

  ## Agent uuid for GroundWork API Server.
  agent_id = ""

  ## Username and password to access GroundWork API.
  username = ""
  password = ""

  ## Default display name for the host with services(metrics).
  # default_host = "telegraf"

  ## Default service state.
  # default_service_state = "SERVICE_OK"

  ## The name of the tag that contains the hostname.
  # resource_tag = "host"

  ## The name of the tag that contains the host group name.
  # group_tag = "group"
```

## List of tags used by the plugin

* group - to define the name of the group you want to monitor, can be changed
  with config.
* host - to define the name of the host you want to monitor, can be changed with
  config.
* service - to define the name of the service you want to monitor.
* status - to define the status of the service. Supported statuses:
  "SERVICE_OK", "SERVICE_WARNING", "SERVICE_UNSCHEDULED_CRITICAL",
  "SERVICE_PENDING", "SERVICE_SCHEDULED_CRITICAL", "SERVICE_UNKNOWN".
* message - to provide any message you want.
* unitType - to use in monitoring contexts(subset of The Unified Code for Units
  of Measure standard). Supported types: "1", "%cpu", "KB", "GB", "MB".
* warning - to define warning threshold value.
* critical - to define critical threshold value.

## NOTE

The current version of GroundWork Monitor does not support metrics whose values
are strings. Such metrics will be skipped and will not be added to the final
payload. You can find more context in this pull request: [#10255][].

[#10255]: https://github.com/influxdata/telegraf/pull/10255


text:
import sys
from stack import Stack

def parse_expression_into_parts(expression):
    """
    Parse expression into list of parts
    :rtype : list
    :param expression: str # i.e. "2 * 3 + ( 2 - 3 )"
    """
    raise NotImplementedError("complete me!")

def evaluate_expression(a, b, op):
    raise NotImplementedError("complete me!")

def evaluate_postfix(parts):
    raise NotImplementedError("complete me!")

if __name__ == "__main__":
    expr = None
    if len(sys.argv) > 1:
        expr = sys.argv[1]
        parts = parse_expression_into_parts(expr)
        print "Evaluating %s == %s" % (expr, evaluate_postfix(parts))
    else:
        print 'Usage: python postfix.py "<expr>" -- i.e. python postfix.py "9 1 3 + 2 * -"'
        print "Spaces are required between every term."


text:
using Testura.Android.Device;
using Testura.Android.Device.Ui.Nodes.Data;
using Testura.Android.Device.Ui.Search;
using Testura.Android.Util.Walker.Input;

namespace Testura.Android.Util.Walker.Cases.Tap
{
    /// <summary>
    /// Provides the base class from which the classes that represent tap cases are derived. Tap cases
    /// make it possible to handle specific nodes in <see cref="TapAppWalkerInput"/>
    /// </summary>
    public abstract class TapCase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TapCase"/> class.
        /// </summary>
        /// <param name="wheres">A set of special case wheres</param>
        protected TapCase(IList<Where> wheres)
        {
            Wheres = wheres;
        }

        /// <summary>
        /// Gets or sets the with for the special case node
        /// </summary>
        public IList<Where> Wheres { get; set; }

        /// <summary>
        /// Check if selected node match this tap case
        /// </summary>
        /// <param name="node">Selected node</param>
        /// <returns>True if we match, false otherwise</returns>
        public bool IsMatching(Node node)
        {
            return Wheres.All(where => where.NodeMatch(node, null));
        }

        /// <summary>
        /// Execute the case
        /// </summary>
        /// <param name="devie">The current device</param>
        /// <param name="node">The currently selected node</param>
        /// <returns>True if we should still tap on node, false otherwise</returns>
        public abstract bool Execute(IAndroidDevice devie, Node node);
    }
}


text:
package com.mkl.eu.service.service.persistence;

import com.excilys.ebi.spring.dbunit.config.DBOperation;
import com.excilys.ebi.spring.dbunit.test.DataSet;
import com.excilys.ebi.spring.dbunit.test.RollbackTransactionalDataSetTestExecutionListener;
import com.mkl.eu.client.common.util.CommonUtil;
import com.mkl.eu.client.service.service.ITablesService;
import com.mkl.eu.client.service.vo.country.PlayableCountry;
import com.mkl.eu.client.service.vo.enumeration.*;
import com.mkl.eu.client.service.vo.tables.*;
import com.mkl.eu.service.service.persistence.tables.ITablesDao;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Test for Tables service, dao and mapping.
 *
 * @author MKL
 */
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        RollbackTransactionalDataSetTestExecutionListener.class
})
@ContextConfiguration(locations = {"classpath:com/mkl/eu/service/service/eu-service-service-applicationContext.xml",
        "classpath:com/mkl/eu/service/service/test-database-applicationContext.xml"})
@DataSet(value = "tables.xml", columnSensing = true, tearDownOperation = DBOperation.DELETE_ALL)
public class TableDaoImplTest {
    @Autowired
    private ITablesService tablesService;

    @Autowired
    private ITablesDao tablesDao;

    @Test
    public void testTables() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(7, tables.getPeriods().size());
        Assert.assertEquals(Period.PERIOD_III, tables.getPeriods().get(2).getName());
        Assert.assertEquals(15, tables.getPeriods().get(2).getBegin().intValue());
        Assert.assertEquals(25, tables.getPeriods().get(2).getEnd().intValue());

        Assert.assertEquals(16, tables.getTechs().size());
        Assert.assertEquals("TERCIO", tables.getTechs().get(2).getName());
        Assert.assertEquals(16, tables.getTechs().get(2).getBeginBox().intValue());
        Assert.assertEquals(6, tables.getTechs().get(2).getBeginTurn().intValue());
        Assert.assertEquals("espagne", tables.getTechs().get(2).getCountry());
        Assert.assertEquals(true, tables.getTechs().get(2).isLand());

        Assert.assertEquals(55, tables.getForeignTrades().size());

        Assert.assertEquals(45, tables.getDomesticTrades().size());

        Assert.assertEquals(145, tables.getBasicForces().size());
        Assert.assertEquals("hollande", tables.getBasicForces().get(109).getCountry());
        Assert.assertEquals(1, tables.getBasicForces().get(109).getNumber().intValue());
        Assert.assertEquals(Period.PERIOD_IV, tables.getBasicForces().get(109).getPeriod().getName());
        Assert.assertEquals(ForceTypeEnum.ARMY_PLUS, tables.getBasicForces().get(109).getType());

        Assert.assertEquals(1339, tables.getUnits().size());
        Assert.assertEquals(ForceTypeEnum.ARMY_PLUS, tables.getUnits().get(1162).getType());
        Assert.assertEquals("pologne", tables.getUnits().get(1162).getCountry());
        Assert.assertEquals(UnitActionEnum.MAINT_WAR, tables.getUnits().get(1162).getAction());
        Assert.assertEquals(25, tables.getUnits().get(1162).getPrice().intValue());
        Assert.assertEquals(Tech.ARQUEBUS, tables.getUnits().get(1162).getTech().getName());
        Assert.assertEquals(true, tables.getUnits().get(1162).isSpecial());

        Assert.assertEquals(1400, tables.getLimits().size());
        Limit limit = CommonUtil.findFirst(tables.getLimits().stream(),
                l -> StringUtils.equals("france", l.getCountry()) && l.getType() == LimitTypeEnum.LEADER_CONQUISTADOR
                        && StringUtils.equals(Period.PERIOD_IV, l.getPeriod().getName()));
        Assert.assertEquals(1, limit.getNumber().intValue());

        Assert.assertEquals(90, tables.getResults().size());
        Result result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == -4 && r.getDie() == 2);
        Assert.assertEquals(ResultEnum.FUMBLE, result.getResult());
        result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == 2 && r.getDie() == 1);
        Assert.assertEquals(ResultEnum.FAILED, result.getResult());
        result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == 0 && r.getDie() == 5);
        Assert.assertEquals(ResultEnum.AVERAGE, result.getResult());
        result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == 0 && r.getDie() == 6);
        Assert.assertEquals(ResultEnum.AVERAGE_PLUS, result.getResult());
        result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == -3 && r.getDie() == 10);
        Assert.assertEquals(ResultEnum.SUCCESS, result.getResult());
        result = CommonUtil.findFirst(tables.getResults().stream(),
                r -> r.getColumn() == 4 && r.getDie() == 9);
        Assert.assertEquals(ResultEnum.CRITICAL_HIT, result.getResult());
    }

    @Test
    public void testTradeIncome() {
        Assert.assertEquals(2, tablesDao.getTradeIncome(1, 2, false));
        Assert.assertEquals(4, tablesDao.getTradeIncome(1, 4, false));
        Assert.assertEquals(9, tablesDao.getTradeIncome(60, 3, false));
        Assert.assertEquals(21, tablesDao.getTradeIncome(160, 3, false));
        Assert.assertEquals(27, tablesDao.getTradeIncome(161, 3, false));
        Assert.assertEquals(60, tablesDao.getTradeIncome(251, 3, false));
        Assert.assertEquals(60, tablesDao.getTradeIncome(9999, 3, false));
        Assert.assertEquals(100, tablesDao.getTradeIncome(9999, 5, false));

        Assert.assertEquals(60, tablesDao.getTradeIncome(0, 2, true));
        Assert.assertEquals(120, tablesDao.getTradeIncome(0, 4, true));
        Assert.assertEquals(81, tablesDao.getTradeIncome(60, 3, true));
        Assert.assertEquals(54, tablesDao.getTradeIncome(299, 3, true));
        Assert.assertEquals(45, tablesDao.getTradeIncome(300, 3, true));
        Assert.assertEquals(3, tablesDao.getTradeIncome(1100, 3, true));
        Assert.assertEquals(3, tablesDao.getTradeIncome(9999, 3, true));
        Assert.assertEquals(5, tablesDao.getTradeIncome(9999, 5, true));
    }

    @Test
    public void testBattleTech() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(113, tables.getBattleTechs().size());

        BattleTech arqRen = tables.getBattleTechs().stream()
                .filter(bt -> StringUtils.equals(bt.getTechnologyFor(), Tech.ARQUEBUS) &&
                        StringUtils.equals(bt.getTechnologyAgainst(), Tech.RENAISSANCE))
                .findAny()
                .orElse(null);

        Assert.assertNotNull(arqRen);
        Assert.assertEquals(true, arqRen.isLand());
        Assert.assertEquals("C", arqRen.getColumnFire());
        Assert.assertEquals("A", arqRen.getColumnShock());
        Assert.assertEquals(2, arqRen.getMoral());
        Assert.assertEquals(true, arqRen.isMoralBonusVeteran());

        BattleTech car74 = tables.getBattleTechs().stream()
                .filter(bt -> StringUtils.equals(bt.getTechnologyFor(), Tech.CARRACK) &&
                        StringUtils.equals(bt.getTechnologyAgainst(), Tech.SEVENTY_FOUR))
                .findAny()
                .orElse(null);

        Assert.assertNotNull(car74);
        Assert.assertEquals(false, car74.isLand());
        Assert.assertEquals(null, car74.getColumnFire());
        Assert.assertEquals("E", car74.getColumnShock());
        Assert.assertEquals(1, car74.getMoral());
        Assert.assertEquals(false, car74.isMoralBonusVeteran());
    }

    @Test
    public void testCombatResult() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(60, tables.getCombatResults().size());

        CombatResult a5 = tables.getCombatResults().stream()
                .filter(cr -> StringUtils.equals("A", cr.getColumn()) && cr.getDice() == 5)
                .findAny()
                .orElse(null);

        Assert.assertNotNull(a5);
        Assert.assertEquals(0, a5.getRoundLoss().intValue());
        Assert.assertEquals(2, a5.getThirdLoss().intValue());
        Assert.assertEquals(0, a5.getMoraleLoss().intValue());

        CombatResult d12 = tables.getCombatResults().stream()
                .filter(cr -> StringUtils.equals("D", cr.getColumn()) && cr.getDice() == 12)
                .findAny()
                .orElse(null);

        Assert.assertNotNull(d12);
        Assert.assertEquals(2, d12.getRoundLoss().intValue());
        Assert.assertEquals(0, d12.getThirdLoss().intValue());
        Assert.assertEquals(2, d12.getMoraleLoss().intValue());
    }

    @Test
    public void testArmyClasse() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(63, tables.getArmyClasses().size());

        ArmyClasse russieI = tables.getArmyClasses().stream()
                .filter(ac -> StringUtils.equals(Period.PERIOD_I, ac.getPeriod()) && ac.getArmyClass() == ArmyClassEnum.I)
                .findAny()
                .orElse(null);

        Assert.assertNotNull(russieI);
        Assert.assertEquals(7, russieI.getSize().intValue());

        ArmyClasse fraV = tables.getArmyClasses().stream()
                .filter(ac -> StringUtils.equals(Period.PERIOD_V, ac.getPeriod()) && ac.getArmyClass() == ArmyClassEnum.IV)
                .findAny()
                .orElse(null);

        Assert.assertNotNull(fraV);
        Assert.assertEquals(3, fraV.getSize().intValue());
    }

    @Test
    public void testArmyArtillery() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(133, tables.getArmyArtilleries().size());

        ArmyArtillery russieI = tables.getArmyArtilleries().stream()
                .filter(ac -> StringUtils.equals(Period.PERIOD_I, ac.getPeriod()) && StringUtils.equals(PlayableCountry.RUSSIA, ac.getCountry()))
                .findAny()
                .orElse(null);

        Assert.assertNotNull(russieI);
        Assert.assertEquals(1, russieI.getArtillery().intValue());

        ArmyArtillery fraV = tables.getArmyArtilleries().stream()
                .filter(ac -> StringUtils.equals(Period.PERIOD_V, ac.getPeriod()) && StringUtils.equals(PlayableCountry.FRANCE, ac.getCountry()))
                .findAny()
                .orElse(null);

        Assert.assertNotNull(fraV);
        Assert.assertEquals(5, fraV.getArtillery().intValue());

        ArmyArtillery IIMIII = tables.getArmyArtilleries().stream()
                .filter(ac -> StringUtils.equals(Period.PERIOD_III, ac.getPeriod()) && ac.getArmyClass() == ArmyClassEnum.IIM)
                .findAny()
                .orElse(null);

        Assert.assertNotNull(IIMIII);
        Assert.assertEquals(3, IIMIII.getArtillery().intValue());
    }

    @Test
    public void testArtillerySiege() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(18, tables.getArtillerySieges().size());

        ArtillerySiege artillerySiege = tables.getArtillerySieges().stream()
                .filter(as -> as.getFortress() == 0 && as.getArtillery() == 1)
                .findAny()
                .orElse(null);
        Assert.assertNotNull(artillerySiege);
        Assert.assertEquals(1, artillerySiege.getBonus().intValue());

        artillerySiege = tables.getArtillerySieges().stream()
                .filter(as -> as.getFortress() == 0 && as.getArtillery() == 3)
                .findAny()
                .orElse(null);
        Assert.assertNotNull(artillerySiege);
        Assert.assertEquals(2, artillerySiege.getBonus().intValue());

        artillerySiege = tables.getArtillerySieges().stream()
                .filter(as -> as.getFortress() == 0 && as.getArtillery() == 5)
                .findAny()
                .orElse(null);
        Assert.assertNotNull(artillerySiege);
        Assert.assertEquals(3, artillerySiege.getBonus().intValue());
    }

    @Test
    public void testFortressResistance() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(12, tables.getFortressResistances().size());

        FortressResistance fortressResistance = tables.getFortressResistances().stream()
                .filter(fr -> fr.getFortress() == 4 && !fr.isBreach())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(fortressResistance);
        Assert.assertEquals(3, fortressResistance.getRound().intValue());
        Assert.assertEquals(0, fortressResistance.getThird().intValue());

        fortressResistance = tables.getFortressResistances().stream()
                .filter(fr -> fr.getFortress() == 5 && !fr.isBreach())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(fortressResistance);
        Assert.assertEquals(3, fortressResistance.getRound().intValue());
        Assert.assertEquals(0, fortressResistance.getThird().intValue());

        fortressResistance = tables.getFortressResistances().stream()
                .filter(fr -> fr.getFortress() == 0 && fr.isBreach())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(fortressResistance);
        Assert.assertEquals(0, fortressResistance.getRound().intValue());
        Assert.assertEquals(1, fortressResistance.getThird().intValue());
    }

    @Test
    public void testAssaultResult() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();

        Assert.assertEquals(60, tables.getAssaultResults().size());

        AssaultResult assaultResult = tables.getAssaultResults().stream()
                .filter(ar -> ar.getDice() == 6 && ar.isFire() && !ar.isBreach() && !ar.isBesieger())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(assaultResult);
        Assert.assertEquals(0, assaultResult.getRoundLoss().intValue());
        Assert.assertEquals(2, assaultResult.getThirdLoss().intValue());
        Assert.assertEquals(1, assaultResult.getMoraleLoss().intValue());

        assaultResult = tables.getAssaultResults().stream()
                .filter(ar -> ar.getDice() == 7 && ar.isFire() && !ar.isBreach() && ar.isBesieger())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(assaultResult);
        Assert.assertEquals(1, assaultResult.getRoundLoss().intValue());
        Assert.assertEquals(0, assaultResult.getThirdLoss().intValue());
        Assert.assertEquals(1, assaultResult.getMoraleLoss().intValue());

        assaultResult = tables.getAssaultResults().stream()
                .filter(ar -> ar.getDice() == 10 && !ar.isFire() && ar.isBreach() && !ar.isBesieger())
                .findAny()
                .orElse(null);
        Assert.assertNotNull(assaultResult);
        Assert.assertEquals(1, assaultResult.getRoundLoss().intValue());
        Assert.assertEquals(0, assaultResult.getThirdLoss().intValue());
        Assert.assertEquals(3, assaultResult.getMoraleLoss().intValue());
    }

    @Test
    public void testExchequer() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();
        List<Exchequer> exchequers = tables.getExchequers();

        Assert.assertEquals(6, exchequers.size());
        Exchequer exchequer = exchequers.stream()
                .filter(exc -> exc.getResult() == ResultEnum.FUMBLE)
                .findAny()
                .orElse(null);
        Assert.assertNotNull(exchequer);
        Assert.assertEquals(30, exchequer.getRegular().intValue());
        Assert.assertEquals(0, exchequer.getPrestige().intValue());
        Assert.assertEquals(40, exchequer.getNatLoan().intValue());
        Assert.assertEquals(20, exchequer.getInterLoan().intValue());

        exchequer = exchequers.stream()
                .filter(exc -> exc.getResult() == ResultEnum.CRITICAL_HIT)
                .findAny()
                .orElse(null);
        Assert.assertNotNull(exchequer);
        Assert.assertEquals(60, exchequer.getRegular().intValue());
        Assert.assertEquals(40, exchequer.getPrestige().intValue());
        Assert.assertEquals(20, exchequer.getNatLoan().intValue());
        Assert.assertEquals(100, exchequer.getInterLoan().intValue());
    }

    @Test
    public void testLeaders() {
        tablesService.refresh();
        Tables tables = tablesService.getTables();
        List<Leader> leaders = tables.getLeaders();

        Assert.assertEquals(920, leaders.size());

        Leader leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Bonaparte"))
                .findAny()
                .orElse(null);
        Assert.assertNotNull(leader);
        Assert.assertEquals("Bonaparte", leader.getName());
        Assert.assertEquals("revolutionnaires", leader.getCountry());
        Assert.assertEquals("VII-5(2)", leader.getEvent());
        Assert.assertEquals(null, leader.getBegin());
        Assert.assertEquals(null, leader.getEnd());
        Assert.assertEquals("B", leader.getRank());
        Assert.assertEquals(6, leader.getManoeuvre());
        Assert.assertEquals(6, leader.getFire());
        Assert.assertEquals(6, leader.getShock());
        Assert.assertEquals(3, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.GENERAL, leader.getType());
        Assert.assertEquals(false, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(false, leader.isMediterranee());
        Assert.assertEquals(false, leader.isPrivateer());
        Assert.assertEquals(false, leader.isAnonymous());
        Assert.assertEquals(false, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertNull(leader.getOtherSide());
        Assert.assertTrue(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Albuquerque"))
                .findAny()
                .orElse(null);
        Assert.assertNotNull(leader);
        Assert.assertEquals("Albuquerque", leader.getName());
        Assert.assertEquals("porviceroy", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(5, leader.getBegin().intValue());
        Assert.assertEquals(9, leader.getEnd().intValue());
        Assert.assertEquals("B", leader.getRank());
        Assert.assertEquals(5, leader.getManoeuvre());
        Assert.assertEquals(5, leader.getFire());
        Assert.assertEquals(5, leader.getShock());
        Assert.assertEquals(3, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.CONQUISTADOR, leader.getType());
        Assert.assertEquals(true, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(false, leader.isMediterranee());
        Assert.assertEquals(false, leader.isPrivateer());
        Assert.assertEquals(false, leader.isAnonymous());
        Assert.assertEquals(true, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertEquals("Albuquerque-2", leader.getOtherSide());
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertTrue(Leader.landRotw.test(leader));
        Assert.assertTrue(Leader.landRotwAmerica.test(leader));
        Assert.assertTrue(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));
        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Albuquerque-2"))
                .findAny()
                .orElse(null);
        Assert.assertEquals("Albuquerque", leader.getName());
        Assert.assertEquals("porviceroy", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(5, leader.getBegin().intValue());
        Assert.assertEquals(9, leader.getEnd().intValue());
        Assert.assertEquals("B", leader.getRank());
        Assert.assertEquals(5, leader.getManoeuvre());
        Assert.assertEquals(5, leader.getFire());
        Assert.assertEquals(5, leader.getShock());
        Assert.assertEquals(0, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.EXPLORER, leader.getType());
        Assert.assertEquals(true, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(false, leader.isMediterranee());
        Assert.assertEquals(true, leader.isPrivateer());
        Assert.assertEquals(false, leader.isAnonymous());
        Assert.assertEquals(false, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertEquals("Albuquerque", leader.getOtherSide());
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertTrue(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Barbaros2"))
                .findAny()
                .orElse(null);
        Assert.assertNotNull(leader);
        Assert.assertEquals("Barbaros2", leader.getName());
        Assert.assertEquals("algerie", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(5, leader.getBegin().intValue());
        Assert.assertEquals(11, leader.getEnd().intValue());
        Assert.assertEquals("A", leader.getRank());
        Assert.assertEquals(5, leader.getManoeuvre());
        Assert.assertEquals(4, leader.getFire());
        Assert.assertEquals(5, leader.getShock());
        Assert.assertEquals(0, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.ADMIRAL, leader.getType());
        Assert.assertEquals(false, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(true, leader.isMediterranee());
        Assert.assertEquals(true, leader.isPrivateer());
        Assert.assertEquals(false, leader.isAnonymous());
        Assert.assertEquals(true, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertEquals("Barbaros2-2", leader.getOtherSide());
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertTrue(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));
        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Barbaros2-2"))
                .findAny()
                .orElse(null);
        Assert.assertEquals("Barbaros2", leader.getName());
        Assert.assertEquals("turquie", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(5, leader.getBegin().intValue());
        Assert.assertEquals(11, leader.getEnd().intValue());
        Assert.assertEquals("A", leader.getRank());
        Assert.assertEquals(5, leader.getManoeuvre());
        Assert.assertEquals(4, leader.getFire());
        Assert.assertEquals(5, leader.getShock());
        Assert.assertEquals(0, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.ADMIRAL, leader.getType());
        Assert.assertEquals(false, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(true, leader.isMediterranee());
        Assert.assertEquals(true, leader.isPrivateer());
        Assert.assertEquals(false, leader.isAnonymous());
        Assert.assertEquals(false, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertEquals("Barbaros2", leader.getOtherSide());
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertTrue(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "timar_Israf"))
                .findAny()
                .orElse(null);
        Assert.assertNotNull(leader);
        Assert.assertEquals("timar_Israf", leader.getName());
        Assert.assertEquals("turquie", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(null, leader.getBegin());
        Assert.assertEquals(null, leader.getEnd());
        Assert.assertEquals("S", leader.getRank());
        Assert.assertEquals(4, leader.getManoeuvre());
        Assert.assertEquals(4, leader.getFire());
        Assert.assertEquals(4, leader.getShock());
        Assert.assertEquals(0, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.PACHA, leader.getType());
        Assert.assertEquals(false, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(false, leader.isMediterranee());
        Assert.assertEquals(false, leader.isPrivateer());
        Assert.assertEquals(true, leader.isAnonymous());
        Assert.assertEquals(true, leader.isMain());
        Assert.assertEquals(2, leader.getSize().intValue());
        Assert.assertEquals("timar_Israf-2", leader.getOtherSide());
        Assert.assertTrue(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));
        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "timar_Israf-2"))
                .findAny()
                .orElse(null);
        Assert.assertEquals("timar_Israf", leader.getName());
        Assert.assertEquals("turquie", leader.getCountry());
        Assert.assertEquals(null, leader.getEvent());
        Assert.assertEquals(null, leader.getBegin());
        Assert.assertEquals(null, leader.getEnd());
        Assert.assertEquals(null, leader.getRank());
        Assert.assertEquals(0, leader.getManoeuvre());
        Assert.assertEquals(0, leader.getFire());
        Assert.assertEquals(0, leader.getShock());
        Assert.assertEquals(0, leader.getSiege());
        Assert.assertEquals(LeaderTypeEnum.PACHA, leader.getType());
        Assert.assertEquals(false, leader.isRotw());
        Assert.assertEquals(false, leader.isAmerica());
        Assert.assertEquals(false, leader.isAsia());
        Assert.assertEquals(false, leader.isMediterranee());
        Assert.assertEquals(false, leader.isPrivateer());
        Assert.assertEquals(true, leader.isAnonymous());
        Assert.assertEquals(false, leader.isMain());
        Assert.assertEquals(null, leader.getSize());
        Assert.assertEquals("timar_Israf", leader.getOtherSide());
        Assert.assertTrue(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Rochambeau"))
                .findAny()
                .orElse(null);
        Assert.assertTrue(Leader.landEurope.test(leader));
        Assert.assertTrue(Leader.landRotw.test(leader));
        Assert.assertTrue(Leader.landRotwAmerica.test(leader));
        Assert.assertTrue(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Santa Cruz"))
                .findAny()
                .orElse(null);
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertTrue(Leader.navalEurope.test(leader));
        Assert.assertTrue(Leader.navalEuropeMed.test(leader));
        Assert.assertTrue(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Colonna"))
                .findAny()
                .orElse(null);
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertTrue(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Maetsuycker"))
                .findAny()
                .orElse(null);
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertFalse(Leader.landRotwAmerica.test(leader));
        Assert.assertTrue(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));

        leader = leaders.stream()
                .filter(l -> StringUtils.equals(l.getCode(), "Antonelli"))
                .findAny()
                .orElse(null);
        Assert.assertFalse(Leader.landEurope.test(leader));
        Assert.assertFalse(Leader.landRotw.test(leader));
        Assert.assertTrue(Leader.landRotwAmerica.test(leader));
        Assert.assertFalse(Leader.landRotwAsia.test(leader));
        Assert.assertFalse(Leader.navalEurope.test(leader));
        Assert.assertFalse(Leader.navalEuropeMed.test(leader));
        Assert.assertFalse(Leader.navalRotw.test(leader));
    }
}


text:
FROM phpdockerio/php71-fpm:latest

# Install selected extensions and other stuff
RUN apt-get update \
    && apt-get -y --no-install-recommends install php-memcached php7.1-mysql php7.1-dev php-redis php7.1-bz2 php-pear libsasl2-dev pkg-config php-gearman \
    && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

WORKDIR "/var/www/isp-monitor"

RUN 	pecl install mongodb

RUN echo "extension=mongodb.so" > /etc/php/7.1/fpm/conf.d/20-mongodb.ini && \
	echo "extension=mongodb.so" > /etc/php/7.1/cli/conf.d/20-mongodb.ini && \
	echo "extension=mongodb.so" > /etc/php/7.1/mods-available/mongodb.ini


text:
package com.intellij.codeInsight.highlighting;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yole
 */
public abstract class HighlightUsagesHandlerBase<T extends PsiElement> {
  @NotNull protected final Editor myEditor;
  @NotNull protected final PsiFile myFile;

  protected List<TextRange> myReadUsages = new ArrayList<>();
  protected List<TextRange> myWriteUsages = new ArrayList<>();
  protected String myStatusText;
  protected String myHintText;

  protected HighlightUsagesHandlerBase(@NotNull Editor editor, @NotNull PsiFile file) {
    myEditor = editor;
    myFile = file;
  }

  public void highlightUsages() {
    List<T> targets = getTargets();
    if (targets == null) {
      return;
    }
    selectTargets(targets, targets1 -> {
      computeUsages(targets1);
      performHighlighting();
    });
  }

  protected void performHighlighting() {
    boolean clearHighlights = HighlightUsagesHandler.isClearHighlights(myEditor);
    EditorColorsManager manager = EditorColorsManager.getInstance();
    TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
    HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
                                           myEditor, attributes, clearHighlights, myReadUsages);
    HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
                                           myEditor, writeAttributes, clearHighlights, myWriteUsages);
    if (!clearHighlights) {
      WindowManager.getInstance().getStatusBar(myEditor.getProject()).setInfo(myStatusText);

      HighlightHandlerBase.setupFindModel(myEditor.getProject()); // enable f3 navigation
    }
    if (myHintText != null) {
      HintManager.getInstance().showInformationHint(myEditor, myHintText);
    }
  }

  protected void buildStatusText(@Nullable String elementName, int refCount) {
    if (refCount > 0) {
      myStatusText = CodeInsightBundle.message(elementName != null ?
                                        "status.bar.highlighted.usages.message" :
                                        "status.bar.highlighted.usages.no.target.message", refCount, elementName,
                                               HighlightUsagesHandler.getShortcutText());
    }
    else {
      myHintText = CodeInsightBundle.message(elementName != null ?
                                          "status.bar.highlighted.usages.not.found.message" :
                                          "status.bar.highlighted.usages.not.found.no.target.message", elementName);
    }
  }

  public abstract List<T> getTargets();

  @Nullable
  public String getFeatureId() {
    return null;
  }

  protected abstract void selectTargets(List<T> targets, Consumer<List<T>> selectionConsumer);

  public abstract void computeUsages(List<T> targets);

  protected void addOccurrence(@NotNull PsiElement element) {
    TextRange range = element.getTextRange();
    if (range != null) {
      range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range);
      myReadUsages.add(range);
    }
  }

  public List<TextRange> getReadUsages() {
    return myReadUsages;
  }

  public List<TextRange> getWriteUsages() {
    return myWriteUsages;
  }

  /**
   * In case of egoistic handler (highlightReferences = false) IdentifierHighlighterPass applies information only from this particular handler.
   * Otherwise additional information would be collected from reference search as well.
   */
  public boolean highlightReferences() {
    return false;
  }
}


text:
package com.yammer.dropwizard.util;

import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableMap;
import org.codehaus.jackson.annotate.JsonCreator;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public class Duration {
    private static final Pattern PATTERN = Pattern.compile("[\\d]+[\\s]*(" +
            "ns|nanosecond(s)?|" +
            "us|microsecond(s)?|" +
            "ms|millisecond(s)?|" +
            "s|second(s)?|" +
            "m|minute(s)?|" +
            "h|hour(s)?|" +
            "d|day(s)?" +
            ')');
    private static final ImmutableMap<String, TimeUnit> SUFFIXES;

    static {
        final ImmutableMap.Builder<String, TimeUnit> suffixes = ImmutableMap.builder();

        suffixes.put("ns", TimeUnit.NANOSECONDS);
        suffixes.put("nanosecond", TimeUnit.NANOSECONDS);
        suffixes.put("nanoseconds", TimeUnit.NANOSECONDS);

        suffixes.put("us", TimeUnit.MICROSECONDS);
        suffixes.put("microsecond", TimeUnit.MICROSECONDS);
        suffixes.put("microseconds", TimeUnit.MICROSECONDS);

        suffixes.put("ms", TimeUnit.MILLISECONDS);
        suffixes.put("millisecond", TimeUnit.MILLISECONDS);
        suffixes.put("milliseconds", TimeUnit.MILLISECONDS);

        suffixes.put("s", TimeUnit.SECONDS);
        suffixes.put("second", TimeUnit.SECONDS);
        suffixes.put("seconds", TimeUnit.SECONDS);

        suffixes.put("m", TimeUnit.MINUTES);
        suffixes.put("minute", TimeUnit.MINUTES);
        suffixes.put("minutes", TimeUnit.MINUTES);

        suffixes.put("h", TimeUnit.HOURS);
        suffixes.put("hour", TimeUnit.HOURS);
        suffixes.put("hours", TimeUnit.HOURS);

        suffixes.put("d", TimeUnit.DAYS);
        suffixes.put("day", TimeUnit.DAYS);
        suffixes.put("days", TimeUnit.DAYS);

        SUFFIXES = suffixes.build();
    }

    public static Duration nanoseconds(long count) {
        return new Duration(count, TimeUnit.NANOSECONDS);
    }

    public static Duration microseconds(long count) {
        return new Duration(count, TimeUnit.MICROSECONDS);
    }

    public static Duration milliseconds(long count) {
        return new Duration(count, TimeUnit.MILLISECONDS);
    }

    public static Duration seconds(long count) {
        return new Duration(count, TimeUnit.SECONDS);
    }

    public static Duration minutes(long count) {
        return new Duration(count, TimeUnit.MINUTES);
    }

    public static Duration hours(long count) {
        return new Duration(count, TimeUnit.HOURS);
    }

    public static Duration days(long count) {
        return new Duration(count, TimeUnit.DAYS);
    }

    private static long parseCount(String s) {
        checkArgument(PATTERN.matcher(s).matches(), "Invalid duration: %s", s);
        final String value = CharMatcher.WHITESPACE.removeFrom(s);
        return Long.parseLong(CharMatcher.JAVA_LETTER.trimTrailingFrom(value));
    }

    private static TimeUnit parseUnit(String s) {
        final String value = CharMatcher.WHITESPACE.removeFrom(s);
        final String suffix = CharMatcher.DIGIT.trimLeadingFrom(value);
        return SUFFIXES.get(suffix);
    }

    @JsonCreator
    public static Duration parse(String duration) {
        return new Duration(parseCount(duration), parseUnit(duration));
    }

    private final long count;
    private final TimeUnit unit;

    private Duration(long count, TimeUnit unit) {
        this.count = count;
        this.unit = checkNotNull(unit);
    }

    public long toNanoseconds() {
        return TimeUnit.NANOSECONDS.convert(count, unit);
    }

    public long toMicroseconds() {
        return TimeUnit.MICROSECONDS.convert(count, unit);
    }

    public long toMilliseconds() {
        return TimeUnit.MILLISECONDS.convert(count, unit);
    }

    public long toSeconds() {
        return TimeUnit.SECONDS.convert(count, unit);
    }

    public long toMinutes() {
        return TimeUnit.MINUTES.convert(count, unit);
    }

    public long toHours() {
        return TimeUnit.HOURS.convert(count, unit);
    }

    public long toDays() {
        return TimeUnit.DAYS.convert(count, unit);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if ((obj == null) || (getClass() != obj.getClass())) { return false; }
        final Duration duration = (Duration) obj;
        return (count == duration.count) && (unit == duration.unit);

    }

    @Override
    public int hashCode() {
        return (31 * (int) (count ^ (count >>> 32))) + unit.hashCode();
    }

    @Override
    public String toString() {
        String units = unit.toString().toLowerCase();
        if (count == 1) {
            units = units.substring(0, units.length() - 1);
        }
        return Long.toString(count) + ' ' + units;
    }
}


text:
package core.launch.operation;

import java.io.File;
import java.util.ArrayList;

import core.launch.LaunchAgent;
import core.launch.data.Artifact;
import core.launch.data.StatusManager.Status;
import core.persistence.Cache;
import core.runtime.TaskManager;

import util.CommandTask;

public class CommandOperation extends AbstractOperation {

	private CommandOperationConfig config;

	public CommandOperation(
			Cache cache,
			TaskManager taskManager,
			LaunchAgent parent,
			CommandOperationConfig config)
	{
		super(cache, taskManager, parent, config);
		this.config = (CommandOperationConfig) super.config;
	}

	@Override
	public String getRuntimeDescription() {
		return config.getCommand() + (!config.getArguments().isEmpty() ? " "+config.getArguments() : "");
	}

	@Override
	protected void execute() throws Exception {

		CommandTask task = new CommandTask(
				config.getCommand(),
				config.getArguments(),
				config.getDirectory().isEmpty() ?
						parent.getFolder() :
						parent.getFolder()+File.separator+config.getDirectory(),
				config.getEnvironment(),
				taskManager,
				logger
		);

		try{
			task.syncRun(0, timeout);
		}finally{
			if(task.hasSucceded()){
				statusManager.setStatus(Status.SUCCEED);
			}else{
				statusManager.setStatus(Status.ERROR);
			}
			if(!task.getOutput().isEmpty()){
				artifacts.add(new Artifact("Command", task.getOutput(), "txt"));
			}
		}
	}

	@Override
	protected void finish() {
		ArrayList<String> outputs = config.getOutputs();
		for(String output : outputs){
			handleOutput(output);
		}
		super.finish();
	}
}


text:
/*!
 * \file
 * \brief Class tools::Interleaver_core_CCSDS.
 */
#ifndef INTERLEAVER_CORE_CCSDS_HPP
#define INTERLEAVER_CORE_CCSDS_HPP

#include <cstdint>

#include "Tools/Interleaver/Interleaver_core.hpp"

namespace aff3ct
{
namespace tools
{
template <typename T = uint32_t>
class Interleaver_core_CCSDS : public Interleaver_core<T>
{
public:
	Interleaver_core_CCSDS(const int size);
	virtual ~Interleaver_core_CCSDS() = default;

	virtual Interleaver_core_CCSDS<T>* clone() const;

protected:
	void gen_lut(T *lut, const size_t frame_id);

private:
	static inline int pi_CCSDS(const int &index, const int &k_1, const int &k_2);
};
}
}

#endif	/* INTERLEAVER_CORE_CCSDS_HPP */


text:
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Towan</title>

Towan

		  Home
		  Game
		  Profile
		  Settings

Forum

				<form class="form-horizontal" method="post" th:action="${forums} ? @{/editEntry(id=${forums.id})} : @{addEntry}">
					<fieldset>
						<legend th:text="${forums}? 'Change Entry' : 'New Entry'">New Entry</legend>

							Text

								<input class="form-control" id="inputText" type="text"
									name="text" th:value="${forums} ? ${forums.text}">

								<button type="submit" class="btn btn-primary">Submit</button>

									<button type="button" class="btn btn-default">Cancel</button>

					</fieldset>
					<input type="hidden" th:name="${_csrf.parameterName}"
						th:value="${_csrf.token}" />
				</form>

	About


text:
package com.jbooktrader.platform.marketdepth;

import java.util.*;

/**
 * @author Eugene Kononov
 */
public enum MarketDepthSide {

    Ask(0), Bid(1);

    private final int value;
    private static final Map<Integer, MarketDepthSide> sides = new HashMap<>();

    MarketDepthSide(int value) {
        this.value = value;
    }

    public static MarketDepthSide getSide(int value) {
        return sides.get(value);
    }

    static {
        for (MarketDepthSide side : values()) {
            sides.put(side.value, side);
        }
    }
}