text:
#include "cbase.h"

#include "IViewRender.h"
#include "view.h"
#include "studio.h"
#include "bone_setup.h"
#include "model_types.h"
#include "beamdraw.h"
#include "engine/ivdebugoverlay.h"
#include "iviewrender_beams.h"
#include "fx.h"
#include "IEffects.h"
#include "C_ASW_Entity_Dissolve.h"
#include "movevars_shared.h"
#include "precache_register.h"
#include "asw_fx_shared.h"

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

// ASW - Custom version of the entity dissolve effect, used by alien goo when it fades out (doesn't have sparks, etc.)

IMPLEMENT_CLIENTCLASS_DT( C_ASW_Entity_Dissolve, DT_ASW_Entity_Dissolve, CASW_Entity_Dissolve )
RecvPropTime(RECVINFO(m_flStartTime)),
RecvPropFloat(RECVINFO(m_flFadeOutStart)),
RecvPropFloat(RECVINFO(m_flFadeOutLength)),
RecvPropFloat(RECVINFO(m_flFadeOutModelStart)),
RecvPropFloat(RECVINFO(m_flFadeOutModelLength)),
RecvPropFloat(RECVINFO(m_flFadeInStart)),
RecvPropFloat(RECVINFO(m_flFadeInLength)),
RecvPropInt(RECVINFO(m_nDissolveType)),
END_RECV_TABLE()

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_ASW_Entity_Dissolve::C_ASW_Entity_Dissolve( void )
{
	m_bLinkedToServerEnt = true;
	m_pController = false;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::GetRenderBounds( Vector& theMins, Vector& theMaxs )
{
	if ( GetMoveParent() )
	{
		GetMoveParent()->GetRenderBounds( theMins, theMaxs );
	}
	else
	{
		theMins = GetAbsOrigin();
		theMaxs = theMaxs;
	}
}

//-----------------------------------------------------------------------------
// On data changed
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::OnDataChanged( DataUpdateType_t updateType )
{
	BaseClass::OnDataChanged( updateType );
	if ( updateType == DATA_UPDATE_CREATED )
	{
		m_flNextSparkTime = m_flStartTime;
		SetNextClientThink( CLIENT_THINK_ALWAYS );
	}
}

//-----------------------------------------------------------------------------
// Cleanup
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::UpdateOnRemove( void )
{
	if ( m_pController )
	{
		physenv->DestroyMotionController( m_pController );
		m_pController = NULL;
	}

	BaseClass::UpdateOnRemove();
}

//------------------------------------------------------------------------------
// Apply the forces to the entity
//------------------------------------------------------------------------------
IMotionEvent::simresult_e C_ASW_Entity_Dissolve::Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular )
{
	linear.Init();
	angular.Init();

	// Make it zero g
	linear.z -= -1.02 * sv_gravity.GetFloat();

	Vector vel;
	AngularImpulse angVel;
	pObject->GetVelocity( &vel, &angVel );
	vel += linear * deltaTime; // account for gravity scale

	Vector unitVel = vel;
	Vector unitAngVel = angVel;

	float speed = VectorNormalize( unitVel );
	float flLinearLimit = 50;
	float flLinearLimitDelta = 40;
	if ( speed > flLinearLimit )
	{
		float flDeltaVel = (flLinearLimit - speed) / deltaTime;
		if ( flLinearLimitDelta != 0.0f )
		{
			float flMaxDeltaVel = -flLinearLimitDelta / deltaTime;
			if ( flDeltaVel < flMaxDeltaVel )
			{
				flDeltaVel = flMaxDeltaVel;
			}
		}
		VectorMA( linear, flDeltaVel, unitVel, linear );
	}

	return SIM_GLOBAL_ACCELERATION;
}

//-----------------------------------------------------------------------------
// Tesla effect
//-----------------------------------------------------------------------------
static void FX_BuildTesla( C_BaseEntity *pEntity, Vector &vecOrigin, Vector &vecEnd )
{
	BeamInfo_t beamInfo;
	beamInfo.m_pStartEnt = pEntity;
	beamInfo.m_nStartAttachment = 0;
	beamInfo.m_pEndEnt = NULL;
	beamInfo.m_nEndAttachment = 0;
	beamInfo.m_nType = TE_BEAMTESLA;
	beamInfo.m_vecStart = vecOrigin;
	beamInfo.m_vecEnd = vecEnd;
	beamInfo.m_pszModelName = "sprites/lgtning.vmt";
	beamInfo.m_flHaloScale = 0.0;
	beamInfo.m_flLife = random->RandomFloat( 0.25f, 1.0f );
	beamInfo.m_flWidth = random->RandomFloat( 8.0f, 14.0f );
	beamInfo.m_flEndWidth = 1.0f;
	beamInfo.m_flFadeLength = 0.5f;
	beamInfo.m_flAmplitude = 24;
	beamInfo.m_flBrightness = 255.0;
	beamInfo.m_flSpeed = 150.0f;
	beamInfo.m_nStartFrame = 0.0;
	beamInfo.m_flFrameRate = 30.0;
	beamInfo.m_flRed = 255.0;
	beamInfo.m_flGreen = 255.0;
	beamInfo.m_flBlue = 255.0;
	beamInfo.m_nSegments = 18;
	beamInfo.m_bRenderable = true;
	beamInfo.m_nFlags = 0; //FBEAM_ONLYNOISEONCE;

	beams->CreateBeamEntPoint( beamInfo );
}

//-----------------------------------------------------------------------------
// Purpose: Tesla effect
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::BuildTeslaEffect( mstudiobbox_t *pHitBox, const matrix3x4_t &hitboxToWorld, bool bRandom, float flYawOffset )
{
	Vector vecOrigin;
	QAngle vecAngles;
	MatrixGetColumn( hitboxToWorld, 3, vecOrigin );
	MatrixAngles( hitboxToWorld, vecAngles.Base() );
	C_BaseEntity *pEntity = GetMoveParent();

	// Make a couple of tries at it
	int iTries = -1;
	Vector vecForward;
	trace_t tr;
	do
	{
		iTries++;

		// Some beams are deliberatly aimed around the point, the rest are random.
		if ( !bRandom )
		{
			QAngle vecTemp = vecAngles;
			vecTemp[YAW] += flYawOffset;
			AngleVectors( vecTemp, &vecForward );

			// Randomly angle it up or down
			vecForward.z = RandomFloat( -1, 1 );
		}
		else
		{
			vecForward = RandomVector( -1, 1 );
		}

		UTIL_TraceLine( vecOrigin, vecOrigin + (vecForward * 192), MASK_SHOT, pEntity, COLLISION_GROUP_NONE, &tr );
	} while ( tr.fraction >= 1.0 && iTries < 3 );

	Vector vecEnd = tr.endpos - (vecForward * 8);

	// Only spark & glow if we hit something
	if ( tr.fraction < 1.0 )
	{
		if ( !EffectOccluded( tr.endpos ) )
		{
			ASSERT_LOCAL_PLAYER_RESOLVABLE();
			int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();

			// Move it towards the camera
			Vector vecFlash = tr.endpos;
			Vector vecForward;
			AngleVectors( MainViewAngles(nSlot), &vecForward );
			vecFlash -= (vecForward * 8);

			g_pEffects->EnergySplash( vecFlash, -vecForward, false );

			// End glow
			CSmartPtr<CSimpleEmitter> pSimple = CSimpleEmitter::Create( "dust" );
			pSimple->SetSortOrigin( vecFlash );
			SimpleParticle *pParticle;
			pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( "effects/blood" ), vecFlash );	// "effects/tesla_glow_noz"
			if ( pParticle != NULL )
			{
				pParticle->m_flLifetime = 0.0f;
				pParticle->m_flDieTime	= RandomFloat( 0.5, 1 );
				pParticle->m_vecVelocity = vec3_origin;
				Vector color( 1,1,1 );
				float  colorRamp = RandomFloat( 0.75f, 1.25f );
				pParticle->m_uchColor[0]	= 0; //MIN( 1.0f, color[0] * colorRamp ) * 255.0f;
				pParticle->m_uchColor[1]	= MIN( 1.0f, color[1] * colorRamp ) * 255.0f;
				pParticle->m_uchColor[2]	= 0; //MIN( 1.0f, color[2] * colorRamp ) * 255.0f;
				pParticle->m_uchStartSize	= RandomFloat( 6,13 );
				pParticle->m_uchEndSize		= pParticle->m_uchStartSize - 2;
				pParticle->m_uchStartAlpha	= 255;
				pParticle->m_uchEndAlpha	= 10;
				pParticle->m_flRoll			= RandomFloat( 0,360 );
				pParticle->m_flRollDelta	= 0;
			}
		}
	}

	// Build the tesla
	FX_BuildTesla( pEntity, vecOrigin, tr.endpos );
}

//-----------------------------------------------------------------------------
// Sorts the components of a vector
//-----------------------------------------------------------------------------
static inline void SortAbsVectorComponents( const Vector& src, int* pVecIdx )
{
	Vector absVec( fabs(src[0]), fabs(src[1]), fabs(src[2]) );

	int maxIdx = (absVec[0] > absVec[1]) ? 0 : 1;
	if (absVec[2] > absVec[maxIdx])
	{
		maxIdx = 2;
	}

	// always choose something right-handed....
	switch(	maxIdx )
	{
	case 0:
		pVecIdx[0] = 1;
		pVecIdx[1] = 2;
		pVecIdx[2] = 0;
		break;
	case 1:
		pVecIdx[0] = 2;
		pVecIdx[1] = 0;
		pVecIdx[2] = 1;
		break;
	case 2:
		pVecIdx[0] = 0;
		pVecIdx[1] = 1;
		pVecIdx[2] = 2;
		break;
	}
}

