text:
Accelero
========

This jQuery Plugin was created to manage multiple layers of both vertical and horizontal parallax.  It also combines the ability to add 3D depth by using CSS 3D transforms to rotate and move each layer based on your interaction.

The name Accelero comes from another awesome feature... if your device has an Accelerometer, you can use it to control the parallax.

There are plenty of settings to make this work right for you.  Check out our demos to get an idea of what this plugin can do.

**Follow me on Twitter for Updates**: [@mrmidi](http://twitter.com/mrmidi)

Demo
---
* [Touch & Mouse Based Control](http://lab.peterschmalfeldt.com/accelero/demos/touch.html)
* [Device Accelerometer Control](http://lab.peterschmalfeldt.com/accelero/demos/orientation.html) ( **Cool Note**: Mac Laptops can use this too )

[](http://lab.peterschmalfeldt.com/accelero/demos/touch.html "Touch & Mouse Based Control")

Usage
---
This plugin is hopefully pretty straight forward.  You just make a DIV with the class of **accelero**.  Then you put some more DIVs in that accelero DIV that you want to make awesome.

If for some reason you want to have a DIV inside accelero be ignored so it does not move, just give that DIV a class of **ignore**.

You will likely want to use CSS to set sizes and the images you want for your new found awesomeness, so check out the demos on how we set things up.

Settings
---

You can configure the plugin via the following JavaScript Settings.  Default values shown.

	/** Choose which method you want to control motion. Preference given to orientation and then touch */
	controlMethod: 'auto' // options: auto, touch & orientation

	/** Whether to use CSS Transform Translate to Move X & Y */
	enableMove: true

	/** Whether to use CSS Transform Rotation to Rotate X & Y */
	enableRotate: true

	/** Invert the Layers opposite of how you have them in your HTML */
	invertLayerStack: false

	/** Whether to Flip the X Axis Movement Calculations. Does nothing if enableMove is false. */
	invertMoveX: false

	/** Whether to Flip the Y Axis Movement Calculations. Does nothing if enableMove is false. */
	invertMoveY: false

	/** Whether to Flip the X Axis Rotation Calculations. Does nothing if enableRotate is false. */
	invertRotateX: false

	/** Whether to Flip the Y Axis Rotation Calculations. Does nothing if enableRotate is false. */
	invertRotateY: false

	/** How much rotation to use. Setting it above 45 not recommended. Does nothing if enableRotate is false. */
	maxAngle: 3

	/** Adjust how quickly each layer moves. Does nothing if enableMove is false. */
	speed: 0.2

Or you can use data attributes on the element you will be using for Accelero

	data-control-method="auto"

	data-enable-move="true"

	data-enable-rotate="true"

	data-invert-layer-stack="false"

	data-invert-move-x="false"

	data-invert-move-y="false"

	data-invert-rotate-x="false"

	data-invert-rotate-y="false"

	data-max-angle="3"

	data-speed="0.2"

Example
---

The following example will automatically execute the Accelero plugin since there is a DIV with a class of accelero.

You can put whatever you want here, and since it has an ignore class it will not move

If you would like to change some settings without creating any JavaScript, you can do so using data attributes.

But maybe you want to control when the plugin gets used... thats fine too

And, FYI, you can still use the data attributes and not have to pass them over when you're ready to call Accelero


text:
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "basetypes.h"
#include "tier1/convar.h"
#include "tier1/strtools.h"
#include "tier1/characterset.h"
#include "tier1/utlbuffer.h"
#include "tier1/tier1.h"
#include "tier1/convar_serverbounded.h"
#include "icvar.h"
#include "tier0/dbg.h"
#include "Color.h"
#if defined( _X360 )
#include "xbox/xbox_console.h"
#endif
#include "tier0/memdbgon.h"

#ifndef NDEBUG
// Comment this out when we release.
#define ALLOW_DEVELOPMENT_CVARS
#endif

//-----------------------------------------------------------------------------
// Statically constructed list of ConCommandBases,
// used for registering them with the ICVar interface
//-----------------------------------------------------------------------------
ConCommandBase			*ConCommandBase::s_pConCommandBases = NULL;
IConCommandBaseAccessor	*ConCommandBase::s_pAccessor = NULL;
static int s_nCVarFlag = 0;
static int s_nDLLIdentifier = -1;	// A unique identifier indicating which DLL this convar came from
static bool s_bRegistered = false;

class CDefaultAccessor : public IConCommandBaseAccessor
{
public:
	virtual bool RegisterConCommandBase( ConCommandBase *pVar )
	{
		// Link to engine's list instead
		g_pCVar->RegisterConCommand( pVar );
		return true;
	}
};

static CDefaultAccessor s_DefaultAccessor;

//-----------------------------------------------------------------------------
// Called by the framework to register ConCommandBases with the ICVar
//-----------------------------------------------------------------------------
void ConVar_Register( int nCVarFlag, IConCommandBaseAccessor *pAccessor )
{
	if ( !g_pCVar || s_bRegistered )
		return;

	Assert( s_nDLLIdentifier < 0 );
	s_bRegistered = true;
	s_nCVarFlag = nCVarFlag;
	s_nDLLIdentifier = g_pCVar->AllocateDLLIdentifier();

	ConCommandBase *pCur, *pNext;

	ConCommandBase::s_pAccessor = pAccessor ? pAccessor : &s_DefaultAccessor;
	pCur = ConCommandBase::s_pConCommandBases;
	while ( pCur )
	{
		pNext = pCur->m_pNext;
		pCur->AddFlags( s_nCVarFlag );
		pCur->Init();
		pCur = pNext;
	}

	g_pCVar->ProcessQueuedMaterialThreadConVarSets();
	ConCommandBase::s_pConCommandBases = NULL;
}

void ConVar_Unregister( )
{
	if ( !g_pCVar || !s_bRegistered )
		return;

	Assert( s_nDLLIdentifier >= 0 );
	g_pCVar->UnregisterConCommands( s_nDLLIdentifier );
	s_nDLLIdentifier = -1;
	s_bRegistered = false;
}

//-----------------------------------------------------------------------------
// Purpose: Default constructor
//-----------------------------------------------------------------------------
ConCommandBase::ConCommandBase( void )
{
	m_bRegistered   = false;
	m_pszName       = NULL;
	m_pszHelpString = NULL;

	m_nFlags = 0;
	m_pNext  = NULL;
}

//-----------------------------------------------------------------------------
// Purpose: The base console invoked command/cvar interface
// Input  : *pName - name of variable/command
//			*pHelpString - help text
//			flags - flags
//-----------------------------------------------------------------------------
ConCommandBase::ConCommandBase( const char *pName, const char *pHelpString /*=0*/, int flags /*= 0*/ )
{
	Create( pName, pHelpString, flags );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ConCommandBase::~ConCommandBase( void )
{
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool ConCommandBase::IsCommand( void ) const
{
//	Assert( 0 ); This can't assert. . causes a recursive assert in Sys_Printf, etc.
	return true;
}

//-----------------------------------------------------------------------------
// Returns the DLL identifier
//-----------------------------------------------------------------------------
CVarDLLIdentifier_t ConCommandBase::GetDLLIdentifier() const
{
	return s_nDLLIdentifier;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *pName -
//			callback -
//			*pHelpString -
//			flags -
//-----------------------------------------------------------------------------
void ConCommandBase::Create( const char *pName, const char *pHelpString /*= 0*/, int flags /*= 0*/ )
{
	static char *empty_string = "";

	m_bRegistered = false;

	// Name should be static data
	Assert( pName );
	m_pszName = pName;
	m_pszHelpString = pHelpString ? pHelpString : empty_string;

	m_nFlags = flags;

#ifdef ALLOW_DEVELOPMENT_CVARS
	m_nFlags &= ~FCVAR_DEVELOPMENTONLY;
#endif

	if ( !( m_nFlags & FCVAR_UNREGISTERED ) )
	{
		m_pNext = s_pConCommandBases;
		s_pConCommandBases = this;
	}
	else
	{
		// It's unregistered
		m_pNext = NULL;
	}

	// If s_pAccessor is already set (this ConVar is not a global variable),
	//  register it.
	if ( s_pAccessor )
	{
		Init();
	}
}

//-----------------------------------------------------------------------------
// Purpose: Used internally by OneTimeInit to initialize.
//-----------------------------------------------------------------------------
void ConCommandBase::Init()
{
	if ( s_pAccessor )
	{
		s_pAccessor->RegisterConCommandBase( this );
	}
}

void ConCommandBase::Shutdown()
{
	if ( g_pCVar )
	{
		g_pCVar->UnregisterConCommand( this );
	}
}

//-----------------------------------------------------------------------------
// Purpose: Return name of the command/var
// Output : const char
//-----------------------------------------------------------------------------
const char *ConCommandBase::GetName( void ) const
{
	return m_pszName;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : flag -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool ConCommandBase::IsFlagSet( int flag ) const
{
	return ( flag & m_nFlags ) ? true : false;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : flags -
//-----------------------------------------------------------------------------
void ConCommandBase::AddFlags( int flags )
{
	m_nFlags |= flags;

#ifdef ALLOW_DEVELOPMENT_CVARS
	m_nFlags &= ~FCVAR_DEVELOPMENTONLY;
#endif
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : const ConCommandBase
//-----------------------------------------------------------------------------
const ConCommandBase *ConCommandBase::GetNext( void ) const
{
	return m_pNext;
}

ConCommandBase *ConCommandBase::GetNext( void )
{
	return m_pNext;
}

//-----------------------------------------------------------------------------
// Purpose: Copies string using local new/delete operators
// Input  : *from -
// Output : char
//-----------------------------------------------------------------------------
char *ConCommandBase::CopyString( const char *from )
{
	int		len;
	char	*to;

	len = strlen( from );
	if ( len <= 0 )
	{
		to = new char[1];
		to[0] = 0;
	}
	else
	{
		to = new char[len+1];
		Q_strncpy( to, from, len+1 );
	}
	return to;
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : const char
//-----------------------------------------------------------------------------
const char *ConCommandBase::GetHelpText( void ) const
{
	return m_pszHelpString;
}

//-----------------------------------------------------------------------------
// Purpose: Has this cvar been registered
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool ConCommandBase::IsRegistered( void ) const
{
	return m_bRegistered;
}

//-----------------------------------------------------------------------------
//
// Con Commands start here
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Global methods
//-----------------------------------------------------------------------------
static characterset_t s_BreakSet;
static bool s_bBuiltBreakSet = false;

//-----------------------------------------------------------------------------
// Tokenizer class
//-----------------------------------------------------------------------------
CCommand::CCommand()
{
	if ( !s_bBuiltBreakSet )
	{
		s_bBuiltBreakSet = true;
		CharacterSetBuild( &s_BreakSet, "{}()':" );
	}

	Reset();
}

CCommand::CCommand( int nArgC, const char **ppArgV )
{
	Assert( nArgC > 0 );

	if ( !s_bBuiltBreakSet )
	{
		s_bBuiltBreakSet = true;
		CharacterSetBuild( &s_BreakSet, "{}()':" );
	}

	Reset();

	char *pBuf = m_pArgvBuffer;
	char *pSBuf = m_pArgSBuffer;
	m_nArgc = nArgC;
	for ( int i = 0; i < nArgC; ++i )
	{
		m_ppArgv[i] = pBuf;
		int nLen = Q_strlen( ppArgV[i] );
		memcpy( pBuf, ppArgV[i], nLen+1 );
		if ( i == 0 )
		{
			m_nArgv0Size = nLen;
		}
		pBuf += nLen+1;

		bool bContainsSpace = strchr( ppArgV[i], ' ' ) != NULL;
		if ( bContainsSpace )
		{
			*pSBuf++ = '\"';
		}
		memcpy( pSBuf, ppArgV[i], nLen );
		pSBuf += nLen;
		if ( bContainsSpace )
		{
			*pSBuf++ = '\"';
		}

		if ( i != nArgC - 1 )
		{
			*pSBuf++ = ' ';
		}
	}
}

void CCommand::Reset()
{
	m_nArgc = 0;
	m_nArgv0Size = 0;
	m_pArgSBuffer[0] = 0;
}

characterset_t* CCommand::DefaultBreakSet()
{
	return &s_BreakSet;
}

bool CCommand::Tokenize( const char *pCommand, characterset_t *pBreakSet )
{
	Reset();
	if ( !pCommand )
		return false;

	// Use default break set
	if ( !pBreakSet )
	{
		pBreakSet = &s_BreakSet;
	}

	// Copy the current command into a temp buffer
	// NOTE: This is here to avoid the pointers returned by DequeueNextCommand
	// to become invalid by calling AddText. Is there a way we can avoid the memcpy?
	int nLen = Q_strlen( pCommand );
	if ( nLen >= COMMAND_MAX_LENGTH - 1 )
	{
		Warning( "CCommand::Tokenize: Encountered command which overflows the tokenizer buffer.. Skipping!\n" );
		return false;
	}

	memcpy( m_pArgSBuffer, pCommand, nLen + 1 );

	// Parse the current command into the current command buffer
	CUtlBuffer bufParse( m_pArgSBuffer, nLen, CUtlBuffer::TEXT_BUFFER | CUtlBuffer::READ_ONLY );
	int nArgvBufferSize = 0;
	while ( bufParse.IsValid() && ( m_nArgc < COMMAND_MAX_ARGC ) )
	{
		char *pArgvBuf = &m_pArgvBuffer[nArgvBufferSize];
		int nMaxLen = COMMAND_MAX_LENGTH - nArgvBufferSize;
		int nStartGet = bufParse.TellGet();
		int	nSize = bufParse.ParseToken( pBreakSet, pArgvBuf, nMaxLen );
		if ( nSize < 0 )
			break;

		// Check for overflow condition
		if ( nMaxLen == nSize )
		{
			Reset();
			return false;
		}

		if ( m_nArgc == 1 )
		{
			// Deal with the case where the arguments were quoted
			m_nArgv0Size = bufParse.TellGet();
			bool bFoundEndQuote = m_pArgSBuffer[m_nArgv0Size-1] == '\"';
			if ( bFoundEndQuote )
			{
				--m_nArgv0Size;
			}
			m_nArgv0Size -= nSize;
			Assert( m_nArgv0Size != 0 );

			// The StartGet check is to handle this case: "foo"bar
			// which will parse into 2 different args. ArgS should point to bar.
			bool bFoundStartQuote = ( m_nArgv0Size > nStartGet ) && ( m_pArgSBuffer[m_nArgv0Size-1] == '\"' );
			Assert( bFoundEndQuote == bFoundStartQuote );
			if ( bFoundStartQuote )
			{
				--m_nArgv0Size;
			}
		}

		m_ppArgv[ m_nArgc++ ] = pArgvBuf;
		if( m_nArgc >= COMMAND_MAX_ARGC )
		{
			Warning( "CCommand::Tokenize: Encountered command which overflows the argument buffer.. Clamped!\n" );
		}

		nArgvBufferSize += nSize + 1;
		Assert( nArgvBufferSize <= COMMAND_MAX_LENGTH );
	}

	return true;
}

//-----------------------------------------------------------------------------
// Helper function to parse arguments to commands.
//-----------------------------------------------------------------------------
const char* CCommand::FindArg( const char *pName ) const
{
	int nArgC = ArgC();
	for ( int i = 1; i < nArgC; i++ )
	{
		if ( !Q_stricmp( Arg(i), pName ) )
			return (i+1) < nArgC ? Arg( i+1 ) : "";
	}
	return 0;
}

int CCommand::FindArgInt( const char *pName, int nDefaultVal ) const
{
	const char *pVal = FindArg( pName );
	if ( pVal )
		return atoi( pVal );
	else
		return nDefaultVal;
}

//-----------------------------------------------------------------------------
// Default console command autocompletion function
//-----------------------------------------------------------------------------
int DefaultCompletionFunc( const char *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] )
{
	return 0;
}

//-----------------------------------------------------------------------------
// Purpose: Constructs a console command
//-----------------------------------------------------------------------------
//ConCommand::ConCommand()
//{
//	m_bIsNewConCommand = true;
//}

ConCommand::ConCommand( const char *pName, FnCommandCallbackV1_t callback, const char *pHelpString /*= 0*/, int flags /*= 0*/, FnCommandCompletionCallback completionFunc /*= 0*/ )
{
	// Set the callback
	m_fnCommandCallbackV1 = callback;
	m_bUsingNewCommandCallback = false;
	m_bUsingCommandCallbackInterface = false;
	m_fnCompletionCallback = completionFunc ? completionFunc : DefaultCompletionFunc;
	m_bHasCompletionCallback = completionFunc != 0 ? true : false;

	// Setup the rest
	BaseClass::Create( pName, pHelpString, flags );
}

ConCommand::ConCommand( const char *pName, FnCommandCallback_t callback, const char *pHelpString /*= 0*/, int flags /*= 0*/, FnCommandCompletionCallback completionFunc /*= 0*/ )
{
	// Set the callback
	m_fnCommandCallback = callback;
	m_bUsingNewCommandCallback = true;
	m_fnCompletionCallback = completionFunc ? completionFunc : DefaultCompletionFunc;
	m_bHasCompletionCallback = completionFunc != 0 ? true : false;
	m_bUsingCommandCallbackInterface = false;

	// Setup the rest
	BaseClass::Create( pName, pHelpString, flags );
}

ConCommand::ConCommand( const char *pName, ICommandCallback *pCallback, const char *pHelpString /*= 0*/, int flags /*= 0*/, ICommandCompletionCallback *pCompletionCallback /*= 0*/ )
{
	// Set the callback
	m_pCommandCallback = pCallback;
	m_bUsingNewCommandCallback = false;
	m_pCommandCompletionCallback = pCompletionCallback;
	m_bHasCompletionCallback = ( pCompletionCallback != 0 );
	m_bUsingCommandCallbackInterface = true;

	// Setup the rest
	BaseClass::Create( pName, pHelpString, flags );
}

//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
ConCommand::~ConCommand( void )
{
}

//-----------------------------------------------------------------------------
// Purpose: Returns true if this is a command
//-----------------------------------------------------------------------------
bool ConCommand::IsCommand( void ) const
{
	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Invoke the function if there is one
//-----------------------------------------------------------------------------
void ConCommand::Dispatch( const CCommand &command )
{
	if ( m_bUsingNewCommandCallback )
	{
		if ( m_fnCommandCallback )
		{
			( *m_fnCommandCallback )( command );
			return;
		}
	}
	else if ( m_bUsingCommandCallbackInterface )
	{
		if ( m_pCommandCallback )
		{
			m_pCommandCallback->CommandCallback( command );
			return;
		}
	}
	else
	{
		if ( m_fnCommandCallbackV1 )
		{
			( *m_fnCommandCallbackV1 )();
			return;
		}
	}

	// Command without callback!!!
	AssertMsg( 0, ( "Encountered ConCommand '%s' without a callback!\n", GetName() ) );
}

//-----------------------------------------------------------------------------
// Purpose: Calls the autocompletion method to get autocompletion suggestions
//-----------------------------------------------------------------------------
int	ConCommand::AutoCompleteSuggest( const char *partial, CUtlVector< CUtlString > &commands )
{
	if ( m_bUsingCommandCallbackInterface )
	{
		if ( !m_pCommandCompletionCallback )
			return 0;
		return m_pCommandCompletionCallback->CommandCompletionCallback( partial, commands );
	}

	Assert( m_fnCompletionCallback );
	if ( !m_fnCompletionCallback )
		return 0;

	char rgpchCommands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ];
	int iret = ( m_fnCompletionCallback )( partial, rgpchCommands );
	for ( int i = 0 ; i < iret; ++i )
	{
		CUtlString str = rgpchCommands[ i ];
		commands.AddToTail( str );
	}
	return iret;
}

//-----------------------------------------------------------------------------
// Returns true if the console command can autocomplete
//-----------------------------------------------------------------------------
bool ConCommand::CanAutoComplete( void )
{
	return m_bHasCompletionCallback;
}

//-----------------------------------------------------------------------------
//
// Console Variables
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Various constructors
//-----------------------------------------------------------------------------
ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags /* = 0 */ )
{
	Create( pName, pDefaultValue, flags );
}

ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString )
{
	Create( pName, pDefaultValue, flags, pHelpString );
}

ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax )
{
	Create( pName, pDefaultValue, flags, pHelpString, bMin, fMin, bMax, fMax );
}

ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, FnChangeCallback_t callback )
{
	Create( pName, pDefaultValue, flags, pHelpString, false, 0.0, false, 0.0, callback );
}

ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax, FnChangeCallback_t callback )
{
	Create( pName, pDefaultValue, flags, pHelpString, bMin, fMin, bMax, fMax, callback );
}

//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
ConVar::~ConVar( void )
{
	if ( m_pszString )
	{
		delete[] m_pszString;
		m_pszString = NULL;
	}
}

//-----------------------------------------------------------------------------
// Install a change callback (there shouldn't already be one....)
//-----------------------------------------------------------------------------
void ConVar::InstallChangeCallback( FnChangeCallback_t callback )
{
	Assert( !m_pParent->m_fnChangeCallback || !callback );
	m_pParent->m_fnChangeCallback = callback;

	if ( m_pParent->m_fnChangeCallback )
	{
		// Call it immediately to set the initial value...
		m_pParent->m_fnChangeCallback( this, m_pszString, m_fValue );
	}
}

bool ConVar::IsFlagSet( int flag ) const
{
	return ( flag & m_pParent->m_nFlags ) ? true : false;
}

const char *ConVar::GetHelpText( void ) const
{
	return m_pParent->m_pszHelpString;
}

void ConVar::AddFlags( int flags )
{
	m_pParent->m_nFlags |= flags;

#ifdef ALLOW_DEVELOPMENT_CVARS
	m_pParent->m_nFlags &= ~FCVAR_DEVELOPMENTONLY;
#endif
}

bool ConVar::IsRegistered( void ) const
{
	return m_pParent->m_bRegistered;
}

const char *ConVar::GetName( void ) const
{
	return m_pParent->m_pszName;
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool ConVar::IsCommand( void ) const
{
	return false;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  :
//-----------------------------------------------------------------------------
void ConVar::Init()
{
	BaseClass::Init();
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *value -
//-----------------------------------------------------------------------------
void ConVar::InternalSetValue( const char *value )
{
	if ( IsFlagSet( FCVAR_MATERIAL_THREAD_MASK ) )
	{
		if ( g_pCVar && !g_pCVar->IsMaterialThreadSetAllowed() )
		{
			g_pCVar->QueueMaterialThreadSetValue( this, value );
			return;
		}
	}

	float fNewValue;
	char  tempVal[ 32 ];
	char  *val;

	Assert(m_pParent == this); // Only valid for root convars.

	float flOldValue = m_fValue;

	val = (char *)value;
	if ( !value )
		fNewValue = 0.0f;
	else
		fNewValue = ( float )atof( value );

	if ( ClampValue( fNewValue ) )
	{
		Q_snprintf( tempVal,sizeof(tempVal), "%f", fNewValue );
		val = tempVal;
	}

	// Redetermine value
	m_fValue		= fNewValue;
	m_nValue		= ( int )( m_fValue );

	if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) )
	{
		ChangeStringValue( val, flOldValue );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *tempVal -
//-----------------------------------------------------------------------------
void ConVar::ChangeStringValue( const char *tempVal, float flOldValue )
{
	Assert( !( m_nFlags & FCVAR_NEVER_AS_STRING ) );

 	char* pszOldValue = (char*)stackalloc( m_StringLength );
	memcpy( pszOldValue, m_pszString, m_StringLength );

	if ( tempVal )
	{
		int len = Q_strlen(tempVal) + 1;

		if ( len > m_StringLength)
		{
			if (m_pszString)
			{
				delete[] m_pszString;
			}

			m_pszString	= new char[len];
			m_StringLength = len;
		}

		memcpy( m_pszString, tempVal, len );
	}
	else
	{
		*m_pszString = 0;
	}

	// Invoke any necessary callback function
	if ( m_fnChangeCallback )
	{
		m_fnChangeCallback( this, pszOldValue, flOldValue );
	}

	g_pCVar->CallGlobalChangeCallbacks( this, pszOldValue, flOldValue );

	stackfree( pszOldValue );
}

//-----------------------------------------------------------------------------
// Purpose: Check whether to clamp and then perform clamp
// Input  : value -
// Output : Returns true if value changed
//-----------------------------------------------------------------------------
bool ConVar::ClampValue( float& value )
{
	if ( m_bHasMin && ( value < m_fMinVal ) )
	{
		value = m_fMinVal;
		return true;
	}

	if ( m_bHasMax && ( value > m_fMaxVal ) )
	{
		value = m_fMaxVal;
		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *value -
//-----------------------------------------------------------------------------
void ConVar::InternalSetFloatValue( float fNewValue )
{
	if ( fNewValue == m_fValue )
		return;

	if ( IsFlagSet( FCVAR_MATERIAL_THREAD_MASK ) )
	{
		if ( g_pCVar && !g_pCVar->IsMaterialThreadSetAllowed() )
		{
			g_pCVar->QueueMaterialThreadSetValue( this, fNewValue );
			return;
		}
	}

	Assert( m_pParent == this ); // Only valid for root convars.

	// Check bounds
	ClampValue( fNewValue );

	// Redetermine value
	float flOldValue = m_fValue;
	m_fValue		= fNewValue;
	m_nValue		= ( int )m_fValue;

	if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) )
	{
		char tempVal[ 32 ];
		Q_snprintf( tempVal, sizeof( tempVal), "%f", m_fValue );
		ChangeStringValue( tempVal, flOldValue );
	}
	else
	{
		Assert( !m_fnChangeCallback );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *value -
//-----------------------------------------------------------------------------
void ConVar::InternalSetIntValue( int nValue )
{
	if ( nValue == m_nValue )
		return;

	if ( IsFlagSet( FCVAR_MATERIAL_THREAD_MASK ) )
	{
		if ( g_pCVar && !g_pCVar->IsMaterialThreadSetAllowed() )
		{
			g_pCVar->QueueMaterialThreadSetValue( this, nValue );
			return;
		}
	}

	Assert( m_pParent == this ); // Only valid for root convars.

	float fValue = (float)nValue;
	if ( ClampValue( fValue ) )
	{
		nValue = ( int )( fValue );
	}

	// Redetermine value
	float flOldValue = m_fValue;
	m_fValue		= fValue;
	m_nValue		= nValue;

	if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) )
	{
		char tempVal[ 32 ];
		Q_snprintf( tempVal, sizeof( tempVal ), "%d", m_nValue );
		ChangeStringValue( tempVal, flOldValue );
	}
	else
	{
		Assert( !m_fnChangeCallback );
	}
}

//-----------------------------------------------------------------------------
// Purpose: Private creation
//-----------------------------------------------------------------------------
void ConVar::Create( const char *pName, const char *pDefaultValue, int flags /*= 0*/,
	const char *pHelpString /*= NULL*/, bool bMin /*= false*/, float fMin /*= 0.0*/,
	bool bMax /*= false*/, float fMax /*= false*/, FnChangeCallback_t callback /*= NULL*/ )
{
	m_pParent = this;

	// Name should be static data
	SetDefault( pDefaultValue );

	m_StringLength = strlen( m_pszDefaultValue ) + 1;
	m_pszString = new char[m_StringLength];
	memcpy( m_pszString, m_pszDefaultValue, m_StringLength );

	m_bHasMin = bMin;
	m_fMinVal = fMin;
	m_bHasMax = bMax;
	m_fMaxVal = fMax;

	m_fnChangeCallback = callback;

	m_fValue = ( float )atof( m_pszString );

	// Bounds Check, should never happen, if it does, no big deal
	if ( m_bHasMin && ( m_fValue < m_fMinVal ) )
	{
		Assert( 0 );
	}

	if ( m_bHasMax && ( m_fValue > m_fMaxVal ) )
	{
		Assert( 0 );
	}

	m_nValue = ( int )m_fValue;

	BaseClass::Create( pName, pHelpString, flags );
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *value -
//-----------------------------------------------------------------------------
void ConVar::SetValue(const char *value)
{
	ConVar *var = ( ConVar * )m_pParent;
	var->InternalSetValue( value );
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : value -
//-----------------------------------------------------------------------------
void ConVar::SetValue( float value )
{
	ConVar *var = ( ConVar * )m_pParent;
	var->InternalSetFloatValue( value );
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : value -
//-----------------------------------------------------------------------------
void ConVar::SetValue( int value )
{
	ConVar *var = ( ConVar * )m_pParent;
	var->InternalSetIntValue( value );
}

//-----------------------------------------------------------------------------
// Purpose: Reset to default value
//-----------------------------------------------------------------------------
void ConVar::Revert( void )
{
	// Force default value again
	ConVar *var = ( ConVar * )m_pParent;
	var->SetValue( var->m_pszDefaultValue );
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : minVal -
// Output : true if there is a min set
//-----------------------------------------------------------------------------
bool ConVar::GetMin( float& minVal ) const
{
	minVal = m_pParent->m_fMinVal;
	return m_pParent->m_bHasMin;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : maxVal -
//-----------------------------------------------------------------------------
bool ConVar::GetMax( float& maxVal ) const
{
	maxVal = m_pParent->m_fMaxVal;
	return m_pParent->m_bHasMax;
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : const char
//-----------------------------------------------------------------------------
const char *ConVar::GetDefault( void ) const
{
	return m_pParent->m_pszDefaultValue;
}

void ConVar::SetDefault( const char *pszDefault )
{
	static char *empty_string = "";
	m_pszDefaultValue = pszDefault ? pszDefault : empty_string;
	Assert( m_pszDefaultValue );
}

//-----------------------------------------------------------------------------
// This version is simply used to make reading convars simpler.
// Writing convars isn't allowed in this mode
//-----------------------------------------------------------------------------
class CEmptyConVar : public ConVar
{
public:
	CEmptyConVar() : ConVar( "", "0" ) {}
	// Used for optimal read access
	virtual void SetValue( const char *pValue ) {}
	virtual void SetValue( float flValue ) {}
	virtual void SetValue( int nValue ) {}
	virtual const char *GetName( void ) const { return ""; }
	virtual bool IsFlagSet( int nFlags ) const { return false; }
};

static CEmptyConVar s_EmptyConVar;

ConVarRef::ConVarRef( const char *pName )
{
	Init( pName, false );
}

ConVarRef::ConVarRef( const char *pName, bool bIgnoreMissing )
{
	Init( pName, bIgnoreMissing );
}

void ConVarRef::Init( const char *pName, bool bIgnoreMissing )
{
	m_pConVar = g_pCVar ? g_pCVar->FindVar( pName ) : &s_EmptyConVar;
	if ( !m_pConVar )
	{
		m_pConVar = &s_EmptyConVar;
	}
	m_pConVarState = static_cast< ConVar * >( m_pConVar );
	if( !IsValid() )
	{
		static bool bFirst = true;
		if ( g_pCVar || bFirst )
		{
			if ( !bIgnoreMissing )
			{
				Warning( "ConVarRef %s doesn't point to an existing ConVar\n", pName );
			}
			bFirst = false;
		}
	}
}

ConVarRef::ConVarRef( IConVar *pConVar )
{
	m_pConVar = pConVar ? pConVar : &s_EmptyConVar;
	m_pConVarState = static_cast< ConVar * >( m_pConVar );
}

bool ConVarRef::IsValid() const
{
	return m_pConVar != &s_EmptyConVar;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ConVar_PrintFlags( const ConCommandBase *var )
{
	bool any = false;
	if ( var->IsFlagSet( FCVAR_GAMEDLL ) )
	{
		ConMsg( " game" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_CLIENTDLL ) )
	{
		ConMsg( " client" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_ARCHIVE ) )
	{
		ConMsg( " archive" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_NOTIFY ) )
	{
		ConMsg( " notify" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_SPONLY ) )
	{
		ConMsg( " singleplayer" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_NOT_CONNECTED ) )
	{
		ConMsg( " notconnected" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_CHEAT ) )
	{
		ConMsg( " cheat" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_REPLICATED ) )
	{
		ConMsg( " replicated" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_SERVER_CAN_EXECUTE ) )
	{
		ConMsg( " server_can_execute" );
		any = true;
	}

	if ( var->IsFlagSet( FCVAR_CLIENTCMD_CAN_EXECUTE ) )
	{
		ConMsg( " clientcmd_can_execute" );
		any = true;
	}

	if ( any )
	{
		ConMsg( "\n" );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ConVar_PrintDescription( const ConCommandBase *pVar )
{
	bool bMin, bMax;
	float fMin, fMax;
	const char *pStr;

	assert( pVar );

	Color clr;
	clr.SetColor( 255, 100, 100, 255 );

	if ( !pVar->IsCommand() )
	{
		ConVar *var = ( ConVar * )pVar;
		const ConVar_ServerBounded *pBounded = dynamic_cast<const ConVar_ServerBounded*>( var );

		bMin = var->GetMin( fMin );
		bMax = var->GetMax( fMax );

		const char *value = NULL;
		char tempVal[ 32 ];

		if ( pBounded || var->IsFlagSet( FCVAR_NEVER_AS_STRING ) )
		{
			value = tempVal;

			int intVal = pBounded ? pBounded->GetInt() : var->GetInt();
			float floatVal = pBounded ? pBounded->GetFloat() : var->GetFloat();

			if ( fabs( (float)intVal - floatVal ) < 0.000001 )
			{
				Q_snprintf( tempVal, sizeof( tempVal ), "%d", intVal );
			}
			else
			{
				Q_snprintf( tempVal, sizeof( tempVal ), "%f", floatVal );
			}
		}
		else
		{
			value = var->GetString();
		}

		if ( value )
		{
			ConColorMsg( clr, "\"%s\" = \"%s\"", var->GetName(), value );

			if ( stricmp( value, var->GetDefault() ) )
			{
				ConMsg( " ( def. \"%s\" )", var->GetDefault() );
			}
		}

		if ( bMin )
		{
			ConMsg( " min. %f", fMin );
		}
		if ( bMax )
		{
			ConMsg( " max. %f", fMax );
		}

		ConMsg( "\n" );

		// Handled virtualized cvars.
		if ( pBounded && fabs( pBounded->GetFloat() - var->GetFloat() ) > 0.0001f )
		{
			ConColorMsg( clr, "** NOTE: The real value is %.3f but the server has temporarily restricted it to %.3f **\n",
				var->GetFloat(), pBounded->GetFloat() );
		}
	}
	else
	{
		ConCommand *var = ( ConCommand * )pVar;

		ConColorMsg( clr, "\"%s\"\n", var->GetName() );
	}

	ConVar_PrintFlags( pVar );

	pStr = pVar->GetHelpText();
	if ( pStr && pStr[0] )
	{
		ConMsg( " - %s\n", pStr );
	}
}

redpajama_set_name: RedPajamaGithub


text:
import com.twilio.sdk.TwilioIPMessagingClient;
import com.twilio.sdk.resource.instance.ipmessaging.Service;
import com.twilio.sdk.resource.instance.ipmessaging.Channel;
import com.twilio.sdk.resource.list.ipmessaging.MemberList;
import com.twilio.sdk.TwilioRestException;

public class TwilioTest {
    // Find your Account Sid and Token at twilio.com/user/account
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";
    public static final String SERVICE_SID = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String CHANNEL_SID = "CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    public static void main(String args[]) throws TwilioRestException {
        // Initialize the client
        TwilioIPMessagingClient client = new TwilioIPMessagingClient(ACCOUNT_SID, AUTH_TOKEN);

        // Retrieve a channel
        Service service = client.getService(SERVICE_SID);
        Channel Channel = service.getChannel(CHANNEL_SID);

        // Retrieve the list of members on that channel
        MemberList list = Channel.getMembers();
        System.out.println(list);
    }
}


text:
class UrlBuilder
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers

  def request
    OpenStruct.new(host: 'test.host', scheme: 'http', port: 80, ssl?: false)
  end

  def add_hostname(args)
    opts        = args.extract_options! || {}
    opts[:host] = 'test.host'
    [*args, opts]
  end

  self.default_url_options = {
    host: 'test.host',
    protocol: 'http',
    only_path: false
  }
end


text:
<?php

namespace SocialiteProviders\Zoho;

use GuzzleHttp\RequestOptions;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

class Provider extends AbstractProvider
{
    public const IDENTIFIER = 'ZOHO';

    /**
     * {@inheritdoc}
     */
    protected $scopes = ['aaaserver.profile.READ'];

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase('https://accounts.zoho.com/oauth/v2/auth', $state);
    }

    /**
     * Gets the Accounts Server to use from Zoho provider.
     */
    protected function getAccountsServerUrl()
    {
        return $this->request->input('accounts-server', 'https://accounts.zoho.com');
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return $this->getAccountsServerUrl().'/oauth/v2/token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get($this->getAccountsServerUrl().'/oauth/user/info', [
            RequestOptions::HEADERS => [
                'Authorization' => 'Bearer '.$token,
            ],
        ]);

        return json_decode((string) $response->getBody(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user)->map([
            'id'       => $user['ZUID'],
            'email'    => $user['Email'],
            'nickname' => $user['Display_Name'],
            'name'     => $user['First_Name'].' '.$user['Last_Name'],
            'avatar'   => !empty($user['images']) ? $user['images'][0]['url'] : null,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenFields($code)
    {
        return array_merge(parent::getTokenFields($code), [
            'grant_type' => 'authorization_code',
        ]);
    }
}


text:
.location.info-win-dialog{
    font-size: .8em;
    overflow: hidden;
}

.location.info-win-dialog .infoDiv{
    float: left;
}

.location.info-win-dialog .hide-location{
    width: auto;
    height: auto;
    vertical-align: top;
    text-align: center;
}

.location .hide-location select{
    clear:left;
    height: 30px;
    width: 105px;
    font-size: 12px;
    margin-top: 5px;
    color: #000000;
}

.location .hide-location .btn{
    margin-top: 3px;
}

.location.info-win-dialog .title{
    font-weight: bold;
    font-size: 14px;
    text-align: center;
    margin-left: 30px;
}

.location.info-win-dialog .content{
    position: relative;
    margin-left: 15px;
    width: 480px;
    height: 135px;
}

.location.info-win-dialog .tableDiv{
    float: right;
    vertical-align: top;
    margin-left: 12px;
    height: 133px;
    width: 375px;
    overflow-y: scroll;
    overflow-x: hidden;
    border: 1px solid lightgray;
}

.location.info-win-dialog table.table{
    margin-bottom: 0px;
}

.location.info-win-dialog table.table td{
    padding: 5px;
}


text:
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                     University of Edinburgh, UK                       */
/*                         Copyright (c) 1996                            */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*                       Author :  Alan W Black                          */
/*                       Date   :  May 1996                              */
/*=======================================================================*/
/*                 Shared (private) audio declarations                   */
/*                                                                       */
/*=======================================================================*/
#ifndef __AUDIOP_H__
#define __AUDIOP_H__

int play_nas_wave(EST_Wave &inwave, EST_Option &al);
int play_esd_wave(EST_Wave &inwave, EST_Option &al);
int play_sun16_wave(EST_Wave &inwave, EST_Option &al);
int play_linux_wave(EST_Wave &inwave, EST_Option &al);
int play_mplayer_wave(EST_Wave &inwave, EST_Option &al);
int play_win32audio_wave(EST_Wave &inwave, EST_Option &al);
int play_irix_wave(EST_Wave &inwave, EST_Option &al);
int play_macosx_wave(EST_Wave &inwave, EST_Option &al);

int record_nas_wave(EST_Wave &inwave, EST_Option &al);
int record_esd_wave(EST_Wave &inwave, EST_Option &al);
int record_sun16_wave(EST_Wave &inwave, EST_Option &al);
int record_linux_wave(EST_Wave &inwave, EST_Option &al);

#endif /* __AUDIOP_H__ */


text:
2016-08-29

Sharepoint 2007 : Le contenu de certaine page n'est pas cohérent

			Une fonctionnalité intéressante de Sharepoint 2007 est la gestion de la mise en cache de certains contenus HTML.

			Une fonctionnalité intéressante de Sharepoint 2007 est la gestion de la mise en cache de certains contenus HTML.

            Pour cela, il faut se rendre sur la page d'administration de votre site (_layouts/settings.aspx). Puis dans la partie 'Cache de sortie "collection de site"' et 'Cache de sortie'.
            Ce système de cache est utile pour du contenu statique.
            Comme il n'est paramétrable que par rapport à un site, il faut séparer via sous sites le contenu dynamique du statique.

            Donc attention, si vous activez cette fonctionnalité sur du contenu dynamique vous risquez de faire afficher du contenu non désiré.
            Comme l'objectif de cette option et d'éviter de générer à chaque fois la page HTML demandée ; cette dernière est mise en cache
            pour être immédiatement transférée aux utilisateurs qui la demande. Seulement, si nous sommes avec du contenu dynamique,
            il est possible que ça soit une version du contenu dynamique non à jour (voir l'affichage de données sensibles) qui soit mis en cache
            et transmis par la suite.

Sharepoint 2007 : Incorrect HTML content

			The 'site output cache' an interesting Sharepoint feature. It's used for put in cache the HTML content.

			The 'site output cache' an interesting Sharepoint feature. It's used for put in cache the HTML content.

            Go to the Sharepoint administration (_layouts/settings.aspx) and check 'Site output cache' and 'Site collection output cache'.
            This feature depends from site scope, you need to separate the dynamic content from static with sub sites.

            Be careful, if you activate this feature for dynamic content you can have some problems.
            This option is to limit server treatments, thus Sharepoint save in the cache the generated HTML.
            With dynamic content, you can see an outdated post or a form with incorrect values.


text:
require 'beanstalk_integration_tests/test_helper'

class StatsJobTest < BeanstalkIntegrationTest

  context 'stats-job' do

    setup do
      client.transmit("use #{tube_name}")
    end

    should 'return stats for the specified job with all expected keys' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
      response = client.transmit("stats-job #{job_id}")
      assert_equal 'OK', response[:status]
      job_stats = response[:body]
      expected_keys = %w[
        id tube state pri age delay ttr time-left file reserves timeouts
        releases buries kicks
      ]
      assert_equal expected_keys, job_stats.keys
      assert_nil job_stats.values.compact!, 'Expected job stats to have no nil values'
      assert_equal(initial_cmd_stats_job + 1, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be incremented')
    end

    # Some stats are tested elsewhere:
    #
    # :id => See below
    # :tube => PutTest
    # :state => PutTest, BuryTest, ReleaseTest
    # :pri => PutTest, BuryTest, ReleaseTest
    # :age => See below
    # :time-left => PutTest, TouchTest
    # :file => NOT TESTED (except for presence)
    # :reserves => ReserveTest
    # :timeouts => TouchTest
    # :releases => ReleaseTest
    # :buries => BuryTest
    # :kicks => KickTest, KickJobTest
    #
    # For those that aren't...

    should 'return correct id' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      assert_equal(job_id.to_i, client.transmit("stats-job #{job_id}")[:body]['id'], 'Expected job-stats[id] to return correct job id')
    end

    should 'return correct age' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      initial_job_age = client.transmit("stats-job #{job_id}")[:body]['age']
      sleep 1
      assert_equal(initial_job_age + 1, client.transmit("stats-job #{job_id}")[:body]['age'], 'Expected job-stats[age] to return incremented job age')
    end

    should 'return NOT_FOUND if the job has never existed' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
      assert_raises(Beaneater::NotFoundError, 'Expected job-stats for non-existent job to return NOT_FOUND') do
        client.transmit("stats-job #{job_id.to_i + 1}")
      end
      assert_equal(initial_cmd_stats_job + 1, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be incremented')
    end

    should 'return NOT_FOUND if the job is deleted' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      client.transmit("delete #{job_id}")
      initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
      assert_raises(Beaneater::NotFoundError, 'Expected job-stats for deleted job to return NOT_FOUND') do
        client.transmit("stats-job #{job_id}")
      end
      assert_equal(initial_cmd_stats_job + 1, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be incremented')
    end

    should 'return BAD_FORMAT without trailing space' do
      initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
      assert_raises(Beaneater::BadFormatError, 'Expected job-stats without space to return BAD_FORMAT') do
        client.transmit('stats-job')
      end
      assert_equal(initial_cmd_stats_job, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be unchanged')
    end

    should 'return NOT_FOUND if job id is null, negative, or non-integer' do
      ['', -5, 'foo'].each do |job_id|
        initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
        assert_raises(Beaneater::NotFoundError, 'Expected job-stats for invalid job id to return NOT_FOUND') do
          client.transmit("stats-job #{job_id}")
        end
        assert_equal(initial_cmd_stats_job + 1, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be incremented')
      end
    end

    should 'ignore trailing space, arguments, and chars' do
      message = uuid
      job_id = client.transmit("put 0 0 120 #{message.bytesize}\r\n#{message}")[:id]
      [' ', ' and ignore these arguments', '_and_ignore_these_letters'].each do |trailer|
        initial_cmd_stats_job = client.transmit('stats')[:body]['cmd-stats-job']
        client.transmit("stats-job #{job_id}#{trailer}")
        assert_equal(initial_cmd_stats_job + 1, client.transmit('stats')[:body]['cmd-stats-job'], 'Expected cmd-stats-job to be incremented')
      end
    end

  end

end


text:
<?php
namespace Flowpack\ElasticSearch\Tests\Functional\Fixtures;

use Flowpack\ElasticSearch\Domain\Model\AbstractType;
use Neos\Flow\Annotations as Flow;

/**
 * A twitter sample type
 */
class TwitterType extends AbstractType
{
}


text:
/**
 * Global constants.
 *
 * @ignore
 */

var CONST = {

    /**
     * Phaser Release Version
     *
     * @name Phaser.VERSION
     * @const
     * @type {string}
     * @since 3.0.0
     */
    VERSION: '3.60.0-beta.15',

    BlendModes: require('./renderer/BlendModes'),

    ScaleModes: require('./renderer/ScaleModes'),

    /**
     * This setting will auto-detect if the browser is capable of suppporting WebGL.
     * If it is, it will use the WebGL Renderer. If not, it will fall back to the Canvas Renderer.
     *
     * @name Phaser.AUTO
     * @const
     * @type {number}
     * @since 3.0.0
     */
    AUTO: 0,

    /**
     * Forces Phaser to only use the Canvas Renderer, regardless if the browser supports
     * WebGL or not.
     *
     * @name Phaser.CANVAS
     * @const
     * @type {number}
     * @since 3.0.0
     */
    CANVAS: 1,

    /**
     * Forces Phaser to use the WebGL Renderer. If the browser does not support it, there is
     * no fallback to Canvas with this setting, so you should trap it and display a suitable
     * message to the user.
     *
     * @name Phaser.WEBGL
     * @const
     * @type {number}
     * @since 3.0.0
     */
    WEBGL: 2,

    /**
     * A Headless Renderer doesn't create either a Canvas or WebGL Renderer. However, it still
     * absolutely relies on the DOM being present and available. This mode is meant for unit testing,
     * not for running Phaser on the server, which is something you really shouldn't do.
     *
     * @name Phaser.HEADLESS
     * @const
     * @type {number}
     * @since 3.0.0
     */
    HEADLESS: 3,

    /**
     * In Phaser the value -1 means 'forever' in lots of cases, this const allows you to use it instead
     * to help you remember what the value is doing in your code.
     *
     * @name Phaser.FOREVER
     * @const
     * @type {number}
     * @since 3.0.0
     */
    FOREVER: -1,

    /**
     * Direction constant.
     *
     * @name Phaser.NONE
     * @const
     * @type {number}
     * @since 3.0.0
     */
    NONE: 4,

    /**
     * Direction constant.
     *
     * @name Phaser.UP
     * @const
     * @type {number}
     * @since 3.0.0
     */
    UP: 5,

    /**
     * Direction constant.
     *
     * @name Phaser.DOWN
     * @const
     * @type {number}
     * @since 3.0.0
     */
    DOWN: 6,

    /**
     * Direction constant.
     *
     * @name Phaser.LEFT
     * @const
     * @type {number}
     * @since 3.0.0
     */
    LEFT: 7,

    /**
     * Direction constant.
     *
     * @name Phaser.RIGHT
     * @const
     * @type {number}
     * @since 3.0.0
     */
    RIGHT: 8

};

module.exports = CONST;


text:
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import 'rxjs/add/operator/switchMap';

import { WeatherService } from "../weather.service";
import { WeatherDataModel } from "../weatherDataModel";

@Component({
    /* If this component is part of routing, then 'selector' is not necessary */
    'moduleId': module.id,
    'templateUrl': 'weather-details.component.html'
})
export class WeatherDetailsComponent implements OnInit {

    constructor(private weatherService: WeatherService,
                private route: ActivatedRoute) {}

    weatherData: WeatherDataModel;
    city: string;

    ngOnInit(): void {
        this.route.params.subscribe((params: Params) => this.city = params['city'])

        this.route.params
        .switchMap((params: Params) => this.weatherService.getWeatherInfo(params['city']))
        .subscribe(weatherData => this.weatherData = weatherData);
    }
}


text:
WK.BackForwardEntry = function(dashboardView, cookie)
{
    WK.Object.call(this);

    console.assert(dashboardView instanceof WK.DashboardView, dashboardView);

    this._dashboardView = dashboardView;

    // Cookies are compared with Object.shallowEqual, so should not store objects or arrays.
    this._cookie = cookie || {};

    dashboardView.saveToCookie(this._cookie);
}

WK.BackForwardEntry.prototype = {
    __proto__: WK.Object.prototype,
    constructor: WK.BackForwardEntry,

    // Public

    get dashboardView()
    {
        return this._dashboardView;
    },

    get cookie()
    {
        // Cookies are immutable; they represent a specific navigation action.
        return Object.shallowCopy(this._cookie);
    },

    prepareToShow: function(shouldCallShown)
    {
        this._restoreFromCookie();

        this.dashboardView.visible = true;
        if (shouldCallShown)
            this.dashboardView.shown();
        this.dashboardView.updateLayout();
    },

    prepareToHide: function()
    {
        this.dashboardView.visible = false;
        this.dashboardView.hidden();
    },

    // Private

    _restoreFromCookie: function()
    {
        this.dashboardView.restoreFromCookie(this.cookie);
    },

};


text:
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/about', {
      controller: 'aboutController',
      templateUrl: 'views/about.html'
    })
    .when('/projects', {
      controller: 'projectController',
      templateUrl: 'views/projects.html'
    })
    .when('/sap', {
      controller: 'sapController',
      templateUrl: 'views/sap.html'
    })
    .when('/events', {
      controller: 'eventsController',
      templateUrl: 'views/events.html'
    })
    .when('/assoc', {
      controller: 'assocController',
      templateUrl: 'views/assoc.html'
    })
    .when('/recog', {
      controller: 'recogController',
      templateUrl: 'views/recog.html'
    })
    .when('/team', {
      controller: 'teamController',
      templateUrl: 'views/team.html'
    })
    .when('/contact', {
      controller: 'contactController',
      templateUrl: 'views/contact.html'
    })
    .when('/', {
      controller: 'homeController',
      templateUrl: 'views/home.html'
    })
    .otherwise({
      redirectTo: '/'
    });
}]);


text:
CREATE TEMPORARY VIEW tab1 AS SELECT * FROM VALUES
    (1, 2),
    (1, 2),
    (1, 3),
    (1, 3),
    (2, 3),
    (null, null),
    (null, null)
    AS tab1(k, v);
CREATE TEMPORARY VIEW tab2 AS SELECT * FROM VALUES
    (1, 2),
    (1, 2),
    (2, 3),
    (3, 4),
    (null, null),
    (null, null)
    AS tab2(k, v);

-- Basic INTERSECT ALL
SELECT udf(k), v FROM tab1
INTERSECT ALL
SELECT k, udf(v) FROM tab2;

-- INTERSECT ALL same table in both branches
SELECT k, udf(v) FROM tab1
INTERSECT ALL
SELECT udf(k), v FROM tab1 WHERE udf(k) = 1;

-- Empty left relation
SELECT udf(k), udf(v) FROM tab1 WHERE k > udf(2)
INTERSECT ALL
SELECT udf(k), udf(v) FROM tab2;

-- Empty right relation
SELECT udf(k), v FROM tab1
INTERSECT ALL
SELECT udf(k), v FROM tab2 WHERE udf(udf(k)) > 3;

-- Type Coerced INTERSECT ALL
SELECT udf(k), v FROM tab1
INTERSECT ALL
SELECT CAST(udf(1) AS BIGINT), CAST(udf(2) AS BIGINT);

-- Error as types of two side are not compatible
SELECT k, udf(v) FROM tab1
INTERSECT ALL
SELECT array(1), udf(2);

-- Mismatch on number of columns across both branches
SELECT udf(k) FROM tab1
INTERSECT ALL
SELECT udf(k), udf(v) FROM tab2;

-- Basic
SELECT udf(k), v FROM tab2
INTERSECT ALL
SELECT k, udf(v) FROM tab1
INTERSECT ALL
SELECT udf(k), udf(v) FROM tab2;

-- Chain of different `set operations
SELECT udf(k), v FROM tab1
EXCEPT
SELECT k, udf(v) FROM tab2
UNION ALL
SELECT k, udf(udf(v)) FROM tab1
INTERSECT ALL
SELECT udf(k), v FROM tab2
;

-- Chain of different `set operations
SELECT udf(k), udf(v) FROM tab1
EXCEPT
SELECT udf(k), v FROM tab2
EXCEPT
SELECT k, udf(v) FROM tab1
INTERSECT ALL
SELECT udf(k), udf(udf(v)) FROM tab2
;

-- test use parenthesis to control order of evaluation
(
  (
    (
      SELECT udf(k), v FROM tab1
      EXCEPT
      SELECT k, udf(v) FROM tab2
    )
    EXCEPT
    SELECT udf(k), udf(v) FROM tab1
  )
  INTERSECT ALL
  SELECT udf(k), udf(v) FROM tab2
)
;

-- Join under intersect all
SELECT *
FROM   (SELECT udf(tab1.k),
               udf(tab2.v)
        FROM   tab1
               JOIN tab2
                 ON udf(udf(tab1.k)) = tab2.k)
INTERSECT ALL
SELECT *
FROM   (SELECT udf(tab1.k),
               udf(tab2.v)
        FROM   tab1
               JOIN tab2
                 ON udf(tab1.k) = udf(udf(tab2.k)));

-- Join under intersect all (2)
SELECT *
FROM   (SELECT udf(tab1.k),
               udf(tab2.v)
        FROM   tab1
               JOIN tab2
                 ON udf(tab1.k) = udf(tab2.k))
INTERSECT ALL
SELECT *
FROM   (SELECT udf(tab2.v) AS k,
               udf(tab1.k) AS v
        FROM   tab1
               JOIN tab2
                 ON tab1.k = udf(tab2.k));

-- Group by under intersect all
SELECT udf(v) FROM tab1 GROUP BY v
INTERSECT ALL
SELECT udf(udf(k)) FROM tab2 GROUP BY k;

-- Test pre spark2.4 behaviour of set operation precedence
-- All the set operators are given equal precedence and are evaluated
-- from left to right as they appear in the query.

-- Set the property
SET spark.sql.legacy.setopsPrecedence.enabled= true;

SELECT udf(k), v FROM tab1
EXCEPT
SELECT k, udf(v) FROM tab2
UNION ALL
SELECT udf(k), udf(v) FROM tab1
INTERSECT ALL
SELECT udf(udf(k)), udf(v) FROM tab2;

SELECT k, udf(v) FROM tab1
EXCEPT
SELECT udf(k), v FROM tab2
UNION ALL
SELECT udf(k), udf(v) FROM tab1
INTERSECT
SELECT udf(k), udf(udf(v)) FROM tab2;

-- Restore the property
SET spark.sql.legacy.setopsPrecedence.enabled = false;

-- Clean-up
DROP VIEW IF EXISTS tab1;
DROP VIEW IF EXISTS tab2;


text:
<?php
/**
 * Wow Secure Cookie Manager
 *
 * PHP version 5
 *
 * @category Wow
 * @package  WowSecureCookie
 * @author   Matthieu Huguet <matthieu@huguet.eu>
 * @author   Yi-Feng Tzeng <yftzeng@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT License
 * @link     http://blog.gcos.me/
 */

namespace Wow\Security;

/**
 * Wow Secure Cookie Manager class
 *
 * @category Wow
 * @package  WowSecureCookie
 * @author   Matthieu Huguet <matthieu@huguet.eu>
 * @author   Tzeng, Yi-Feng <yftzeng@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT License
 * @link     http://blog.gcos.me/
 */

class WowSecureCookie
{

    /**
     * Server secret key
     * @var string
     */
    protected $secret = '';

    /**
     * Encrypt/Decrypt IV, only works if PHP version >= 5.3.3
     * Must be 16 bytes long
     * @var string
     */
    protected $iv = '1234567890123456';

    /**
     * Cryptographic algorithm used to encrypt cookies data
     * Ref: http://www.php.net/manual/en/function.openssl-get-cipher-methods.php
     * @var object
     */
    protected $algorithm = 'AES-256-CTR';

    /**
     * Salt for Hash algorithm used to hash cookies data
     * @var string
     */
    protected $salt = 'badbadguy';

    /**
     * Default cookie expired time
     * 86400   = 24 hour = 1 day
     * 2592000 = 30 day
     * @var int
     */
    protected $expired_time = 2592000;

    /**
     * Hash algorithm used to hash cookies data
     * Ref: http://www.php.net/manual/en/function.hash-algos.php
     * @var string
     */
    protected $hash = 'sha1';

    /**
     * Secure Cookie level
     * 1: secureValue = username|expire|value|HMAC(user|expire|value,k)
     * 2: secureValue =
     *    username|expire|base64((value)k,expire)|HMAC(user|expire|value,k)
     * 3: secureValue = encrypt(value)
     * 4: secureValue = username|expire|encrypt(value)|HMAC(user|expire|value,k)
     * @var bool
     */
    protected $secure_level = 3;

    /**
     * Enable SSL support
     * @var bool
     */
    protected $ssl = false;

    /**
     * @param string $secret server's secret key
     * @param array  $config config array
     *
     * @comment Constructor
     *
     * Initialize cookie manager and mcrypt module.
     *
     * @return void
     */
    public function __construct($secret, $config = null)
    {
        if (empty($secret)) {
            throw new \Exception('You must provide a secret key');
        }

        $this->secret = $secret;

        if ($config !== null && !is_array($config)) {
            throw new \Exception('Config must be an array');
        }

        if (is_array($config)) {
            if (isset($config['algorithm'])) {
                $this->algorithm = $config['algorithm'];
            }
            if (isset($config['iv'])) {
                $this->iv = $config['iv'];
            }
            if (isset($config['salt'])) {
                $this->salt = $config['salt'];
            }
            if (isset($config['default_expire'])) {
                $this->expired_time = $config['default_expire'];
            }
            if (isset($config['hash'])) {
                $this->hash = $config['hash'];
            }
            if (isset($config['secure_level'])) {
                $this->secure_level = $config['secure_level'];
            }
            if (isset($config['enable_ssl'])) {
                $this->ssl = $config['enable_ssl'];
            }
        }

        if (in_array($this->algorithm, openssl_get_cipher_methods()) === false) {
            throw new \Exception('Error while loading mcrypt module');
        }
    }

    /**
     * Get the secure level mode
     *
     * @return bool true if cookie data encryption is enabled, or false if it isn't
     */
    public function getSecureLevel()
    {
        return $this->secure_level;
    }

    /**
     * @param bool $enable true to enable, false to disable
     *
     * @comment Set the secure level mode
     * Enable or disable cookie data encryption
     *
     * @return mixed
     */
    public function setSecureLevel($enable)
    {
        $this->secure_level = $enable;
        return $this;
    }

    /**
     * @comment Get the SSL status (enabled or disabled?)
     *
     * @return bool true if SSL support is enabled, or false if it isn't
     *
     */
    public function getSSL()
    {
        return $this->ssl;
    }

    /**
     * @param bool $enable true to enable, false to disable
     *
     * @comment Enable SSL support (not enabled by default)
     * pro: protect against replay attack
     * con: cookie's lifetime is limited to SSL session's lifetime
     *
     * @return mixed
     */
    public function setSSL($enable)
    {
        $this->ssl = $enable;
        return $this;
    }

    /**
     * @param string $username username
     *
     * @comment Hash username for more secure
     *
     * @return string
     */
    public function doHash($username)
    {
        if ($this->hash === 'sha1') {
            return sha1($username . $this->salt);
        } elseif ($this->hash === 'md5') {
            return md5($username . $this->salt);
        } else {
            return sha1($username . $this->salt);
        }
    }

    /**
     * @param string  $cookiename cookie name
     * @param string  $value      cookie value
     * @param string  $username   user name (or ID)
     * @param integer $expire     expiration time
     * @param string  $path       cookie path
     * @param string  $domain     cookie domain
     * @param bool    $secure     when true, send cookie only on secure connection
     * @param bool    $httponly   when true the cookie will be made accessible only
     *                            through the HTTP protocol
     *
     * @comment Send a secure cookie
     *
     * @return mixed
     */
    public function setCookie(
        $cookiename, $value, $username = null, $expire = null, $path = '',
        $domain = '', $secure = false, $httponly = null
    ) {
        if ($this->secure_level !==3 ) {
            if (is_null($username)) {
                throw new \Exception('You must provide $username argument');
            }
        }
        $expire = is_null($expire) ? time() + $this->expired_time : $expire;
        if ($this->secure_level === 2) {
            $value = base64_encode($value . ',' . $expire);
        }
        if ($this->secure_level === 3) {
            $secureValue = $this->encrypt($value, $this->secret);
        } else {
            $secureValue = $this->secureCookieHashValue(
                $value, $this->doHash($username), $expire
            );
        }
        $this->setClassicCookie(
            $cookiename, $secureValue, $expire, $path, $domain, $secure, $httponly
        );
    }

    /**
     * @param string $cookiename cookie name
     * @param string $path       cookie path
     * @param string $domain     cookie domain
     * @param bool   $secure     when true, send cookie only on a secure connection
     * @param bool   $httponly   when true the cookie will be made accessible only
     *                           through the HTTP protocol
     *
     * @comment Delete a cookie
     *
     * @return void
     */
    public function deleteCookie(
        $cookiename, $path = '/', $domain = '', $secure = false, $httponly = null
    ) {
        // delete cookie only once
        if (isset($this->deleted)) {
            return;
        } else {
            $this->deleted = true;
        }
        /* 1980-01-01 */
        $expire = 315554400;
        setcookie($cookiename, '', $expire, $path, $domain, $secure, $httponly);
    }

    /**
     * @param string $cookiename      cookie name
     * @param bool   $deleteIfInvalid destroy the cookie if invalid
     *
     * @comment Get a secure cookie value
     *
     * Verify the integrity of cookie data and decrypt it.
     * If the cookie is invalid, it can be automatically destroyed
     * (default behaviour)
     *
     * @return mixed
     */
    public function getCookie($cookiename, $deleteIfInvalid = true)
    {
        if ($this->cookieExists($cookiename)) {
            if ($this->secure_level === 3) {
                return $this->decrypt($_COOKIE[$cookiename], $this->secret);
            }
            $cookieValues = explode('|', $_COOKIE[$cookiename]);
            if ((count($cookieValues) === 4)
                && ($cookieValues[1] == 0 || $cookieValues[1] >= time())
            ) {
                $key = hash_hmac(
                    $this->hash, $cookieValues[0].$cookieValues[1], $this->secret
                );
                $cookieData = $cookieValues[2];
                if ($this->secure_level === 1 || $this->secure_level === 2) {
                    $data = $cookieData;
                } elseif ($this->secure_level === 4) {
                    $data = $this->decrypt($cookieData, $key, md5($cookieValues[1]));
                }

                if ($this->_ssl && isset($_SERVER['SSL_SESSION_ID'])) {
                    $verifKey = hash_hmac(
                        $this->hash,
                        $cookieValues[0].$cookieValues[1].$data.
                        $_SERVER['SSL_SESSION_ID'],
                        $key
                    );
                } else {
                    $verifKey = hash_hmac(
                        $this->hash, $cookieValues[0].$cookieValues[1].$data, $key
                    );
                }
                if ($verifKey === $cookieValues[3]) {
                    if ($this->secure_level === 2) {
                        $data = base64_decode($cookieData);
                        $data = explode(',', $data)[0];
                    }
                    return $data;
                }
            }
        }
        if ($deleteIfInvalid) {
            $this->deleteCookie($cookiename);
        }
        return false;
    }

    /**
     * @param string $cookiename      cookie name
     * @param bool   $deleteIfInvalid destroy the cookie if invalid
     *
     * @comment Get a classic (unsecure) cookie value
     *
     * @return mixed
     */
    public function getClassicCookieValue($cookiename, $deleteIfInvalid = true)
    {
        if ($this->cookieExists($cookiename)) {
            return $_COOKIE[$cookiename];
        }
        if ($deleteIfInvalid) {
            $this->deleteCookie($cookiename);
        }
        return false;
    }

    /**
     * @param string  $cookiename cookie name
     * @param string  $value      cookie value
     * @param integer $expire     expiration time
     * @param string  $path       cookie path
     * @param string  $domain     cookie domain
     * @param bool    $secure     when true, send cookie only in secure connection
     * @param bool    $httponly   when true the cookie will be made accessible
     *                            only through the HTTP protocol
     *
     * @comment Send a classic (unsecure) cookie
     *
     * @return void
     */
    public function setClassicCookie(
        $cookiename, $value, $expire = 0, $path = '', $domain = '',
        $secure = false, $httponly = null
    ) {
        /* httponly option is only available for PHP version >= 5.2 */
        if ($httponly !== null
            && (!defined('PHP_VERSION_ID')
            || PHP_VERSION_ID >= 50200)
        ) {

            setcookie(
                $cookiename, $value, $expire, $path, $domain, $secure, $httponly
            );
        } else {
            setcookie($cookiename, $value, $expire, $path, $domain, $secure);
        }
    }

    /**
     * @param string $cookiename the cookie's name
     *
     * @comment Verify if a cookie exists
     *
     * @return bool true if cookie exist, or false if not
     */
    public function cookieExists($cookiename)
    {
        return isset($_COOKIE[$cookiename]);
    }

    /**
     * @param string  $value    unsecure value
     * @param string  $username user name (or ID)
     * @param integer $expire   expiration time
     *
     * @comment Secure a hash cookie value
     *
     * The initial value is transformed with this protocol :
     *
     *  secureValue =
     *      username|expire|base64((value)k,expire)|HMAC(user|expire|value,k)
     *  where k = HMAC(user|expire, sk)
     *  and sk is server's secret key
     *  (value)k,md5(expire) is the result an cryptographic function (ex: AES256)
     *  on "value" with key k and initialisation vector = md5(expire)
     *
     * @return string secured value
    */

    protected function secureCookieHashValue($value, $username, $expire)
    {
        $key = hash_hmac($this->hash, $username.$expire, $this->secret);
        if ($this->secure_level === 4) {
            $encryptedValue = $this->encrypt($value, $key, md5($expire));
        } else {
            $encryptedValue = $value;
        }
        if ($this->_ssl && isset($_SERVER['SSL_SESSION_ID'])) {
            $verifKey = hash_hmac(
                $this->hash,
                $username . $expire . $value . $_SERVER['SSL_SESSION_ID'],
                $key
            );
        } else {
            $verifKey = hash_hmac($this->hash, $username . $expire . $value, $key);
        }
        $result = array($username, $expire, $encryptedValue, $verifKey);
        return implode('|', $result);
    }

    /**
     * @param string $data data to crypt
     * @param string $key  secret key
     *
     * @comment Encrypt given data with given key and a given initialisation vector
     *
     * @return string encrypted data
     */
    protected function encrypt($data, $key)
    {
        /* If PHP version >= 5.3.3 */
        if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID >= 50303) {
            $res = openssl_encrypt(
                $data, $this->algorithm, $key, false, $this->iv
            );
        } else {
            $res = openssl_encrypt($data, $this->algorithm, $key, false);
        }
        return $res;
    }

    /**
     * @param string $data data to crypt
     * @param string $key  secret key
     *
     * @comment Decrypt given data with given key and a given initialisation vector
     *
     * @return string encrypted data
     */
    protected function decrypt($data, $key)
    {
        /* If PHP version >= 5.3.3 */
        if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID >= 50303) {
            $res = openssl_decrypt(
                $data, $this->algorithm, $key, false, $this->iv
            );
        } else {
            $res = openssl_decrypt($data, $this->algorithm, $key, false);
        }
        return $res;
    }

    /**
     * @param string $data set given secret
     *
     * @comment set secret
     *
     * @return void
     */
    public function setSecret($data)
    {
        $this->secret = $data;
    }

    /**
     * @param string $data set given iv
     *
     * @comment set iv
     *
     * @return void
     */
    public function setIv($data)
    {
        $this->iv = $data;
    }

    /**
     * @param string $data set given encryption algorithm
     *
     * @comment set encryption algorithm
     *
     * @return void
     */
    public function setAlgorithm($data)
    {
        $this->algorithm = $data;
    }

    /**
     * @param string $data set salt
     *
     * @comment set salt
     *
     * @return void
     */
    public function setSalt($data)
    {
        $this->salt = $data;
    }

    /**
     * @param string $data expired time
     *
     * @comment set expired time
     *
     * @return void
     */
    public function setExpiredTime($data)
    {
        $this->expired_time = $data;
    }

    /**
     * @param string $data data to hash
     *
     * @comment hash a given data
     *
     * @return void
     */
    public function setHash($data)
    {
        $this->hash($data);
    }
}


text:
module Google
  module Analytics
    module Data
      module V1alpha
        # The dimensions and metrics currently accepted in reporting methods.
        # @!attribute [rw] name
        #   @return [::String]
        #     Resource name of this metadata.
        # @!attribute [rw] dimensions
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DimensionMetadata>]
        #     The dimension descriptions.
        # @!attribute [rw] metrics
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricMetadata>]
        #     The metric descriptions.
        class Metadata
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The request to generate a report.
        # @!attribute [rw] entity
        #   @return [::Google::Analytics::Data::V1alpha::Entity]
        #     A property whose events are tracked. Within a batch request, this entity
        #     should either be unspecified or consistent with the batch-level entity.
        # @!attribute [rw] dimensions
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Dimension>]
        #     The dimensions requested and displayed.
        # @!attribute [rw] metrics
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Metric>]
        #     The metrics requested and displayed.
        # @!attribute [rw] date_ranges
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DateRange>]
        #     Date ranges of data to read. If multiple date ranges are requested, each
        #     response row will contain a zero based date range index. If two date
        #     ranges overlap, the event data for the overlapping days is included in the
        #     response rows for both date ranges. In a cohort request, this `dateRanges`
        #     must be unspecified.
        # @!attribute [rw] offset
        #   @return [::Integer]
        #     The row count of the start row. The first row is counted as row 0.
        #
        #     To learn more about this pagination parameter, see
        #     [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).
        # @!attribute [rw] limit
        #   @return [::Integer]
        #     The number of rows to return. If unspecified, 10 rows are returned. If
        #     -1, all rows are returned.
        #
        #     To learn more about this pagination parameter, see
        #     [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).
        # @!attribute [rw] metric_aggregations
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricAggregation>]
        #     Aggregation of metrics. Aggregated metric values will be shown in rows
        #     where the dimension_values are set to "RESERVED_(MetricAggregation)".
        # @!attribute [rw] dimension_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of dimensions. Dimensions must be requested to be used in
        #     this filter. Metrics cannot be used in this filter.
        # @!attribute [rw] metric_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of metrics. Applied at post aggregation phase, similar to
        #     SQL having-clause. Metrics must be requested to be used in this filter.
        #     Dimensions cannot be used in this filter.
        # @!attribute [rw] order_bys
        #   @return [::Array<::Google::Analytics::Data::V1alpha::OrderBy>]
        #     Specifies how rows are ordered in the response.
        # @!attribute [rw] currency_code
        #   @return [::String]
        #     A currency code in ISO4217 format, such as "AED", "USD", "JPY".
        #     If the field is empty, the report uses the entity's default currency.
        # @!attribute [rw] cohort_spec
        #   @return [::Google::Analytics::Data::V1alpha::CohortSpec]
        #     Cohort group associated with this request. If there is a cohort group
        #     in the request the 'cohort' dimension must be present.
        # @!attribute [rw] keep_empty_rows
        #   @return [::Boolean]
        #     If false or unspecified, each row with all metrics equal to 0 will not be
        #     returned. If true, these rows will be returned if they are not separately
        #     removed by a filter.
        # @!attribute [rw] return_property_quota
        #   @return [::Boolean]
        #     Toggles whether to return the current state of this Analytics Property's
        #     quota. Quota is returned in [PropertyQuota](#PropertyQuota).
        class RunReportRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The response report table corresponding to a request.
        # @!attribute [rw] dimension_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DimensionHeader>]
        #     Describes dimension columns. The number of DimensionHeaders and ordering of
        #     DimensionHeaders matches the dimensions present in rows.
        # @!attribute [rw] metric_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricHeader>]
        #     Describes metric columns. The number of MetricHeaders and ordering of
        #     MetricHeaders matches the metrics present in rows.
        # @!attribute [rw] rows
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     Rows of dimension value combinations and metric values in the report.
        # @!attribute [rw] totals
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the totaled values of metrics.
        # @!attribute [rw] maximums
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the maximum values of metrics.
        # @!attribute [rw] minimums
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the minimum values of metrics.
        # @!attribute [rw] row_count
        #   @return [::Integer]
        #     The total number of rows in the query result, regardless of the number of
        #     rows returned in the response. For example if a query returns 175 rows and
        #     includes limit = 50 in the API request, the response will contain row_count
        #     = 175 but only 50 rows.
        #
        #     To learn more about this pagination parameter, see
        #     [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).
        # @!attribute [rw] metadata
        #   @return [::Google::Analytics::Data::V1alpha::ResponseMetaData]
        #     Metadata for the report.
        # @!attribute [rw] property_quota
        #   @return [::Google::Analytics::Data::V1alpha::PropertyQuota]
        #     This Analytics Property's quota state including this request.
        class RunReportResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The request to generate a pivot report.
        # @!attribute [rw] entity
        #   @return [::Google::Analytics::Data::V1alpha::Entity]
        #     A property whose events are tracked. Within a batch request, this entity
        #     should either be unspecified or consistent with the batch-level entity.
        # @!attribute [rw] dimensions
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Dimension>]
        #     The dimensions requested. All defined dimensions must be used by one of the
        #     following: dimension_expression, dimension_filter, pivots, order_bys.
        # @!attribute [rw] metrics
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Metric>]
        #     The metrics requested, at least one metric needs to be specified. All
        #     defined metrics must be used by one of the following: metric_expression,
        #     metric_filter, order_bys.
        # @!attribute [rw] dimension_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of dimensions. Dimensions must be requested to be used in
        #     this filter. Metrics cannot be used in this filter.
        # @!attribute [rw] metric_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of metrics. Applied at post aggregation phase, similar to
        #     SQL having-clause. Metrics must be requested to be used in this filter.
        #     Dimensions cannot be used in this filter.
        # @!attribute [rw] pivots
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Pivot>]
        #     Describes the visual format of the report's dimensions in columns or rows.
        #     The union of the fieldNames (dimension names) in all pivots must be a
        #     subset of dimension names defined in Dimensions. No two pivots can share a
        #     dimension. A dimension is only visible if it appears in a pivot.
        # @!attribute [rw] date_ranges
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DateRange>]
        #     The date range to retrieve event data for the report. If multiple date
        #     ranges are specified, event data from each date range is used in the
        #     report. A special dimension with field name "dateRange" can be included in
        #     a Pivot's field names; if included, the report compares between date
        #     ranges. In a cohort request, this `dateRanges` must be unspecified.
        # @!attribute [rw] currency_code
        #   @return [::String]
        #     A currency code in ISO4217 format, such as "AED", "USD", "JPY".
        #     If the field is empty, the report uses the entity's default currency.
        # @!attribute [rw] cohort_spec
        #   @return [::Google::Analytics::Data::V1alpha::CohortSpec]
        #     Cohort group associated with this request. If there is a cohort group
        #     in the request the 'cohort' dimension must be present.
        # @!attribute [rw] keep_empty_rows
        #   @return [::Boolean]
        #     If false or unspecified, each row with all metrics equal to 0 will not be
        #     returned. If true, these rows will be returned if they are not separately
        #     removed by a filter.
        # @!attribute [rw] return_property_quota
        #   @return [::Boolean]
        #     Toggles whether to return the current state of this Analytics Property's
        #     quota. Quota is returned in [PropertyQuota](#PropertyQuota).
        class RunPivotReportRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The response pivot report table corresponding to a pivot request.
        # @!attribute [rw] pivot_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::PivotHeader>]
        #     Summarizes the columns and rows created by a pivot. Each pivot in the
        #     request produces one header in the response. If we have a request like
        #     this:
        #
        #         "pivots": [{
        #           "fieldNames": ["country",
        #             "city"]
        #         },
        #         {
        #           "fieldNames": "eventName"
        #         }]
        #
        #     We will have the following `pivotHeaders` in the response:
        #
        #         "pivotHeaders" : [{
        #           "dimensionHeaders": [{
        #             "dimensionValues": [
        #                { "value": "United Kingdom" },
        #                { "value": "London" }
        #              ]
        #           },
        #           {
        #             "dimensionValues": [
        #             { "value": "Japan" },
        #             { "value": "Osaka" }
        #             ]
        #           }]
        #         },
        #         {
        #           "dimensionHeaders": [{
        #             "dimensionValues": [{ "value": "session_start" }]
        #           },
        #           {
        #             "dimensionValues": [{ "value": "scroll" }]
        #           }]
        #         }]
        # @!attribute [rw] dimension_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DimensionHeader>]
        #     Describes dimension columns. The number of DimensionHeaders and ordering of
        #     DimensionHeaders matches the dimensions present in rows.
        # @!attribute [rw] metric_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricHeader>]
        #     Describes metric columns. The number of MetricHeaders and ordering of
        #     MetricHeaders matches the metrics present in rows.
        # @!attribute [rw] rows
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     Rows of dimension value combinations and metric values in the report.
        # @!attribute [rw] aggregates
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     Aggregation of metric values. Can be totals, minimums, or maximums. The
        #     returned aggregations are controlled by the metric_aggregations in the
        #     pivot. The type of aggregation returned in each row is shown by the
        #     dimension_values which are set to "RESERVED_<MetricAggregation>".
        # @!attribute [rw] metadata
        #   @return [::Google::Analytics::Data::V1alpha::ResponseMetaData]
        #     Metadata for the report.
        # @!attribute [rw] property_quota
        #   @return [::Google::Analytics::Data::V1alpha::PropertyQuota]
        #     This Analytics Property's quota state including this request.
        class RunPivotReportResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The batch request containing multiple report requests.
        # @!attribute [rw] entity
        #   @return [::Google::Analytics::Data::V1alpha::Entity]
        #     A property whose events are tracked. This entity must be specified for the
        #     batch. The entity within RunReportRequest may either be unspecified or
        #     consistent with this entity.
        # @!attribute [rw] requests
        #   @return [::Array<::Google::Analytics::Data::V1alpha::RunReportRequest>]
        #     Individual requests. Each request has a separate report response. Each
        #     batch request is allowed up to 5 requests.
        class BatchRunReportsRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The batch response containing multiple reports.
        # @!attribute [rw] reports
        #   @return [::Array<::Google::Analytics::Data::V1alpha::RunReportResponse>]
        #     Individual responses. Each response has a separate report request.
        class BatchRunReportsResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The batch request containing multiple pivot report requests.
        # @!attribute [rw] entity
        #   @return [::Google::Analytics::Data::V1alpha::Entity]
        #     A property whose events are tracked. This entity must be specified for the
        #     batch. The entity within RunPivotReportRequest may either be unspecified or
        #     consistent with this entity.
        # @!attribute [rw] requests
        #   @return [::Array<::Google::Analytics::Data::V1alpha::RunPivotReportRequest>]
        #     Individual requests. Each request has a separate pivot report response.
        #     Each batch request is allowed up to 5 requests.
        class BatchRunPivotReportsRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The batch response containing multiple pivot reports.
        # @!attribute [rw] pivot_reports
        #   @return [::Array<::Google::Analytics::Data::V1alpha::RunPivotReportResponse>]
        #     Individual responses. Each response has a separate pivot report request.
        class BatchRunPivotReportsResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # Request for a property's dimension and metric metadata.
        # @!attribute [rw] name
        #   @return [::String]
        #     Required. The resource name of the metadata to retrieve. This name field is
        #     specified in the URL path and not URL parameters. Property is a numeric
        #     Google Analytics GA4 Property identifier. To learn more, see [where to find
        #     your Property
        #     ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).
        #
        #     Example: properties/1234/metadata
        #
        #     Set the Property ID to 0 for dimensions and metrics common to all
        #     properties. In this special mode, this method will not return custom
        #     dimensions and metrics.
        class GetMetadataRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The request to generate a realtime report.
        # @!attribute [rw] property
        #   @return [::String]
        #     A Google Analytics GA4 property identifier whose events are tracked.
        #     Specified in the URL path and not the body. To learn more, see [where to
        #     find your Property
        #     ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).
        #
        #     Example: properties/1234
        # @!attribute [rw] dimensions
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Dimension>]
        #     The dimensions requested and displayed.
        # @!attribute [rw] metrics
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Metric>]
        #     The metrics requested and displayed.
        # @!attribute [rw] limit
        #   @return [::Integer]
        #     The number of rows to return. If unspecified, 10 rows are returned. If
        #     -1, all rows are returned.
        # @!attribute [rw] dimension_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of dimensions. Dimensions must be requested to be used in
        #     this filter. Metrics cannot be used in this filter.
        # @!attribute [rw] metric_filter
        #   @return [::Google::Analytics::Data::V1alpha::FilterExpression]
        #     The filter clause of metrics. Applied at post aggregation phase, similar to
        #     SQL having-clause. Metrics must be requested to be used in this filter.
        #     Dimensions cannot be used in this filter.
        # @!attribute [rw] metric_aggregations
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricAggregation>]
        #     Aggregation of metrics. Aggregated metric values will be shown in rows
        #     where the dimension_values are set to "RESERVED_(MetricAggregation)".
        # @!attribute [rw] order_bys
        #   @return [::Array<::Google::Analytics::Data::V1alpha::OrderBy>]
        #     Specifies how rows are ordered in the response.
        # @!attribute [rw] return_property_quota
        #   @return [::Boolean]
        #     Toggles whether to return the current state of this Analytics Property's
        #     Realtime quota. Quota is returned in [PropertyQuota](#PropertyQuota).
        class RunRealtimeReportRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The response realtime report table corresponding to a request.
        # @!attribute [rw] dimension_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::DimensionHeader>]
        #     Describes dimension columns. The number of DimensionHeaders and ordering of
        #     DimensionHeaders matches the dimensions present in rows.
        # @!attribute [rw] metric_headers
        #   @return [::Array<::Google::Analytics::Data::V1alpha::MetricHeader>]
        #     Describes metric columns. The number of MetricHeaders and ordering of
        #     MetricHeaders matches the metrics present in rows.
        # @!attribute [rw] rows
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     Rows of dimension value combinations and metric values in the report.
        # @!attribute [rw] totals
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the totaled values of metrics.
        # @!attribute [rw] maximums
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the maximum values of metrics.
        # @!attribute [rw] minimums
        #   @return [::Array<::Google::Analytics::Data::V1alpha::Row>]
        #     If requested, the minimum values of metrics.
        # @!attribute [rw] row_count
        #   @return [::Integer]
        #     The total number of rows in the query result, regardless of the number of
        #     rows returned in the response. For example if a query returns 175 rows and
        #     includes limit = 50 in the API request, the response will contain row_count
        #     = 175 but only 50 rows.
        # @!attribute [rw] property_quota
        #   @return [::Google::Analytics::Data::V1alpha::PropertyQuota]
        #     This Analytics Property's Realtime quota state including this request.
        class RunRealtimeReportResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end
      end
    end
  end
end


text:
package com.sedsoftware.xyzreader.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtils {

  public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
  }
}