//-----------------------------------------------------------------------------
// Compute the bounding box's center, size, and basis
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::ComputeRenderInfo( mstudiobbox_t *pHitBox, const matrix3x4_t &hitboxToWorld,
											  Vector *pVecAbsOrigin, Vector *pXVec, Vector *pYVec )
{
	// Compute the center of the hitbox in worldspace
	Vector vecHitboxCenter;
	VectorAdd( pHitBox->bbmin, pHitBox->bbmax, vecHitboxCenter );
	vecHitboxCenter *= 0.5f;
	VectorTransform( vecHitboxCenter, hitboxToWorld, *pVecAbsOrigin );

	// Get the object's basis
	Vector vec[3];
	MatrixGetColumn( hitboxToWorld, 0, vec[0] );
	MatrixGetColumn( hitboxToWorld, 1, vec[1] );
	MatrixGetColumn( hitboxToWorld, 2, vec[2] );
	//	vec[1] *= -1.0f;

	Vector vecViewDir;
	VectorSubtract( CurrentViewOrigin(), *pVecAbsOrigin, vecViewDir );
	VectorNormalize( vecViewDir );

	// Project the shadow casting direction into the space of the hitbox
	Vector localViewDir;
	localViewDir[0] = DotProduct( vec[0], vecViewDir );
	localViewDir[1] = DotProduct( vec[1], vecViewDir );
	localViewDir[2] = DotProduct( vec[2], vecViewDir );

	// Figure out which vector has the largest component perpendicular
	// to the view direction...
	// Sort by how perpendicular it is
	int vecIdx[3];
	SortAbsVectorComponents( localViewDir, vecIdx );

	// Here's our hitbox basis vectors; namely the ones that are
	// most perpendicular to the view direction
	*pXVec = vec[vecIdx[0]];
	*pYVec = vec[vecIdx[1]];

	// Project them into a plane perpendicular to the view direction
	*pXVec -= vecViewDir * DotProduct( vecViewDir, *pXVec );
	*pYVec -= vecViewDir * DotProduct( vecViewDir, *pYVec );
	VectorNormalize( *pXVec );
	VectorNormalize( *pYVec );

	// Compute the hitbox size
	Vector boxSize;
	VectorSubtract( pHitBox->bbmax, pHitBox->bbmin, boxSize );

	// We project the two longest sides into the vectors perpendicular
	// to the projection direction, then add in the projection of the perp direction
	Vector2D size( boxSize[vecIdx[0]], boxSize[vecIdx[1]] );
	size.x *= fabs( DotProduct( vec[vecIdx[0]], *pXVec ) );
	size.y *= fabs( DotProduct( vec[vecIdx[1]], *pYVec ) );

	// Add the third component into x and y
	size.x += boxSize[vecIdx[2]] * fabs( DotProduct( vec[vecIdx[2]], *pXVec ) );
	size.y += boxSize[vecIdx[2]] * fabs( DotProduct( vec[vecIdx[2]], *pYVec ) );

	// Bloat a bit, since the shadow wants to extend outside the model a bit
	size *= 2.0f;

	// Clamp the minimum size
	Vector2DMax( size, Vector2D(10.0f, 10.0f), size );

	// Factor the size into the xvec + yvec
	(*pXVec) *= size.x * 0.5f;
	(*pYVec) *= size.y * 0.5f;
}

//-----------------------------------------------------------------------------
// Sparks!
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::DoSparks( mstudiohitboxset_t *set, matrix3x4_t *hitboxbones[MAXSTUDIOBONES] )
{
	if ( m_flNextSparkTime > gpGlobals->curtime )
		return;

	float dt = m_flStartTime + m_flFadeOutStart - gpGlobals->curtime;
	dt = clamp( dt, 0.0f, m_flFadeOutStart );

	float flNextTime;
	if (m_nDissolveType == ENTITY_DISSOLVE_ELECTRICAL)
	{
		flNextTime = SimpleSplineRemapVal( dt, 0.0f, m_flFadeOutStart, 2.0f * TICK_INTERVAL, 0.4f );
	}
	else
	{
		// m_nDissolveType == ENTITY_DISSOLVE_ELECTRICAL_LIGHT);
		flNextTime = SimpleSplineRemapVal( dt, 0.0f, m_flFadeOutStart, 0.3f, 1.0f );
	}

	m_flNextSparkTime = gpGlobals->curtime + flNextTime;

	// Send out beams around us
	int iNumBeamsAround = 2;
	int iNumRandomBeams = 1;
	int iTotalBeams = iNumBeamsAround + iNumRandomBeams;
	float flYawOffset = RandomFloat(0,360);
	for ( int i = 0; i < iTotalBeams; i++ )
	{
		int nHitbox = random->RandomInt( 0, set->numhitboxes - 1 );
		mstudiobbox_t *pBox = set->pHitbox(nHitbox);

		float flActualYawOffset = 0;
		bool bRandom = ( i >= iNumBeamsAround );
		if ( !bRandom )
		{
			flActualYawOffset = anglemod( flYawOffset + ((360 / iTotalBeams) * i) );
		}

		BuildTeslaEffect( pBox, *hitboxbones[pBox->bone], bRandom, flActualYawOffset );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::SetupEmitter( void )
{
	if ( !m_pEmitter )
	{
		m_pEmitter = CSimpleEmitter::Create( "C_ASW_Entity_Dissolve" );
		m_pEmitter->SetSortOrigin( GetAbsOrigin() );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float C_ASW_Entity_Dissolve::GetFadeInPercentage( void )
{
	float dt = gpGlobals->curtime - m_flStartTime;

	if ( dt > m_flFadeOutStart )
		return 1.0f;

	if ( dt < m_flFadeInStart )
		return 0.0f;

	if ( (dt > m_flFadeInStart) && (dt < m_flFadeInStart + m_flFadeInLength) )
	{
		dt -= m_flFadeInStart;

		return ( dt / m_flFadeInLength );
	}

	return 1.0f;
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float C_ASW_Entity_Dissolve::GetFadeOutPercentage( void )
{
	float dt = gpGlobals->curtime - m_flStartTime;

	if ( dt < m_flFadeInStart )
		return 1.0f;

	if ( dt > m_flFadeOutStart )
	{
		dt -= m_flFadeOutStart;

		if ( dt > m_flFadeOutLength )
			return 0.0f;

		return 1.0f - ( dt / m_flFadeOutLength );
	}

	return 1.0f;
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float C_ASW_Entity_Dissolve::GetModelFadeOutPercentage( void )
{
	float dt = gpGlobals->curtime - m_flStartTime;

	if ( dt < m_flFadeOutModelStart )
		return 1.0f;

	if ( dt > m_flFadeOutModelStart )
	{
		dt -= m_flFadeOutModelStart;

		if ( dt > m_flFadeOutModelLength )
			return 0.0f;

		return 1.0f - ( dt / m_flFadeOutModelLength );
	}

	return 1.0f;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C_ASW_Entity_Dissolve::ClientThink( void )
{
	C_BaseAnimating *pAnimating = GetMoveParent() ? GetMoveParent()->GetBaseAnimating() : NULL;
	if (!pAnimating)
		return;

	// NOTE: IsRagdoll means *client-side* ragdoll. We shouldn't be trying to fight
	// the server ragdoll (or any server physics) on the client
	if (( !m_pController ) && ( m_nDissolveType == ENTITY_DISSOLVE_NORMAL ) && pAnimating->IsRagdoll())
	{
		IPhysicsObject *ppList[32];
		int nCount = pAnimating->VPhysicsGetObjectList( ppList, 32 );
		if ( nCount > 0 )
		{
			m_pController = physenv->CreateMotionController( this );
			for ( int i = 0; i < nCount; ++i )
			{
				m_pController->AttachObject( ppList[i], true );
			}
		}
	}

	color32 color;

	color.r = color.g = color.b = ( 1.0f - GetFadeInPercentage() ) * 255.0f;
	color.a = GetModelFadeOutPercentage() * 255.0f;

	// Setup the entity fade
	pAnimating->SetRenderMode( kRenderTransColor );
	pAnimating->SetRenderColor( color.r, color.g, color.b );
	pAnimating->SetRenderAlpha( color.a );

	// If we're dead, fade out
	if ( GetFadeOutPercentage() <= 0.0f )
	{
		// spawn some splurts
		//BloodSpurts();

		ClientThinkList()->RemoveThinkable( GetClientHandle() );

		// Do NOT remove from the client entity list. It'll confuse the local network backdoor, and the entity will never get destroyed
		// because when the server says to destroy it, the client won't be able to find it.
		// ClientEntityList().RemoveEntity( GetClientHandle() );

		partition->Remove( PARTITION_CLIENT_SOLID_EDICTS | PARTITION_CLIENT_RESPONSIVE_EDICTS | PARTITION_CLIENT_NON_STATIC_EDICTS, CollisionProp()->GetPartitionHandle() );

		RemoveFromLeafSystem();

		//FIXME: Ick!
		//Adrian: I'll assume we don't need the ragdoll either so I'll remove that too.
		if ( m_bLinkedToServerEnt == false )
		{
			Release();

			C_ClientRagdoll *pRagdoll = dynamic_cast <C_ClientRagdoll *> ( pAnimating );

			if ( pRagdoll )
			{
				pRagdoll->ReleaseRagdoll();
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : flags -
// Output : int
//-----------------------------------------------------------------------------
int C_ASW_Entity_Dissolve::DrawModel( int flags )
{
	if ( gpGlobals->frametime == 0 )
		return 0;

	// See if we should draw
	if ( m_bReadyToDraw == false )
		return 0;

	C_BaseAnimating *pAnimating = GetMoveParent() ? GetMoveParent()->GetBaseAnimating() : NULL;
	if (!pAnimating)
		return 0;

	matrix3x4_t	*hitboxbones[MAXSTUDIOBONES];
	if ( !pAnimating->HitboxToWorldTransforms( hitboxbones ) )
		return 0;

	studiohdr_t *pStudioHdr = modelinfo->GetStudiomodel( pAnimating->GetModel() );
	if (!pStudioHdr)
		return false;

	mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pAnimating->GetHitboxSet() );
	if ( !set )
		return false;

	SetupEmitter();

	int i;

	float fadeInPerc = GetFadeInPercentage();
	float fadeOutPerc = GetFadeOutPercentage();

	float fadePerc = ( fadeInPerc >= 1.0f ) ? fadeOutPerc : fadeInPerc;

	Vector	vecSkew = vec3_origin;

	if ( ( fadePerc < 0.99f ) && ( (m_nDissolveType == ENTITY_DISSOLVE_ELECTRICAL) || (m_nDissolveType == ENTITY_DISSOLVE_ELECTRICAL_LIGHT) ) )
	{
		DoSparks( set, hitboxbones );
	}

	fadePerc = GetModelFadeOutPercentage();

	// Skew the particles in front or in back of their targets
	vecSkew = CurrentViewForward() * ( 8.0f - ( ( 1.0f - fadePerc ) * 32.0f ) );

	float spriteScale = ( ( gpGlobals->curtime - m_flStartTime ) / m_flFadeOutLength );
	spriteScale = clamp( spriteScale, 0.75f, 1.0f );

	SimpleParticle *sParticle;

	for ( i = 0; i < set->numhitboxes; ++i )
	{
		Vector vecAbsOrigin, xvec, yvec;
		mstudiobbox_t *pBox = set->pHitbox(i);
		ComputeRenderInfo( pBox, *hitboxbones[pBox->bone], &vecAbsOrigin, &xvec, &yvec );

		Vector offset;
		Vector	xDir, yDir;

		xDir = xvec;
		float xScale = VectorNormalize( xDir ) * 0.75f;

		yDir = yvec;
		float yScale = VectorNormalize( yDir ) * 0.75f;

		int numParticles = clamp( 3.0f * fadePerc, 0, 3 );

		// smoke
		for ( int j = 0; j < 4; j++ )	// was 2
		{
			offset = xDir * Helper_RandomFloat( -xScale*0.5f, xScale*0.5f ) + yDir * Helper_RandomFloat( -yScale*0.5f, yScale*0.5f );
			offset += vecSkew;

			if ( random->RandomInt( 0, 2 ) != 0 )
				continue;

			sParticle = (SimpleParticle *) m_pEmitter->AddParticle( sizeof(SimpleParticle), m_pEmitter->GetPMaterial( "swarm/sprites/smoke" ), vecAbsOrigin + offset );	//"effects/spark"

			if ( sParticle == NULL )
				return 1;

			sParticle->m_vecVelocity	= Vector( Helper_RandomFloat( -4.0f, 4.0f ), Helper_RandomFloat( -4.0f, 4.0f ), Helper_RandomFloat( 16.0f, 64.0f ) );

			if ( sParticle->m_vecVelocity.z > 0 )
			{
				sParticle->m_uchStartSize	= random->RandomFloat( 4, 6 ) * spriteScale;
			}
			else
			{
				sParticle->m_uchStartSize	= 2 * spriteScale;
			}

			sParticle->m_flDieTime = random->RandomFloat( 0.4f, 0.5f );

			// If we're the last particles, last longer
			if ( numParticles == 0 )
			{
				sParticle->m_flDieTime *= 2.0f;
				sParticle->m_uchStartSize = 2 * spriteScale * 2;
				sParticle->m_flRollDelta	= 0; //Helper_RandomFloat( -4.0f, 4.0f );
			}
			else
			{
				sParticle->m_flRollDelta	= 0; //Helper_RandomFloat( -8.0f, 8.0f );
			}

			sParticle->m_flLifetime		= 0.0f;

			sParticle->m_flRoll			= Helper_RandomInt( 0, 360 );

			float alpha = 255;

			sParticle->m_uchColor[0]	= alpha*(108.0f/255.0f);
			sParticle->m_uchColor[1]	= alpha*(88.0f/255.0f);
			sParticle->m_uchColor[2]	= alpha*(83.0f/255.0f);
			sParticle->m_uchStartAlpha	= alpha;
			sParticle->m_uchEndAlpha	= 0;
			sParticle->m_uchEndSize		= sParticle->m_uchStartSize * 2.0f;
		}

		// big shrinking soft sparkles
		/*
		for ( int j = 0; j < numParticles; j++ )
		{
		offset = xDir * Helper_RandomFloat( -xScale*0.5f, xScale*0.5f ) + yDir * Helper_RandomFloat( -yScale*0.5f, yScale*0.5f );
		offset += vecSkew;

		sParticle = (SimpleParticle *) m_pEmitter->AddParticle( sizeof(SimpleParticle), m_pEmitter->GetPMaterial( "effects/combinemuzzle2" ), vecAbsOrigin + offset );	//
		//sParticle = (SimpleParticle *) m_pEmitter->AddParticle( sizeof(SimpleParticle), m_pEmitter->GetPMaterial( VarArgs("sprites/flamelet%d", Helper_RandomInt( 1, 5 ) ) ), vecAbsOrigin + offset );

		if ( sParticle == NULL )
		return 1;

		sParticle->m_vecVelocity	= Vector( Helper_RandomFloat( -4.0f, 4.0f ), Helper_RandomFloat( -4.0f, 4.0f ), Helper_RandomFloat( -64.0f, 128.0f ) );
		sParticle->m_uchStartSize	= random->RandomFloat( 8, 12 ) * spriteScale;
		sParticle->m_flDieTime		= 0.1f;
		sParticle->m_flLifetime		= 0.0f;

		sParticle->m_flRoll			= Helper_RandomInt( 0, 360 );
		sParticle->m_flRollDelta	= Helper_RandomFloat( -2.0f, 2.0f );

		float alpha = 255;

		sParticle->m_uchColor[0]	= 0;//alpha;
		sParticle->m_uchColor[1]	= alpha;
		sParticle->m_uchColor[2]	= 0;//alpha;
		sParticle->m_uchStartAlpha	= alpha;
		sParticle->m_uchEndAlpha	= 0;
		sParticle->m_uchEndSize		= 0;
		}*/
	}

	return 1;
}

void C_ASW_Entity_Dissolve::BloodSpurts()
{
	/*
	Vector	vecSkew = vec3_origin;

	// Skew the particles in front or in back of their targets
	//vecSkew = CurrentViewForward() * ( 8.0f - ( ( 0.5f ) * 32.0f ) );

	float spriteScale = ( ( gpGlobals->curtime - m_flStartTime ) / m_flFadeOutLength );
	spriteScale = clamp( spriteScale, 0.75f, 1.0f );

	C_BaseAnimating *pAnimating = GetMoveParent() ? GetMoveParent()->GetBaseAnimating() : NULL;
	if (!pAnimating)
	return;

	matrix3x4_t	*hitboxbones[MAXSTUDIOBONES];
	if ( !pAnimating->HitboxToWorldTransforms( hitboxbones ) )
	return;

	studiohdr_t *pStudioHdr = modelinfo->GetStudiomodel( pAnimating->GetModel() );
	if (!pStudioHdr)
	return;

	mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pAnimating->GetHitboxSet() );
	if ( !set )
	return;

	for ( int i = 0; i < set->numhitboxes; ++i )
	{
	Vector vecAbsOrigin, xvec, yvec;
	mstudiobbox_t *pBox = set->pHitbox(i);
	ComputeRenderInfo( pBox, *hitboxbones[pBox->bone], &vecAbsOrigin, &xvec, &yvec );

	Vector offset;
	Vector	xDir, yDir;

	xDir = xvec;
	float xScale = VectorNormalize( xDir ) * 0.75f;

	yDir = yvec;
	float yScale = VectorNormalize( yDir ) * 0.75f;

	//int numParticles = clamp( 3.0f * 0.5f, 0, 3 );

	// blood in each hitbox
	for ( int j = 0; j < 4; j++ )	// was 2
	{
	offset = xDir * Helper_RandomFloat( -xScale*0.5f, xScale*0.5f ) + yDir * Helper_RandomFloat( -yScale*0.5f, yScale*0.5f );
	//offset += vecSkew;

	if ( random->RandomInt( 0, 2 ) != 0 )
	continue;

	}
	}*/
	UTIL_ASW_BloodDrips( WorldSpaceCenter(), Vector(0,0,1), BLOOD_COLOR_BRIGHTGREEN, 4 );
}


text:
/**
 * angular-dialog-service - A service to handle common dialog types in a web application.  Built on top of Angular-Bootstrap's modal
 * @version v5.3.1
 * @author Michael Conroy, michael.e.conroy@gmail.com
 * @license MIT, http://www.opensource.org/licenses/MIT
 */
/**
 * Dialog Default Translations.
 *
 * Include this module if you're not already using angular-translate in your application, and
 * add it to your application module's dependency list in order to get default header and
 * dialog messages to appear.
 *
 * Ex: var myApp = angular.module('myApplication',['dialogs.main','dialogs.default-translations']);
 *
 * It was necessary to separate this out for those already using angular-translate because this would
 * automatically reset their translation list for 'en-US'
 *
 * For those already using angular-translate, just copy the list of DIALOG_[..] translations to your
 * translation list where you set 'en-US' using the $translateProvider.
 */

//== Translations =============================================================//

 angular.module('dialogs.default-translations',['pascalprecht.translate'])
 /**
     * Default translations in English.
     *
     * Use angular-translate's $translateProvider to provide translations in an
     * alternate language.
     *
     * $translateProvider.translations('[lang]',{[translations]});
     * To use alternate translations set the preferred language to your desired
     * language.
     * $translateProvider.preferredLanguage('[lang]');
     */
    .config(['$translateProvider',function($translateProvider){
        $translateProvider.translations('de-DE',{
            DIALOGS_ERROR: "Error",
            DIALOGS_ERROR_MSG: "Ein unbekannter Fehler ist aufgetreten.",
            DIALOGS_CLOSE: "Schließen",
            DIALOGS_PLEASE_WAIT: "Bitte warten",
            DIALOGS_PLEASE_WAIT_ELIPS: "Bitte warten...",
            DIALOGS_PLEASE_WAIT_MSG: "Warte auf Fertigstellung der Operation.",
            DIALOGS_PERCENT_COMPLETE: "% fertig",
            DIALOGS_NOTIFICATION: "Benachrichtigung",
            DIALOGS_NOTIFICATION_MSG: "Unbekannte Anwendungsbenachrichtigung.",
            DIALOGS_CONFIRMATION: "Bestätigung",
            DIALOGS_CONFIRMATION_MSG: "Bestätigung erforderlich.",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Ja",
            DIALOGS_NO: "Nein"
        });

        $translateProvider.translations('en-US',{
            DIALOGS_ERROR: "Error",
            DIALOGS_ERROR_MSG: "An unknown error has occurred.",
            DIALOGS_CLOSE: "Close",
            DIALOGS_PLEASE_WAIT: "Please Wait",
            DIALOGS_PLEASE_WAIT_ELIPS: "Please Wait...",
            DIALOGS_PLEASE_WAIT_MSG: "Waiting on operation to complete.",
            DIALOGS_PERCENT_COMPLETE: "% Complete",
            DIALOGS_NOTIFICATION: "Notification",
            DIALOGS_NOTIFICATION_MSG: "Unknown application notification.",
            DIALOGS_CONFIRMATION: "Confirmation",
            DIALOGS_CONFIRMATION_MSG: "Confirmation required.",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Yes",
            DIALOGS_NO: "No"
        });

        $translateProvider.translations('es-ES',{
            DIALOGS_ERROR: "Error",
            DIALOGS_ERROR_MSG: "Se ha producido un error.",
            DIALOGS_CLOSE: "Cerrar",
            DIALOGS_PLEASE_WAIT: "Espere por favor",
            DIALOGS_PLEASE_WAIT_ELIPS: "Espere por favor...",
            DIALOGS_PLEASE_WAIT_MSG: "Completando operación.",
            DIALOGS_PERCENT_COMPLETE: "% Completado",
            DIALOGS_NOTIFICATION: "Notificación",
            DIALOGS_NOTIFICATION_MSG: "Notificación de una aplicación desconocida.",
            DIALOGS_CONFIRMATION: "Confirmación",
            DIALOGS_CONFIRMATION_MSG: "Se requiere confirmacion.",
            DIALOGS_OK: "Aceptar",
            DIALOGS_YES: "Sí",
            DIALOGS_NO: "No"
        });

        $translateProvider.translations("fr-FR", {
            DIALOGS_ERROR: "Erreur",
            DIALOGS_ERROR_MSG: "Une erreur inconnue s'est produite.",
            DIALOGS_CLOSE: "Fermer",
            DIALOGS_PLEASE_WAIT: "Patientez svp",
            DIALOGS_PLEASE_WAIT_ELIPS: "Patienter svp...",
            DIALOGS_PLEASE_WAIT_MSG: "En attente de la fin de l'opération.",
            DIALOGS_PERCENT_COMPLETE: "% Terminer",
            DIALOGS_NOTIFICATION: "Notification",
            DIALOGS_NOTIFICATION_MSG: "Notification de l'application inconnue",
            DIALOGS_CONFIRMATION: "Confirmer",
            DIALOGS_CONFIRMATION_MSG: "Merci de confirmer",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Oui",
            DIALOGS_NO: "Non"
        });

        $translateProvider.translations('pt-BR',{
            DIALOGS_ERROR: "Erro",
            DIALOGS_ERROR_MSG: "Ocorreu um erro inesperado.",
            DIALOGS_CLOSE: "Fechar",
            DIALOGS_PLEASE_WAIT: "Por favor aguarde",
            DIALOGS_PLEASE_WAIT_ELIPS: "Por favor aguarde...",
            DIALOGS_PLEASE_WAIT_MSG: "Aguardando que a operação termine.",
            DIALOGS_PERCENT_COMPLETE: "% Completados",
            DIALOGS_NOTIFICATION: "Notificação",
            DIALOGS_NOTIFICATION_MSG: "Notificação de aplicação desconhecida.",
            DIALOGS_CONFIRMATION: "Confirmação",
            DIALOGS_CONFIRMATION_MSG: "Confirmação requerida.",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Sim",
            DIALOGS_NO: "Não"
        });

        $translateProvider.translations('tr-TR',{
            DIALOGS_ERROR: "Hata",
            DIALOGS_ERROR_MSG: "Bilinmeyen bir hata oluştu.",
            DIALOGS_CLOSE: "Kapat",
            DIALOGS_PLEASE_WAIT: "Lütfen Bekleyin",
            DIALOGS_PLEASE_WAIT_ELIPS: "Lütfen Bekleyin...",
            DIALOGS_PLEASE_WAIT_MSG: "İşlemin tamamlanması bekleniyor.",
            DIALOGS_PERCENT_COMPLETE: "% Tamamlandı",
            DIALOGS_NOTIFICATION: "Uyarı",
            DIALOGS_NOTIFICATION_MSG: "Bilinmeyen uygulama uyarısı.",
            DIALOGS_CONFIRMATION: "Konfirmasyon",
            DIALOGS_CONFIRMATION_MSG: "Konfirmasyon gereklidir.",
            DIALOGS_OK: "Tamam",
            DIALOGS_YES: "Evet",
            DIALOGS_NO: "Hayır"
        });

        $translateProvider.translations('zh-CN',{
            DIALOGS_ERROR: "错误",
            DIALOGS_ERROR_MSG: "出现未知错误。",
            DIALOGS_CLOSE: "关闭",
            DIALOGS_PLEASE_WAIT: "请稍候",
            DIALOGS_PLEASE_WAIT_ELIPS: "请稍候...",
            DIALOGS_PLEASE_WAIT_MSG: "请等待操作完成。",
            DIALOGS_PERCENT_COMPLETE: "% 已完成",
            DIALOGS_NOTIFICATION: "通知",
            DIALOGS_NOTIFICATION_MSG: "未知应用程序的通知。",
            DIALOGS_CONFIRMATION: "确认",
            DIALOGS_CONFIRMATION_MSG: "确认要求。",
            DIALOGS_OK: "确定",
            DIALOGS_YES: "确认",
            DIALOGS_NO: "取消"
        });

        $translateProvider.translations('sv-SE',{
            DIALOGS_ERROR: "Fel",
            DIALOGS_ERROR_MSG: "Ett okänt fel har uppstått.",
            DIALOGS_CLOSE: "Stäng",
            DIALOGS_PLEASE_WAIT: "Vänligen vänta",
            DIALOGS_PLEASE_WAIT_ELIPS: "Vänligen vänta...",
            DIALOGS_PLEASE_WAIT_MSG: "Väntar på att processen skall slutföras.",
            DIALOGS_PERCENT_COMPLETE: "% Färdigt",
            DIALOGS_NOTIFICATION: "Meddelande",
            DIALOGS_NOTIFICATION_MSG: "Okänt meddelande från applikationen.",
            DIALOGS_CONFIRMATION: "Bekräftelse",
            DIALOGS_CONFIRMATION_MSG: "Bekräftelse krävs.",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Ja",
            DIALOGS_NO: "Nej"
        });

        $translateProvider.translations('it-IT',{
            DIALOGS_ERROR: "Errore",
            DIALOGS_ERROR_MSG: "Si è verificato un errore sconosciuto.",
            DIALOGS_CLOSE: "Chiudi",
            DIALOGS_PLEASE_WAIT: "Attendere prego",
            DIALOGS_PLEASE_WAIT_ELIPS: "Attendere prego...",
            DIALOGS_PLEASE_WAIT_MSG: "Attendo il completamento dell'operazione.",
            DIALOGS_PERCENT_COMPLETE: "% Completo",
            DIALOGS_NOTIFICATION: "Notifica",
            DIALOGS_NOTIFICATION_MSG: "Notifica dell'applicazione sconosciuta.",
            DIALOGS_CONFIRMATION: "Conferma",
            DIALOGS_CONFIRMATION_MSG: "Conferma richiesta.",
            DIALOGS_OK: "OK",
            DIALOGS_YES: "Sì",
            DIALOGS_NO: "No"
        });

        $translateProvider.preferredLanguage('en-US');
    }]); // end config

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Output Devices
---

Coming Soon !


text:
module DenySpam

  # Provides <tt>tail -f</tt> functionality used to monitor a file for changes.
  # Automatically reopens the file if it is truncated or deleted.
  class Tail

    attr_accessor :interval
    attr_reader   :filename, :lastpos

    def initialize(filename, lastpos = 0, interval = 15)
      @filename  = filename
      @lastpos   = lastpos
      @interval  = interval
      @last_stat = nil
    end

    # Begins tailing the file. When a new line appears, it's passed to the
    # block.
    def tail(&block) # :yields: line
      # Wait for the file to be created if it doesn't already exist.
      until File.exist?(@filename)
        sleep 30
      end

      # Make sure the file isn't a directory.
      if File.directory?(@filename)
        if Syslog.opened?
          Syslog.log(Syslog::LOG_ERR, 'error: %s is a directory', @filename)
          Syslog.log(Syslog::LOG_INFO, 'shutting down')
          Syslog.close
        end

        abort "** Error: #{@filename} is a directory"
      end

      # Begin watching the file.
      File.open(@filename) do |@file|
        begin
          @file.pos = @lastpos if @lastpos > 0
        rescue EOFError
          @file.rewind
        end

        loop do
          restat

          while line = @file.gets
            @lastpos = @file.pos
            yield line
          end

          @file.seek(0, File::SEEK_CUR)

          sleep @interval
        end
      end
    end

    private

    # Reopens the file. This is necessary if the file is deleted or truncated
    # while we're watching it.
    def reopen
      @file.reopen(@filename)
      @lastpos = 0

      Syslog::log(Syslog::LOG_INFO, 'reopening %s', @filename)

    rescue Errno::ENOENT
    rescue Errno::ESTALE
      # File isn't there. Wait for it to reappear.
      sleep 15
      retry
    end

    # Performs various checks to determine whether we should reopen the file.
    def restat
      stat = File.stat(@filename)

      if !@last_stat.nil?
        if stat.ino != @last_stat.ino || stat.dev != @last_stat.dev
          # File was replaced. Reopen it.
          @last_stat = nil
          reopen
        elsif stat.size < @last_stat.size
          # File was truncated. Reopen it.
          @last_stat = nil
          reopen
        end
      else
        @last_stat = stat
      end

    rescue Errno::ENOENT
    rescue Errno::ESTALE
      # File was deleted. Attempt to reopen it.
      reopen
    end

  end

end


text:
FactoryBot.define do
  factory :eligibility do

    code 'over_65'

    factory :veteran do
      code "veteran"
    end

    initialize_with { Eligibility.find_or_create_by(code: code) }

    # Create translations for the eligibility
    trait :with_translations do
      after(:create) do |elig|
        I18n.available_locales.each do |l|
          elig.set_translation(l, :name, "#{l} #{elig.code} name")
          elig.set_translation(l, :note, "#{l} #{elig.code} note")
          elig.set_translation(l, :question, "#{l} #{elig.code} question")
        end
      end
    end

  end
end


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System
{
    public static class __ArgIterator
    {

        public static IObservable<System.TypedReference> GetNextArg(this IObservable<System.ArgIterator> ArgIteratorValue)
        {
            return Observable.Select(ArgIteratorValue, (ArgIteratorValueLambda) => ArgIteratorValueLambda.GetNextArg());
        }

        public static IObservable<System.TypedReference> GetNextArg(this IObservable<System.ArgIterator> ArgIteratorValue, IObservable<System.RuntimeTypeHandle> rth)
        {
            return Observable.Zip(ArgIteratorValue, rth, (ArgIteratorValueLambda, rthLambda) => ArgIteratorValueLambda.GetNextArg(rthLambda));
        }

        public static IObservable<System.Reactive.Unit> End(this IObservable<System.ArgIterator> ArgIteratorValue)
        {
            return Observable.Do(ArgIteratorValue, (ArgIteratorValueLambda) => ArgIteratorValueLambda.End()).ToUnit();
        }

        public static IObservable<System.Int32> GetRemainingCount(this IObservable<System.ArgIterator> ArgIteratorValue)
        {
            return Observable.Select(ArgIteratorValue, (ArgIteratorValueLambda) => ArgIteratorValueLambda.GetRemainingCount());
        }

        public static IObservable<System.RuntimeTypeHandle> GetNextArgType(this IObservable<System.ArgIterator> ArgIteratorValue)
        {
            return Observable.Select(ArgIteratorValue, (ArgIteratorValueLambda) => ArgIteratorValueLambda.GetNextArgType());
        }

        public static IObservable<System.Int32> GetHashCode(this IObservable<System.ArgIterator> ArgIteratorValue)
        {
            return Observable.Select(ArgIteratorValue, (ArgIteratorValueLambda) => ArgIteratorValueLambda.GetHashCode());
        }

        public static IObservable<System.Boolean> Equals(this IObservable<System.ArgIterator> ArgIteratorValue, IObservable<System.Object> o)
        {
            return Observable.Zip(ArgIteratorValue, o, (ArgIteratorValueLambda, oLambda) => ArgIteratorValueLambda.Equals(oLambda));
        }

    }
}


text:
import BaseProjectRole from './base-project-role';

export class CreateProjectRole extends BaseProjectRole {
    projectRole = {
        name: '',
        description: ''
    };

    activate() {
        this.setTemplateParams();
        this.projectRole.submit = this.createProjectRole.bind(this);
    }

    setTemplateParams() {
        this.ctaButtonLabel = 'Create project role';
    }
}


text:
//
//  Copyright (C) 2001-2012 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#ifndef _RD_MOL_OPS_H_
#define _RD_MOL_OPS_H_

#include <vector>
#include <list>
#include <boost/smart_ptr.hpp>
#include <boost/dynamic_bitset.hpp>

extern const int ci_LOCAL_INF;
namespace RDKit{
  class ROMol;
  class RWMol;
  class Atom;
  class Bond;
  typedef std::vector<double> INVAR_VECT;
  typedef INVAR_VECT::iterator INVAR_VECT_I;
  typedef INVAR_VECT::const_iterator INVAR_VECT_CI;

  //! \brief Groups a variety of molecular query and transformation operations.
  namespace MolOps {

    //! return the number of electrons available on an atom to donate for aromaticity
    /*!
       The result is determined using the default valency, number of lone pairs,
       number of bonds and the formal charge. Note that the atom may not donate
       all of these electrons to a ring for aromaticity (also used in Conjugation
       and hybridization code).

       \param at the atom of interest

       \return the number of electrons
    */
    int countAtomElec(const Atom *at);

    //! sums up all atomic formal charges and returns the result
    int getFormalCharge(const ROMol &mol);

    //! returns whether or not the given Atom is involved in a conjugated bond
    bool atomHasConjugatedBond(const Atom *at);

    //! find fragments (disconnected components of the molecular graph)
    /*!

      \param mol     the molecule of interest
      \param mapping used to return the mapping of Atoms->fragments.
         On return \c mapping will be <tt>mol->getNumAtoms()</tt> long
	 and will contain the fragment assignment for each Atom

      \return the number of fragments found.

    */
    unsigned int getMolFrags(const ROMol &mol,std::vector<int> &mapping);
    //! find fragments (disconnected components of the molecular graph)
    /*!

      \param mol    the molecule of interest
      \param frags  used to return the Atoms in each fragment
         On return \c mapping will be \c numFrags long, and each entry
	 will contain the indices of the Atoms in that fragment.

      \return the number of fragments found.

    */
    unsigned int getMolFrags(const ROMol &mol, std::vector<std::vector<int> > &frags);

    //! splits a molecule into its component fragments
    //  (disconnected components of the molecular graph)
    /*!

      \param mol     the molecule of interest
      \param sanitizeFrags  toggles sanitization of the fragments after
                            they are built
      \param frags used to return the mapping of Atoms->fragments.
         if provided, \c frags will be <tt>mol->getNumAtoms()</tt> long
	 on return and will contain the fragment assignment for each Atom

      \return a vector of the fragments as smart pointers to ROMols

    */
    std::vector<boost::shared_ptr<ROMol> > getMolFrags(const ROMol &mol,
                                                       bool sanitizeFrags=true,
                                                       std::vector<int> *frags=0);

#if 0
    //! finds a molecule's minimium spanning tree (MST)
    /*!
      \param mol  the molecule of interest
      \param mst  used to return the MST as a vector of bond indices
    */
    void findSpanningTree(const ROMol &mol,std::vector<int> &mst);
#endif

    //! calculates Balaban's J index for the molecule
    /*!
      \param mol      the molecule of interest
      \param useBO    toggles inclusion of the bond order in the calculation
                      (when false, we're not really calculating the J value)
      \param force    forces the calculation (instead of using cached results)
      \param bondPath when included, only paths using bonds whose indices occur
                      in this vector will be included in the calculation
      \param cacheIt  If this is true, the calculated value will be cached
                      as a property on the molecule
      \return the J index

    */
    double computeBalabanJ(const ROMol &mol,
				  bool useBO=true,
				  bool force=false,
				  const std::vector<int> *bondPath=0,
				  bool cacheIt=true);
    //! \overload
    double computeBalabanJ(double *distMat, int nb, int nAts);

    //! \name Dealing with hydrogens
    //{@

    //! returns a copy of a molecule with hydrogens added in as explicit Atoms
    /*!
        \param mol          the molecule to add Hs to
        \param explicitOnly (optional) if this \c true, only explicit Hs will be added
        \param addCoords    (optional) If this is true, estimates for the atomic coordinates
                    of the added Hs will be used.

        \return the new molecule

        Notes:
	   - it makes no sense to use the \c addCoords option if the molecule's heavy
	     atoms don't already have coordinates.
	   - the caller is responsible for <tt>delete</tt>ing the pointer this returns.
     */
    ROMol *addHs(const ROMol &mol,bool explicitOnly=false,bool addCoords=false);

    //! returns a copy of a molecule with hydrogens removed
    /*!
        \param mol          the molecule to remove Hs from
        \param implicitOnly (optional) if this \c true, only implicit Hs will be removed
        \param updateExplicitCount  (optional) If this is \c true, when explicit Hs are removed
	     from the graph, the heavy atom to which they are bound will have its counter of
	     explicit Hs increased.
        \param sanitize:  (optional) If this is \c true, the final molecule will be
       sanitized

        \return the new molecule

        Notes:
           - Hydrogens which aren't connected to a heavy atom will not be
             removed.  This prevents molecules like <tt>"[H][H]"</tt> from having
             all atoms removed.
           - Labelled hydrogen (e.g. atoms with atomic number=1, but mass > 1),
             will not be removed.

	   - the caller is responsible for <tt>delete</tt>ing the pointer this returns.
    */
    ROMol *removeHs(const ROMol &mol,bool implicitOnly=false,
			   bool updateExplicitCount=false,bool sanitize=true);

    //! returns a copy of a molecule with hydrogens removed and added as queries
    //!  to the heavy atoms to which they are bound.
    /*!
      This is really intended to be used with molecules that contain QueryAtoms

      \param mol the molecule to remove Hs from

      \return the new molecule

      Notes:
        - Atoms that do not already have hydrogen count queries will have one
	        added, other H-related queries will not be touched. Examples:
	      - C[H] -> [C;!H0]
	      - [C;H1][H] -> [C;H1]
	      - [C;H2][H] -> [C;H2]
        - Hydrogens which aren't connected to a heavy atom will not be
          removed.  This prevents molecules like <tt>"[H][H]"</tt> from having
          all atoms removed.
	      - the caller is responsible for <tt>delete</tt>ing the pointer this returns.

    */
    ROMol *mergeQueryHs(const ROMol &mol);
    //@}

    //! \name Sanitization
    //@{

    typedef enum {
      SANITIZE_NONE=0x0,
      SANITIZE_CLEANUP=0x1,
      SANITIZE_PROPERTIES=0x2,
      SANITIZE_SYMMRINGS=0x4,
      SANITIZE_KEKULIZE=0x8,
      SANITIZE_FINDRADICALS=0x10,
      SANITIZE_SETAROMATICITY=0x20,
      SANITIZE_SETCONJUGATION=0x40,
      SANITIZE_SETHYBRIDIZATION=0x80,
      SANITIZE_CLEANUPCHIRALITY=0x100,
      SANITIZE_ADJUSTHS=0x200,
      SANITIZE_ALL=0xFFFFFFF
    } SanitizeFlags;

    //! \brief carries out a collection of tasks for cleaning up a molecule and ensuring
    //! that it makes "chemical sense"
    /*!
       This functions calls the following in sequence
         -# MolOps::cleanUp()
         -# mol.updatePropertyCache()
         -# MolOps::symmetrizeSSSR()
         -# MolOps::Kekulize()
         -# MolOps::assignRadicals()
         -# MolOps::setAromaticity()
         -# MolOps::setConjugation()
         -# MolOps::setHybridization()
         -# MolOps::cleanupChirality()
         -# MolOps::adjustHs()

       \param mol : the RWMol to be cleaned

       \param operationThatFailed : the first (if any) sanitization operation that fails is set here.
                                    The values are taken from the \c SanitizeFlags enum.
                                    On success, the value is  \c SanitizeFlags::SANITIZE_NONE

       \param sanitizeOps : the bits here are used to set which sanitization operations are carried
                            out. The elements of the \c SanitizeFlags enum define the operations.

       Notes:
        - If there is a failure in the sanitization, a \c SanitException
	  will be thrown.
        - in general the user of this function should cast the molecule following this
          function to a ROMol, so that new atoms and bonds cannot be added to the
          molecule and screw up the sanitizing that has been done here
    */
    void sanitizeMol(RWMol &mol,unsigned int &operationThatFailed,
                     unsigned int sanitizeOps=SANITIZE_ALL);
    //! \overload
    void sanitizeMol(RWMol &mol);

    //! Sets up the aromaticity for a molecule
    /*!

      This is what happens here:
         -# find all the simple rings by calling the findSSSR function
         -# loop over all the Atoms in each ring and mark them if they are candidates
            for aromaticity. A ring atom is a candidate if it can spare electrons
            to the ring and if it's from the first two rows of the periodic table.
         -# ased on the candidate atoms, mark the rings to be either candidates
            or non-candidates. A ring is a candidate only if all its atoms are candidates
         -# apply Hueckel rule to each of the candidate rings to check if the ring can be
	    aromatic

      \param mol the RWMol of interest

      \return 1 on succes, 0 otherwise

      Assumptions:
        - Kekulization has been done (i.e. \c MolOps::Kekulize() has already
	  been called)

    */
    int setAromaticity(RWMol &mol);

    //! Designed to be called by the sanitizer to handle special cases before anything is done.
    /*!

        Currently this:
	 - modifies nitro groups, so that the nitrogen does not have a unreasonable
  	   valence of 5, as follows:
             - the nitrogen gets a positve charge
             - one of the oxygens gets a negative chage and the double bond to this
               oxygen is changed to a single bond
	   The net result is that nitro groups can be counted on to be:
	     \c "[N+](=O)[O-]"

       \param mol    the molecule of interest

    */
    void cleanUp(RWMol &mol);

    //! Called by the sanitizer to assign radical counts to atoms
    void assignRadicals(RWMol &mol);

    //! adjust the number of implicit and explicit Hs for special cases
    /*!

        Currently this:
         - modifies aromatic nitrogens so that, when appropriate, they have an
  	   explicit H marked (e.g. so that we get things like \c "c1cc[nH]cc1"

        \param mol    the molecule of interest

        Assumptions
           - this is called after the molecule has been sanitized,
             aromaticity has been perceived, and the implicit valence of
             everything has been calculated.

    */
    void adjustHs(RWMol &mol);

    //! Kekulizes the molecule
    /*!

       \param mol             the molecule of interest
       \param markAtomsBonds  if this is set to true, \c isAromatic boolean settings
                              on both the Bonds and Atoms are turned to false following
                              the Kekulization, otherwise they are left alone in their
                              original state.
       \param maxBackTracks   the maximum number of attempts at back-tracking. The algorithm
                              uses a back-tracking procedure to revist a previous setting of
                              double bond if we hit a wall in the kekulization process

       Notes:
         - even if \c markAtomsBonds is \c false the \c BondType for all aromatic
	   bonds will be changed from \c RDKit::Bond::AROMATIC to \c RDKit::Bond::SINGLE
	   or RDKit::Bond::DOUBLE during Kekulization.

    */
    void Kekulize(RWMol &mol, bool markAtomsBonds=true, unsigned int maxBackTracks=100);

    //! flags the molecule's conjugated bonds
    void setConjugation(ROMol &mol);

    //! calculates and sets the hybridization of all a molecule's Stoms
    void setHybridization(ROMol &mol);

    // @}

    //! \name Ring finding and SSSR
    //@{

    //! finds a molecule's Smallest Set of Smallest Rings
    /*!
      Currently this implements a modified form of Figueras algorithm
        (JCICS - Vol. 36, No. 5, 1996, 986-991)

      \param mol the molecule of interest
      \param res used to return the vector of rings. Each entry is a vector with
          atom indices.  This information is also stored in the molecule's
	  RingInfo structure, so this argument is optional (see overload)

      \return number of smallest rings found

      Base algorithm:
        - The original algorithm starts by finding representative degree 2
	  nodes.
	- Representative because if a series of deg 2 nodes are found only
          one of them is picked.
        - The smallest ring around each of them is found.
        - The bonds that connect to this degree 2 node are them chopped off, yielding
          new deg two nodes
        - The process is repeated on the new deg 2 nodes.
        - If no deg 2 nodes are found, a deg 3 node is picked. The smallest ring
          with it is found. A bond from this is "carefully" (look in the paper)
          selected and chopped, yielding deg 2 nodes. The process is same as
          above once this is done.

      Our Modifications:
        - If available, more than one smallest ring around a representative deg 2
	  node will be computed and stored
        - Typically 3 rings are found around a degree 3 node (when no deg 2s are available)
	  and all the bond to that node are chopped.
        - The extra rings that were found in this process are removed after all the nodes
	  have been covered.

      These changes were motivated by several factors:
        - We believe the original algorithm fails to find the correct SSSR
          (finds the correct number of them but the wrong ones) on some sample mols
        - Since SSSR may not be unique, a post-SSSR step to symmetrize may be done.
          The extra rings this process adds can be quite useful.
    */
    int findSSSR(const ROMol &mol, std::vector<std::vector<int> > &res);
    //! \overload
    int findSSSR(const ROMol &mol, std::vector<std::vector<int> > *res=0);

    //! use a DFS algorithm to identify ring bonds and atoms in a molecule
    /*!
      \b NOTE: though the RingInfo structure is populated by this function,
      the only really reliable calls that can be made are to check if
      mol.getRingInfo().numAtomRings(idx) or mol.getRingInfo().numBondRings(idx)
      return values >0
    */
    void fastFindRings(const ROMol &mol);

    //! symmetrize the molecule's Smallest Set of Smallest Rings
    /*!
       SSSR rings obatined from "findSSSR" can be non-unique in some case.
       For example, cubane has five SSSR rings, not six as one would hope.

       This function adds additional rings to the SSSR list if necessary
       to make the list symmetric, e.g. all atoms in cubane will be part of the same number
       of SSSRs. This function choses these extra rings from the extra rings computed
       and discarded during findSSSR. The new ring are chosen such that:
        - replacing a same sized ring in the SSSR list with an extra ring yields
          the same union of bond IDs as the orignal SSSR list

      \param mol - the molecule of interest
      \param res used to return the vector of rings. Each entry is a vector with
          atom indices.  This information is also stored in the molecule's
	  RingInfo structure, so this argument is optional (see overload)

      \return the total number of rings = (new rings + old SSSRs)

      Notes:
       - if no SSSR rings are found on the molecule - MolOps::findSSSR() is called first
    */
    int symmetrizeSSSR(ROMol &mol, std::vector<std::vector<int> > &res);
    //! \overload
    int symmetrizeSSSR(ROMol &mol);

    //@}

    //! \name Shortest paths and other matrices
    //@{

    //! returns a molecule's adjacency matrix
    /*!
      \param mol             the molecule of interest
      \param useBO           toggles use of bond orders in the matrix
      \param emptyVal        sets the empty value (for non-adjacent atoms)
      \param force           forces calculation of the matrix, even if already computed
      \param propNamePrefix  used to set the cached property name

      \return the adjacency matrix.

      Notes
        - The result of this is cached in the molecule's local property dictionary,
	  which will handle deallocation. Do the caller should not \c delete
	  this pointer.

    */
    double * getAdjacencyMatrix(const ROMol &mol,
                                bool useBO=false,
                                int emptyVal=0,
                                bool force=false,
                                const char *propNamePrefix=0,
                                const boost::dynamic_bitset<> *bondsToUse=0
                                );

    //! Computes the molecule's topological distance matrix
    /*!
       Uses the Floyd-Warshall all-pairs-shortest-paths algorithm.

      \param mol             the molecule of interest
      \param useBO           toggles use of bond orders in the matrix
      \param useAtomWts      sets the diagonal elements of the result to
               6.0/(atomic number) so that the matrix can be used to calculate
	       Balaban J values.  This does not affect the bond weights.
      \param force           forces calculation of the matrix, even if already computed
      \param propNamePrefix  used to set the cached property name

      \return the distance matrix.

      Notes
        - The result of this is cached in the molecule's local property dictionary,
	  which will handle deallocation. Do the caller should not \c delete
	  this pointer.

    */
    double *getDistanceMat(const ROMol &mol,
				  bool useBO=false,
				  bool useAtomWts=false,
				  bool force=false,
				  const char *propNamePrefix=0);

    //! Computes the molecule's topological distance matrix
    /*!
       Uses the Floyd-Warshall all-pairs-shortest-paths algorithm.

      \param mol             the molecule of interest
      \param activeAtoms     only elements corresponding to these atom indices
                             will be included in the calculation
      \param bonds           only bonds found in this list will be included in the
                             calculation
      \param useBO           toggles use of bond orders in the matrix
      \param useAtomWts      sets the diagonal elements of the result to
               6.0/(atomic number) so that the matrix can be used to calculate
	       Balaban J values.  This does not affect the bond weights.

      \return the distance matrix.

      Notes
        - The results of this call are not cached, the caller should \c delete
	  this pointer.

    */
    double *getDistanceMat(const ROMol &mol,
				  const std::vector<int> &activeAtoms,
				  const std::vector<const Bond *> &bonds,
				  bool useBO=false,
				  bool useAtomWts=false);

    //! Find the shortest path between two atoms
    /*!
      Uses the Bellman-Ford algorithm

     \param mol  molecule of interest
     \param aid1 index of the first atom
     \param aid2 index of the second atom

     \return an std::list with the indices of the atoms along the shortest
        path

     Notes:
       - the starting and end atoms are included in the path
       - if no path is found, an empty path is returned

    */
    std::list<int> getShortestPath(const ROMol &mol, int aid1, int aid2);

    //@}

    //! \name Canonicalization
    //@{

    //! assign a canonical ordering to a molecule's atoms
    /*!
      The algorithm used here is a modification of the published Daylight canonical
      smiles algorithm (i.e. it uses atom invariants and products of primes).

      \param mol               the molecule of interest
      \param ranks             used to return the ranks
      \param breakTies         toggles breaking of ties (see below)
      \param rankHistory       used to return the rank history (see below)

      Notes:
        - Tie breaking should be done when it's important to have a full ordering
          of the atoms (e.g. when generating canonical traversal trees). If it's
	        acceptable to have ties between symmetry-equivalent atoms (e.g. when
	        generating CIP codes), tie breaking can/should be skipped.
	      - if the \c rankHistory argument is provided, the evolution of the ranks of
	        individual atoms will be tracked.  The \c rankHistory pointer should be
	        to a VECT_INT_VECT that has at least \c mol.getNumAtoms() elements.
    */
    void rankAtoms(const ROMol &mol,std::vector<int> &ranks,
                   bool breakTies=true,std::vector<std::vector<int> > *rankHistory=0);
    //! assign a canonical ordering to a sub-molecule's atoms
    /*!
      The algorithm used here is a modification of the published Daylight canonical
      smiles algorithm (i.e. it uses atom invariants and products of primes).

      \param mol               the molecule of interest
      \param atomsToUse        atoms to be included
      \param bondsToUse        bonds to be included
      \param atomSymbols       symbols to use for the atoms in the output (these are
                               used in place of atomic number and isotope information)
      \param ranks             used to return the ranks
      \param breakTies         toggles breaking of ties (see below)
      \param rankHistory       used to return the rank history (see below)

      Notes:
        - Tie breaking should be done when it's important to have a full ordering
          of the atoms (e.g. when generating canonical traversal trees). If it's
	        acceptable to have ties between symmetry-equivalent atoms (e.g. when
	        generating CIP codes), tie breaking can/should be skipped.
	      - if the \c rankHistory argument is provided, the evolution of the ranks of
	        individual atoms will be tracked.  The \c rankHistory pointer should be
	        to a VECT_INT_VECT that has at least \c mol.getNumAtoms() elements.
    */
    void rankAtomsInFragment(const ROMol &mol,std::vector<int> &ranks,
                             const boost::dynamic_bitset<> &atomsToUse,
                             const boost::dynamic_bitset<> &bondsToUse,
                             const std::vector<std::string> *atomSymbols=0,
                             const std::vector<std::string> *bondSymbols=0,
                             bool breakTies=true,
                             std::vector<std::vector<int> > *rankHistory=0);

    // @}

    //! \name Stereochemistry
    //@{

    //! removes bogus chirality markers (those on non-sp3 centers):
    void cleanupChirality(RWMol &mol);

    //! \brief Uses a conformer to assign ChiralType to a molecule's atoms
    /*!
      \param mol                  the molecule of interest
      \param confId               the conformer to use
      \param replaceExistingTags  if this flag is true, any existing atomic chiral
                                  tags will be replaced

      If the conformer provided is not a 3D conformer, nothing will be done.
    */
    void assignChiralTypesFrom3D(ROMol &mol,int confId=-1,bool replaceExistingTags=true);

    //! Assign stereochemistry tags to atoms (i.e. R/S) and bonds (i.e. Z/E)
    /*!

      \param mol     the molecule of interest
      \param cleanIt toggles removal of stereo flags from double bonds that can
                     not have stereochemistry
      \param force   forces the calculation to be repeated even if it has
                     already been done
      \param flagPossibleStereoCenters   set the _ChiralityPossible property on
                                         atoms that are possible stereocenters

      Notes:M
        - Throughout we assume that we're working with a hydrogen-suppressed
          graph.

    */
    void assignStereochemistry(ROMol &mol,bool cleanIt=false,bool force=false,
                               bool flagPossibleStereoCenters=false);
    //! Removes all stereochemistry information from atoms (i.e. R/S) and bonds (i.e. Z/E)
    /*!

      \param mol     the molecule of interest
    */
    void removeStereochemistry(ROMol &mol);

    //! \brief finds bonds that could be cis/trans in a molecule and mark them as
    //!  Bond::STEREONONE
    /*!
      \param mol     the molecule of interest
      \param cleanIt toggles removal of stereo flags from double bonds that can
                     not have stereochemistry

      This function is usefuly in two situations
        - when parsing a mol file; for the bonds marked here, coordinate informations
	  on the neighbors can be used to indentify cis or trans states
        - when writing a mol file; bonds that can be cis/trans but not marked as either
	  need to be specially marked in the mol file
    */
    void findPotentialStereoBonds(ROMol &mol,bool cleanIt=false);
    //@}

  }; // end of namespace MolOps
}; // end of namespace RDKit

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd">
    <changeSet author="frankfu"
               id="1593385206-1"
               objectQuotingStrategy="QUOTE_ALL_OBJECTS">
        <createTable tableName="sitelog_associateddocument">
            <column name="document_id" type="INT">
                <constraints nullable="false"/>
            </column>
            <column name="site_id" type="INT">
                <constraints nullable="false"/>
            </column>
        </createTable>
    </changeSet>
    <changeSet author="frankfu"
               id="1593385206-2"
               objectQuotingStrategy="QUOTE_ALL_OBJECTS">
        <addPrimaryKey columnNames="document_id, site_id"
                       constraintName="pk_sitelog_associateddocument_ids"
                       tableName="sitelog_associateddocument"/>
        <addForeignKeyConstraint baseColumnNames="document_id"
                                 baseTableName="sitelog_associateddocument"
                                 constraintName="fk_sitelog_associateddocument_document_id"
                                 deferrable="false"
                                 initiallyDeferred="false"
                                 onDelete="NO ACTION"
                                 onUpdate="NO ACTION"
                                 referencedColumnNames="id"
                                 referencedTableName="document"/>
        <addForeignKeyConstraint baseColumnNames="site_id"
                                 baseTableName="sitelog_associateddocument"
                                 constraintName="fk_sitelog_associateddocument_site_id"
                                 deferrable="false"
                                 initiallyDeferred="false"
                                 onDelete="NO ACTION"
                                 onUpdate="NO ACTION"
                                 referencedColumnNames="id"
                                 referencedTableName="sitelog_site"/>
        <setTableRemarks remarks="A join table of GNSS site and associated documents in site log"
                         tableName="sitelog_associateddocument"/>
    </changeSet>
</databaseChangeLog>


text:
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI.Ingame;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System;
using VRage.Collections;
using VRage.Game.Components;
using VRage.Game.GUI.TextPanel;
using VRage.Game.ModAPI.Ingame.Utilities;
using VRage.Game.ModAPI.Ingame;
using VRage.Game.ObjectBuilders.Definitions;
using VRage.Game;
using VRage;
using VRageMath;
using System.Collections.Immutable;

namespace IngameScript
{
    // This template is intended for extension classes. For most purposes you're going to want a normal
    // utility class.
    // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
    static class $safeitemrootname$
	{

	}
}


text:
//
//  YARecommendTopic.h
//  YAQQNews
//
//  Created by 陈亚伦 on 2017/5/27.
//  Copyright © 2017年 陈亚伦. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface YARecommendTopic : NSObject
/** topicID */
@property (nonatomic, copy) NSString *tpid;
/** 话题名称 */
@property (nonatomic, copy) NSString *tpname;
/** 话题描述 */
@property (nonatomic, copy) NSString *desc;
/** 图标 */
@property (nonatomic, copy) NSString *icon;
/** 话题分类 */
@property (nonatomic, copy) NSString *catName;
/** 时间戳 */
@property (nonatomic, copy) NSString *lastArtUpdate;
/** 标题 */
@property (nonatomic, copy) NSString *title;
/** 订阅数量 */
@property (nonatomic, assign) NSUInteger subCount;
/** 更新周 */
@property (nonatomic, assign) NSUInteger updateWeek;
/** 索引*/
@property (nonatomic, assign) NSUInteger index;

@end


text:
"use strict";var diff=require("../diff")
var patch=require("../patch")
exports["test diff"]=require("./diff")
exports["test patch"]=require("./patch")
exports["test patch(a, diff(a, b)) => b"]=function(assert){var a={a:{b:1},c:{d:2}}
var b={a:{e:3},c:{d:4}}
assert.deepEqual(patch(a,diff(a,b)),b,"patch(a, diff(a, b)) => b")}


text:
<?php

namespace feedly\Mode;

interface Mode
{

    public function getApiBaseUrl();

}


text:
require 'spec_helper'

describe "the template function" do
  before :all do
    Puppet::Parser::Functions.autoloader.loadall
  end

  let :node     do Puppet::Node.new('localhost') end
  let :compiler do Puppet::Parser::Compiler.new(node) end
  let :scope    do Puppet::Parser::Scope.new(compiler) end

  it "concatenates outputs for multiple templates" do
    tw1 = stub_everything "template_wrapper1"
    tw2 = stub_everything "template_wrapper2"
    Puppet::Parser::TemplateWrapper.stubs(:new).returns(tw1,tw2)
    tw1.stubs(:file=).with("1")
    tw2.stubs(:file=).with("2")
    tw1.stubs(:result).returns("result1")
    tw2.stubs(:result).returns("result2")

    scope.function_template(["1","2"]).should == "result1result2"
  end

  it "raises an error if the template raises an error" do
    tw = stub_everything 'template_wrapper'
    Puppet::Parser::TemplateWrapper.stubs(:new).returns(tw)
    tw.stubs(:result).raises

    expect {
      scope.function_template(["1"])
    }.to raise_error(Puppet::ParseError, /Failed to parse template/)
  end

  context "when accessing scope variables via method calls (deprecated)" do
    it "raises an error when accessing an undefined variable" do
      expect {
        eval_template("template <%= deprecated %>")
      }.to raise_error(Puppet::ParseError, /Could not find value for 'deprecated'/)
    end

    it "looks up the value from the scope" do
      scope["deprecated"] = "deprecated value"
      eval_template("template <%= deprecated %>").should == "template deprecated value"
    end

    it "still has access to Kernel methods" do
      expect { eval_template("<%= binding %>") }.to_not raise_error
    end
  end

  context "when accessing scope variables as instance variables" do
    it "has access to values" do
      scope['scope_var'] = "value"
      eval_template("<%= @scope_var %>").should == "value"
    end

    it "get nil accessing a variable that does not exist" do
      eval_template("<%= @not_defined.nil? %>").should == "true"
    end

    it "get nil accessing a variable that is undef" do
      scope['undef_var'] = :undef
      eval_template("<%= @undef_var.nil? %>").should == "true"
    end
  end

  it "is not interfered with by having a variable named 'string' (#14093)" do
    scope['string'] = "this output should not be seen"
    eval_template("some text that is static").should == "some text that is static"
  end

  it "has access to a variable named 'string' (#14093)" do
    scope['string'] = "the string value"
    eval_template("string was: <%= @string %>").should == "string was: the string value"
  end

  it "does not have direct access to Scope#lookupvar" do
    expect {
      eval_template("<%= lookupvar('myvar') %>")
    }.to raise_error(Puppet::ParseError, /Could not find value for 'lookupvar'/)
  end

  def eval_template(content)
    Puppet::FileSystem.stubs(:read_preserve_line_endings).with("template").returns(content)
    Puppet::Parser::Files.stubs(:find_template).returns("template")
    scope.function_template(['template'])
  end
end


text:
function[x,w] = gauss_radau_quadrature(N,varargin)
% gauss_radau_quadrature -- Gauss-Radau quadrature rule for Laguerre polynomials
%
% [x,w] = gauss_radau_quadrature(N,{alpha=0,shift=0,scale=1,r=0})
%
%     Returns the N-point Gauss-Radau quadrature rule for the Laguerre polynomials.
%     The weight function is given by speclab.orthopoly.laguerre.weights.weight.
%     The Radau point is located at x=r.

persistent defaults pss sss recurrence grq
if isempty(defaults)
  from speclab.orthopoly.laguerre import defaults recurrence
  from speclab.orthopoly import gauss_radau_quadrature as grq
  from speclab.common import standard_scaleshift_1d as sss
  from speclab.common import physical_scaleshift_1d as pss
end

opt = defaults(varargin{:});
[scale,shift,r] = deal(opt.scale,opt.shift,opt.r);
r = sss(r,opt);

[a,b] = recurrence(N,opt);
[x,w] = grq(a,b,N,r);

x = pss(x,opt);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ByteBufferInputStream</title>
<meta name="date" content="2015-09-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

info.ata4.util.io

Class ByteBufferInputStream

java.lang.Object

java.io.InputStream

info.ata4.util.io.ByteBufferInputStream

All Implemented Interfaces:

java.io.Closeable, java.lang.AutoCloseable

public class ByteBufferInputStream
extends java.io.InputStream

InputStream wrapper for a ByteBuffer object.

Constructor Summary

Constructors

Constructor and Description

ByteBufferInputStream(java.nio.ByteBuffer buf)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.nio.ByteBuffer
getByteBuffer()

int
read()

int
read(byte[] bytes,
    int off,
    int len)

Methods inherited from class java.io.InputStream

available, close, mark, markSupported, read, reset, skip

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ByteBufferInputStream

public ByteBufferInputStream(java.nio.ByteBuffer buf)

Method Detail

getByteBuffer

public java.nio.ByteBuffer getByteBuffer()

read

public int read()
         throws java.io.IOException

Specified by:

read in class java.io.InputStream

Throws:

java.io.IOException

read

public int read(byte[] bytes,
                int off,
                int len)
         throws java.io.IOException

Overrides:

read in class java.io.InputStream

Throws:

java.io.IOException

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
class InlineCodeClass
  attr_accessible :name
end


text:
#include <pcl/apps/optronic_viewer/qt.h>
#include <pcl/apps/optronic_viewer/main_window.h>

int main( int argc, char** argv )
{
  QApplication app( argc, argv );
  app.setOrganizationName("PCL");
  app.setApplicationName("PCL Optronic Viewer");

  pcl::apps::optronic_viewer::MainWindow::getInstance().show();

  return app.exec();
}


text:
import Path from './path';
import ownerDocument from '../document';
import Attr from '../attribute/ring';

export default class Ring extends Path {
  static Attr = Attr;

  /* override */
  get isVisible() {
    const {innerRadius, outerRadius, startAngle, endAngle} = this.attributes;
    return (innerRadius > 0 || outerRadius > 0) && startAngle !== endAngle && super.isVisible;
  }
}

ownerDocument.registerNode(Ring, 'ring');


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>tesseract: /home/stweil/src/github/tesseract-ocr/tesseract/classify/mastertrainer.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

tesseract
    4.0.0-beta.1-59-g2cc4

Classes |
Namespaces

mastertrainer.h File Reference

#include "classify.h"

#include "cluster.h"

#include "intfx.h"

#include "elst.h"

#include "errorcounter.h"

#include "featdefs.h"

#include "fontinfo.h"

#include "indexmapbidi.h"

#include "intfeaturespace.h"

#include "intfeaturemap.h"

#include "intmatcher.h"

#include "params.h"

#include "shapetable.h"

#include "trainingsample.h"

#include "trainingsampleset.h"

#include "unicharset.h"

Go to the source code of this file.

Classes

struct  	tesseract::ShapeDist

class  	tesseract::MasterTrainer

Namespaces

  	tesseract

classify

mastertrainer.h

Generated on Wed Mar 28 2018 20:00:40 for tesseract by

     1.8.13


text:
package com.cognizant.devops.platformdal.assessmentreport;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="\"INSIGHTS_VISUALIZATION_CONFIGURATION\"")
public class InsightsVisualizationConfig implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -7119630708603019443L;

	@Id
	@Column(name="vType")
	private String vType;

	@Column(name="vDescription")
	private String vDescritpion;

	public String getvType() {
		return vType;
	}

	public void setvType(String vType) {
		this.vType = vType;
	}

	public String getvDescritpion() {
		return vDescritpion;
	}

	public void setvDescritpion(String vDescritpion) {
		this.vDescritpion = vDescritpion;
	}

}


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

package org.rocksdb;

/**
 * Comparators are used by RocksDB to determine
 * the ordering of keys.
 *
 * This class is package private, implementers
 * should extend either of the public abstract classes:
 *   @see org.rocksdb.Comparator
 *   @see org.rocksdb.DirectComparator
 */
public abstract class AbstractComparator<T extends AbstractSlice<?>>
    extends RocksCallbackObject {

  protected AbstractComparator(final ComparatorOptions copt) {
    super(copt.nativeHandle_);
  }

  /**
   * The name of the comparator.  Used to check for comparator
   * mismatches (i.e., a DB created with one comparator is
   * accessed using a different comparator).
   *
   * A new name should be used whenever
   * the comparator implementation changes in a way that will cause
   * the relative ordering of any two keys to change.
   *
   * Names starting with "rocksdb." are reserved and should not be used.
   *
   * @return The name of this comparator implementation
   */
  public abstract String name();

  /**
   * Three-way key comparison
   *
   *  @param a Slice access to first key
   *  @param b Slice access to second key
   *
   *  @return Should return either:
   *    1) < 0 if "a" < "b"
   *    2) == 0 if "a" == "b"
   *    3) > 0 if "a" > "b"
   */
  public abstract int compare(final T a, final T b);

  /**
   *
Used to reduce the space requirements
   * for internal data structures like index blocks.

   *
   *
If start < limit, you may return a new start which is a
   * shorter string in [start, limit).

   *
   *
Simple comparator implementations may return null if they
   * wish to use start unchanged. i.e., an implementation of
   * this method that does nothing is correct.

   *
   * @param start String
   * @param limit of type T
   *
   * @return a shorter start, or null
   */
  public String findShortestSeparator(final String start, final T limit) {
      return null;
  }

  /**
   *
Used to reduce the space requirements
   * for internal data structures like index blocks.

   *
   *
You may return a new short key (key1) where
   * key1 ≥ key.

   *
   *
Simple comparator implementations may return null if they
   * wish to leave the key unchanged. i.e., an implementation of
   * this method that does nothing is correct.

   *
   * @param key String
   *
   * @return a shorter key, or null
   */
  public String findShortSuccessor(final String key) {
      return null;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated 22-May-2008 15:08:32.0937500 -->
<!-- Generated by MathSBML 2.7.5 [2-May-2008] -->
<!-- Generated using Mathematica Version 5.2 for Microsoft Windows (June 20, 2005) -->
<sbml xmlns="http://www.sbml.org/sbml/level2/version3"
    level="2"
    version="3">
 <model id="case00719"
     name="case00719"
     metaid="_case00719">
  <!-- <listOfFunctionDefinitions/> -->
  <!-- <listOfUnitDefinitions/> -->
  <!-- <listOfCompartmentTypes/> -->
  <!-- <listOfSpeciesTypes/> -->
  <listOfCompartments>
   <compartment id="C"
       name="C"
       spatialDimensions="3"
       units="volume"
       size="1."/>
  </listOfCompartments>
  <listOfSpecies>
   <species id="S1"
       name="S1"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="1.5"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S2"
       name="S2"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="2."
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S3"
       name="S3"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="1.5"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S4"
       name="S4"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="4."
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
  </listOfSpecies>
  <listOfParameters>
   <parameter id="k1"
       name="k1"
       value="0.75"/>
   <parameter id="k2"
       name="k2"
       value="0.25"/>
  </listOfParameters>
  <!-- <listOfInitialAssignments/> -->
  <listOfRules>
   <rateRule variable="S3"
       metaid="rule1">
    <math xmlns="http://www.w3.org/1998/Math/MathML">
     <apply>
      <times/>
      <cn type="real">0.5</cn>
      <ci>k1</ci>
     </apply>
    </math>
   </rateRule>
   <rateRule variable="S4"
       metaid="rule2">
    <math xmlns="http://www.w3.org/1998/Math/MathML">
     <apply>
      <times/>
      <cn type="real">-0.5</cn>
      <ci>k2</ci>
     </apply>
    </math>
   </rateRule>
  </listOfRules>
  <!-- <listOfConstraints/> -->
  <listOfReactions>
   <reaction id="reaction1"
       name="reaction1"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S1"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S2"
         stoichiometry="2"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>C</ci>
       <ci>k1</ci>
       <ci>S1</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
  </listOfReactions>
  <!-- <listOfEvents/> -->
 </model>
</sbml>


text:
module ActionController
  class CgiRequest
    alias :initialize_aliased_by_facebooker :initialize

    def initialize(cgi, session_options = {})
      initialize_aliased_by_facebooker(cgi, session_options)
      @cgi.instance_variable_set("@request_params", request_parameters.merge(query_parameters))
    end

    DEFAULT_SESSION_OPTIONS[:cookie_only] = false
  end
end

module ActionController
  class RackRequest < AbstractRequest #:nodoc:
    alias :initialize_aliased_by_facebooker :initialize

    def initialize(cgi, session_options = {})
      initialize_aliased_by_facebooker(cgi, session_options)
      @cgi.instance_variable_set("@request_params", request_parameters.merge(query_parameters))
    end
  end
end

class CGI
  class Session
    private
      alias :initialize_aliased_by_facebooker :initialize
      attr_reader :request, :initialization_options

      def initialize(request, option={})
        @request = request
        @initialization_options = option
        option['session_id'] ||= set_session_id
        initialize_aliased_by_facebooker(request, option)
      end

      def set_session_id
        if session_key_should_be_set_with_facebook_session_key?
          request_parameters[facebook_session_key]
        else
          request_parameters[session_key]
        end
      end

      def request_parameters
        request.instance_variable_get("@request_params")
      end

      def session_key_should_be_set_with_facebook_session_key?
        request_parameters[session_key].blank? && !request_parameters[facebook_session_key].blank?
      end

      def session_key
        initialization_options['session_key'] || '_session_id'
      end

      def facebook_session_key
        'fb_sig_session_key'
      end

      alias :create_new_id_aliased_by_facebooker :create_new_id

      def create_new_id
        @new_session = true
        @session_id || create_new_id_aliased_by_facebooker
      end
  end
end


text:
<?php
/**
 * @author Michał Pawłowski <michal@pawlowski.be>
 */

namespace Vero\Debug;

use ErrorException;

/**
 * PHP Error handler.
 */
class ErrorHandler
{
    private $levels = [
        E_WARNING           => 'Warning',
        E_NOTICE            => 'Notice',
        E_USER_ERROR        => 'User Error',
        E_USER_WARNING      => 'User Warning',
        E_USER_NOTICE       => 'User Notice',
        E_STRICT            => 'Runtime Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
        E_DEPRECATED        => 'Deprecated',
        E_USER_DEPRECATED   => 'User Deprecated',
    ];

    /**
     * Register this handler.
     */
    public function register()
    {
        set_error_handler(array($this, 'handle'));
    }

    /**
     * Unregister this handler.
     */
    public function unregister()
    {
        set_error_handler(null);
    }

    /**
     * Handle PHP error.
     */
    public function handle($level, $message, $file, $line)
    {
        if (error_reporting() & $level) {
            $lvl = isset($this->levels[$level]) ? $this->levels[$level] : $level;
            throw new ErrorException("$lvl: $message in $file:$line", 0, $level, $file, $line);
        }

        return false;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.Communication.CallingServer
{
    [CodeGenModel("RecordingStateResponse")]
    public partial class RecordingStateResult
    {
    }
}


text:
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using PathFinder.Cars.DAL.Model;

namespace PathFinder.Cars.WebApi.Extensions
{
    internal static class CarsContextModelsExtensions
    {
        public static async Task<CarModel> FindModelByIdAsync(this IOrderedQueryable<CarModel> models, int id)
        {
            CarModel carModel = await models.FirstOrDefaultAsync(cm => cm.Id == id);

            return carModel;
        }

        public static async Task<IEnumerable<CarModel>> FindModelsByBrandIdAsync(this IOrderedQueryable<CarBrand> brands, int brandId)
        {
            CarBrand brand = await brands
                .Include(b => b.CarModels).FirstOrDefaultAsync(b => b.Id == brandId);

            return brand == null ? null : brand.CarModels;
        }
    }
}


text:
<?xml version="1.0"?>
<package format="2">
  <name>cirkit_unit03_bringup</name>
  <version>0.1.0</version>
  <description>The cirkit_unit03_bringup package</description>

  <maintainer email="k104009y@mail.kyutech.jp">Arita Yuta</maintainer>
  <maintainer email="o111027y@mail.kyutech.jp">Doi Yusuke</maintainer>
  <maintainer email="p595201m@mail.kyutech.jp">Masaru Morita</maintainer>
  <maintainer email="k104073r@mail.kyutech.jp">Ryodo Tanaka</maintainer>
  <license>BSD</license>
  <url type="repository">https://github.com/CIR-KIT-Unit03/cirkit_unit03_robot.git</url>
  <url type="bugtracker">https://github.com/CIR-KIT-Unit03/cirkit_unit03_robot/issues</url>
  <author email="cirkit.infomation@gmail.com">CIR-KIT</author>

  <buildtool_depend>catkin</buildtool_depend>
  <exec_depend>cirkit_unit03_base</exec_depend>
  <exec_depend>cirkit_unit03_control</exec_depend>
  <exec_depend>cirkit_unit03_description</exec_depend>
  <exec_depend>hokuyo_node</exec_depend>
  <exec_depend>hokuyo3d</exec_depend>
  <exec_depend>joint_state_publisher</exec_depend>
  <exec_depend>robot_state_publisher</exec_depend>
  <exec_depend>roslaunch</exec_depend>
</package>


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Text.RE.CaptureID where

import           Data.Ix
import           Data.Hashable
import qualified Data.HashMap.Strict            as HMS
import           Data.Maybe
import qualified Data.Text                      as T

-- | CaptureID identifies captures, either by number
-- (e.g., [cp|1|]) or name (e.g., [cp|foo|]).
data CaptureID
  = IsCaptureOrdinal CaptureOrdinal
  | IsCaptureName    CaptureName
  deriving (Show,Ord,Eq)

-- | the dictionary for named captures stored in compiled regular
-- expressions associates
type CaptureNames = HMS.HashMap CaptureName CaptureOrdinal

-- | an empty 'CaptureNames' dictionary
noCaptureNames :: CaptureNames
noCaptureNames = HMS.empty

-- | a 'CaptureName' is just the text of the name
newtype CaptureName = CaptureName { getCaptureName :: T.Text }
  deriving (Show,Ord,Eq)

instance Hashable CaptureName where
  hashWithSalt i = hashWithSalt i . getCaptureName

-- | a 'CaptureOrdinal' is just the number of the capture, starting
-- with 0 for the whole of the text matched, then in leftmost,
-- outermost
newtype CaptureOrdinal = CaptureOrdinal { getCaptureOrdinal :: Int }
  deriving (Show,Ord,Eq,Enum,Ix,Num)

-- | look up a 'CaptureID' in the 'CaptureNames' dictionary
findCaptureID :: CaptureID -> CaptureNames -> Int
findCaptureID (IsCaptureOrdinal o) _   = getCaptureOrdinal o
findCaptureID (IsCaptureName    n) hms =
    getCaptureOrdinal $ fromMaybe oops $ HMS.lookup n hms
  where
    oops = error $ unlines $
      ("lookupCaptureID: " ++ T.unpack t ++ " not found in:") :
        [ "  "++T.unpack (getCaptureName nm) | nm <- HMS.keys hms ]
    t = getCaptureName n


text: void testQuat ();


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="error_title">Oops Perdón!</string>
  <string name="error_message">Ocurrió un error. Intenta otra vez</string>
  <string name="error_ok_button_text">OK</string>
  <string name="network_error">Conexión no disponible!</string>
</resources>