text:
/************************************************************************************//**
 * @file CTriggers.cpp
 * @brief Trigger handler
 *
 * This file contains the class implementation for the CTriggers class that
 * encapsulates trigger handling in the RGF.
 * @author Ralph Deane
 *//*
 * Copyright (c) 2001 Ralph Deane; All rights reserved.
 ****************************************************************************************/

// You only need the one, master include file.
#include "RabidFramework.h"

extern geSound_Def *SPool_Sound(const char *SName);

/* ------------------------------------------------------------------------------------ */
//	CTriggers
//
//	Default constructor.  Set all triggers to default values and load any audio we need.
/* ------------------------------------------------------------------------------------ */
CTriggers::CTriggers()
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	m_TriggerCount = 0;					// No triggers

	// Ok, check to see if there are triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return;									// No triggers

	// Ok, we have triggers somewhere.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		if(pTrigger->Model == NULL)
		{
			char szError[256];
			sprintf(szError, "[WARNING] File %s - Line %d: '%s' Missing Model",
					__FILE__, __LINE__, pTrigger->szEntityName);
			CCD->ReportError(szError, false);

			continue;
		}

		if(EffectC_IsStringNull(pTrigger->szEntityName))
		{
			char szName[128];
			geEntity_GetName(pEntity, szName, 128);
			pTrigger->szEntityName = szName;
		}

		m_TriggerCount++;							// Kick count

		// Ok, put this entity into the Global Entity Registry
		CCD->EntityRegistry()->AddEntity(pTrigger->szEntityName, "Trigger");

		// Now add the trigger into the Model Manager, which will do all the
		// ..hard work for us!
		{
			CCD->ModelManager()->AddModel(pTrigger->Model, ENTITY_TRIGGER);
			CCD->ModelManager()->SetLooping(pTrigger->Model, false);
			CCD->ModelManager()->SetAnimationSpeed(pTrigger->Model, pTrigger->AnimationSpeed);
		}

		// Reset all the animation data for each and every trigger
		pTrigger->bInAnimation	= GE_FALSE;	// Not animating
		pTrigger->AnimationTime = 0.0f;		// No time in animation
		pTrigger->bTrigger		= GE_FALSE;	// Not triggered
		pTrigger->time			= 0.0f;
		pTrigger->isHit			= GE_FALSE;
		pTrigger->CallBack		= GE_FALSE;
		pTrigger->bInCollision	= GE_FALSE;	// No collisions
		pTrigger->bActive		= GE_TRUE;	// Trigger is good to go
		pTrigger->bState		= GE_FALSE;	// Trigger state is off
		pTrigger->LastIncrement = 0.0f;		// No last time count
		pTrigger->theSound		= NULL;		// No sound, right now...
		pTrigger->SoundHandle	= -1;		// No sound playing

		if(!EffectC_IsStringNull(pTrigger->szSoundFile))
		{
			pTrigger->theSound = SPool_Sound(pTrigger->szSoundFile);

			if(!pTrigger->theSound)
			{
				char szError[256];
				sprintf(szError, "[WARNING] File %s - Line %d: %s: Failed to open audio file '%s'\n",
						__FILE__, __LINE__, pTrigger->szEntityName, pTrigger->szSoundFile);
				CCD->ReportError(szError, false);
			}
		}
	}

	//	Ok, we've counted the  triggers and reset 'em all to their default
	//	..values.  Leave!
	return;
}

/* ------------------------------------------------------------------------------------ */
//	~CTriggers
//
//	Default destructor
/* ------------------------------------------------------------------------------------ */
CTriggers::~CTriggers()
{
	return;
}

/* ------------------------------------------------------------------------------------ */
//	HandleCollision
//
//	Handle a collision with a  trigger
/* ------------------------------------------------------------------------------------ */
// changed RF063
int CTriggers::HandleCollision(const geWorld_Model *pModel, bool HitType, bool UseKey, const geActor *theActor)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;
	bool state;

	SetState();

	if(m_TriggerCount == 0)
		return RGF_FAILURE;									// None here, ignore call.

	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
	{
		CCD->ReportError("CTriggers: handlecollision: no triggers", false);
		return RGF_FAILURE;
	}

	// Once more we scan the list.  Does this get old, or what?
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		// Get the  data so we can compare models
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		// changed QD 07/15/06
		if(!pTrigger->Model)
			continue;
		// end change

		if(pTrigger->Model == pModel)
		{
// changed RF063
			if(pTrigger->PlayerOnly && theActor != CCD->Player()->GetActor())
				return false;

// changed RF064
			if((pTrigger->bNoCollide && !UseKey) || (UseKey && !pTrigger->UseKey)
				|| (!pTrigger->bShoot && HitType)
				|| (pTrigger->bShoot && !HitType))
// end change RF064
			{
				FreeState();
				if(CCD->ModelManager()->EmptyContent(pTrigger->Model))
					return RGF_EMPTY;

				return RGF_FAILURE;
			}
// end change RF063

			state = true;

			if(!EffectC_IsStringNull(pTrigger->TriggerName))
				state = GetTTriggerState(pTrigger->TriggerName);

			if(!state)
			{
				pTrigger->CallBack = GE_TRUE;
				pTrigger->CallBackCount = 2;
			}

			// If trigger not already running, and active, trigger it!
			if((!pTrigger->bInAnimation)
				&& (pTrigger->bActive == GE_TRUE)
				&& pTrigger->isHit == GE_FALSE
				&& state == true)
			{
				pTrigger->bState = GE_TRUE;
				pTrigger->bTrigger = GE_TRUE;			// It's this one, trigger the animation
				CCD->ModelManager()->Start(pTrigger->Model);
				pTrigger->SoundHandle = PlaySound(pTrigger->theSound, pTrigger->origin, pTrigger->bAudioLoops);
				pTrigger->isHit = GE_TRUE;
				pTrigger->time = 0.0f;
				pTrigger->bInAnimation = GE_TRUE;
			}

			FreeState();

			if(CCD->ModelManager()->EmptyContent(pTrigger->Model))
				return RGF_EMPTY;

			return RGF_SUCCESS;  // Hmmph, we hit a trigger
		}
	}

	FreeState();
	return RGF_FAILURE;							// We hit no known triggers
}

// MOD010122 - Added this function.
/* ------------------------------------------------------------------------------------ */
//	HandleTriggerEvent
//
//	Handle an animated model's trigger event
/* ------------------------------------------------------------------------------------ */
bool CTriggers::HandleTriggerEvent(const char *TName)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;
	bool state;

	SetState();

	if(m_TriggerCount == 0)
		return false;									// None here, ignore call.

	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
	{
		CCD->ReportError("CTriggers: handletriggerevent: no triggers", false);
		return false;
	}

	//	Once more we scan the list.  Does this get old, or what?
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		// Get the  data so we can compare models
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		// changed QD 07/15/06
		if(!pTrigger->Model)
			continue;
		// end change

		if(!strcmp(pTrigger->szEntityName, TName))
		{
			state = true;

			if(!EffectC_IsStringNull(pTrigger->TriggerName))
				state = GetTTriggerState(pTrigger->TriggerName);

			if(!state)
			{
				pTrigger->CallBack = GE_TRUE;
				pTrigger->CallBackCount = 2;
			}

			// If trigger not already running, and active, trigger it!
			if((!pTrigger->bInAnimation)
				&& pTrigger->bActive == GE_TRUE
				&& pTrigger->isHit == GE_FALSE
				&& state == true)
			{
				pTrigger->bState = GE_TRUE;
				pTrigger->bTrigger = GE_TRUE;			// It's this one, trigger the animation
// changed RF063
				CCD->ModelManager()->Start(pTrigger->Model);
// end change RF063
				pTrigger->SoundHandle = PlaySound(pTrigger->theSound, pTrigger->origin, pTrigger->bAudioLoops);
				pTrigger->isHit = GE_TRUE;
				pTrigger->time = 0.0f;
				pTrigger->bInAnimation = GE_TRUE;
			}

			FreeState();
			return true;  // Hmmph, we hit a trigger
		}
	}

    FreeState();
    return false;							// We hit no known triggers
}

/* ------------------------------------------------------------------------------------ */
//	PlaySound
/* ------------------------------------------------------------------------------------ */
// changed QD 12/15/05 - changed 2nd argument from geVec3d to const geVec3d&
int CTriggers::PlaySound(geSound_Def *theSound, const geVec3d &Origin, bool SoundLoop)
{
	if(!theSound)
		return -1;

	Snd Sound;

	memset(&Sound, 0, sizeof(Sound));
    geVec3d_Copy(&Origin, &(Sound.Pos));
    Sound.Min = CCD->GetAudibleRadius();
	Sound.Loop = SoundLoop;
	Sound.SoundDef = theSound;
	int index = CCD->EffectManager()->Item_Add(EFF_SND, (void*)&Sound);

	if(SoundLoop)
		return index;

	return -1;
}

/* ------------------------------------------------------------------------------------ */
//	IsATrigger
//
//	Return TRUE if the passed-in model is a  trigger, FALSE otherwise
/* ------------------------------------------------------------------------------------ */
bool CTriggers::IsATrigger(const geWorld_Model *theModel)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	if(m_TriggerCount == 0)
		return false;										// Don't waste time here.

	// Ok, check to see if there are  triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return false;									// No  triggers

	// Ok, we have  triggers somewhere.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		// changed QD 07/15/06
		if(!pTrigger->Model)
			continue;
		// end change

		if(pTrigger->Model == theModel)
			return true;							// Model IS a trigger
	}

	return false;							// Nope, it's not a trigger
}

/* ------------------------------------------------------------------------------------ */
//	Tick
//
//	Increment animation times for all _animating_  triggers that aren't
//	..in a collision state.
/* ------------------------------------------------------------------------------------ */
void CTriggers::Tick(geFloat dwTicks)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	if(m_TriggerCount == 0)
		return;									// Don't waste time here

	// Ok, check to see if there are  triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return;									// No  triggers

	// Ok, we have triggers somewhere.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		if(!pTrigger->Model)
			continue;

		pTrigger->LastIncrement = dwTicks;					// The amount that moved

		if(pTrigger->isHit == GE_TRUE)
		{
			pTrigger->time += dwTicks;

			if(pTrigger->bState == GE_TRUE)
			{
				if(pTrigger->time >= (pTrigger->TimeOn*1000.0f))
				{
					pTrigger->bState = GE_FALSE;
					pTrigger->time = 0.0f;
					// MOD010122 - Next line commented out to fix bug.  isHit should not be turned off until the full trigger
					//             cycle, on-off is complete.
					//					pTrigger->isHit=false;
				}
			}
			else
			{
				if(pTrigger->time >= (pTrigger->TimeOff*1000.0f))
				{
					pTrigger->bState = GE_FALSE;
					pTrigger->isHit = GE_FALSE;
					pTrigger->time = 0.0f;
				}
			}
		}

		if(pTrigger->CallBack == GE_TRUE)
		{
			pTrigger->CallBackCount -= 1;

			if(pTrigger->CallBackCount == 0)
				pTrigger->CallBack = GE_FALSE;
		}

		if((pTrigger->bInAnimation == GE_TRUE) &&
			(CCD->ModelManager()->IsRunning(pTrigger->Model) == false))
		{
			// Animation has stopped/not running, handle it.
			// MOD010122 - The "&& (!pTrigger->isHit)" was added to the next if statement.  We don't want to reset until
			//             the full trigger cycle, on-off, is complete.
			if((pTrigger->bOneShot != GE_TRUE) && (pTrigger->bActive == GE_TRUE) && (!pTrigger->isHit))
			{
				// Ok, not one-shot, reset the door
				pTrigger->bInAnimation = GE_FALSE;
				pTrigger->bTrigger = GE_FALSE;
			}

			CCD->ModelManager()->Stop(pTrigger->Model);

			if(pTrigger->SoundHandle != -1)
			{
				CCD->EffectManager()->Item_Delete(EFF_SND, pTrigger->SoundHandle);
				pTrigger->SoundHandle = -1;
			}
		}
	}

	return;
}

/* ------------------------------------------------------------------------------------ */
//	SaveTo
//
//	Save the current state of every  trigger in the current world off to an open file.
/* ------------------------------------------------------------------------------------ */
int CTriggers::SaveTo(FILE *SaveFD, bool type)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	// Ok, check to see if there are  triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return RGF_SUCCESS;									// No triggers, whatever...

	// Ok, we have triggers somewhere.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		// changed QD 07/15/06
		if(!pTrigger->Model)
			continue;
		// end change

		WRITEDATA(type, &pTrigger->bInAnimation,	sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->bTrigger,		sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->AnimationTime,	sizeof(int),		1, SaveFD);
		WRITEDATA(type, &pTrigger->bInCollision,	sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->bActive,			sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->LastIncrement,	sizeof(int),		1, SaveFD);
		WRITEDATA(type, &pTrigger->tDoor,			sizeof(float),		1, SaveFD);
		WRITEDATA(type, &pTrigger->origin,			sizeof(geVec3d),	1, SaveFD);
		WRITEDATA(type, &pTrigger->bState,			sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->time,			sizeof(float),		1, SaveFD);
		WRITEDATA(type, &pTrigger->isHit,			sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->CallBack,		sizeof(geBoolean),	1, SaveFD);
		WRITEDATA(type, &pTrigger->CallBackCount,	sizeof(int),		1, SaveFD);
	}

	return RGF_SUCCESS;
}

/* ------------------------------------------------------------------------------------ */
//	RestoreFrom
//
//	Restore the state of every  trigger in the current world from an open file.
/* ------------------------------------------------------------------------------------ */
int CTriggers::RestoreFrom(FILE *RestoreFD, bool type)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	// Ok, check to see if there are  triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return RGF_SUCCESS;									// No triggers, whatever...

	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTrigger = (Trigger*)geEntity_GetUserData(pEntity);

		// changed QD 07/15/06
		if(!pTrigger->Model)
			continue;
		// end change

		READDATA(type, &pTrigger->bInAnimation,		sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->bTrigger,			sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->AnimationTime,	sizeof(int),		1, RestoreFD);
		READDATA(type, &pTrigger->bInCollision,		sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->bActive,			sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->LastIncrement,	sizeof(int),		1, RestoreFD);
		READDATA(type, &pTrigger->tDoor,			sizeof(float),		1, RestoreFD);
		READDATA(type, &pTrigger->origin,			sizeof(geVec3d),	1, RestoreFD);
		READDATA(type, &pTrigger->bState,			sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->time,				sizeof(float),		1, RestoreFD);
		READDATA(type, &pTrigger->isHit,			sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->CallBack,			sizeof(geBoolean),	1, RestoreFD);
		READDATA(type, &pTrigger->CallBackCount,	sizeof(int),		1, RestoreFD);

		if(pTrigger->bInAnimation)
			geWorld_OpenModel(CCD->World(), pTrigger->Model, GE_TRUE);
    }

	return RGF_SUCCESS;
}

//	******************** CRGF Overrides ********************

/* ------------------------------------------------------------------------------------ */
//	LocateEntity
//
//	Given a name, locate the desired item in the currently loaded level
//	..and return it's user data.
/* ------------------------------------------------------------------------------------ */
int CTriggers::LocateEntity(const char *szName, void **pEntityData)
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;

	// Ok, check to see if there are  triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return RGF_NOT_FOUND;									// No triggers

	// Ok, we have  triggers.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pTheEntity = (Trigger*)geEntity_GetUserData(pEntity);

		if(!strcmp(pTheEntity->szEntityName, szName))
		{
			*pEntityData = (void*)pTheEntity;
			return RGF_SUCCESS;
		}
	}

	return RGF_NOT_FOUND;								// Sorry, no such entity here
}

/* ------------------------------------------------------------------------------------ */
//	ReSynchronize
//
//	Correct internal timing to match current time, to make up for time lost
//	..when outside the game loop (typically in "menu mode").
/* ------------------------------------------------------------------------------------ */
int CTriggers::ReSynchronize()
{
	return RGF_SUCCESS;
}

/* ------------------------------------------------------------------------------------ */
//	SetState
/* ------------------------------------------------------------------------------------ */
void CTriggers::SetState()
{
	geEntity_EntitySet *pSet;
	geEntity *pEntity;
	TState *pool;

	Bottom = (TState *)NULL;

	if(m_TriggerCount == 0)
		return;						// Don't waste CPU cycles

	// Ok, check to see if there are triggers in this world
	pSet = geWorld_GetEntitySet(CCD->World(), "Trigger");

	if(!pSet)
		return;

	// Ok, we have triggers somewhere.  Dig through 'em all.
	for(pEntity=geEntity_EntitySetGetNextEntity(pSet, NULL); pEntity;
		pEntity=geEntity_EntitySetGetNextEntity(pSet, pEntity))
	{
		Trigger *pSource = (Trigger*)geEntity_GetUserData(pEntity);

		if(EffectC_IsStringNull(pSource->szEntityName))
		{
			char szName[128];
			geEntity_GetName(pEntity, szName, 128);
			pSource->szEntityName = szName;
		}

		pool = GE_RAM_ALLOCATE_STRUCT(TState);
		memset(pool, 0xbb, sizeof(TState));
		pool->next = Bottom;
		Bottom = pool;

		if(pool->next)
			pool->next->prev = pool;

		pool->Name = strdup(pSource->szEntityName);
		pool->state = pSource->bState;
	}

	return;
}

/* ------------------------------------------------------------------------------------ */
//	GetTTriggerState
/* ------------------------------------------------------------------------------------ */
bool CTriggers::GetTTriggerState(const char *Name)
{
	TState *pool;

	char *EntityType = CCD->EntityRegistry()->GetEntityType(Name);

	if(EntityType)
	{
		if(!stricmp(EntityType, "Trigger"))
		{
			pool = Bottom;

			while(pool != NULL)
			{
				if(!stricmp(Name, pool->Name))
					return pool->state;

				pool = pool->next;
			}

			char szError[256];
			sprintf(szError, "[WARNING] File %s - Line %d: Invalid Trigger Name '%s'\n",
					__FILE__, __LINE__, Name);
			CCD->ReportError(szError, false);
			return false;
		}
	}

	return GetTriggerState(Name);
}

/* ------------------------------------------------------------------------------------ */
//	FreeState
/* ------------------------------------------------------------------------------------ */
void CTriggers::FreeState()
{
	TState *pool, *temp;
	pool = Bottom;

	while(pool != NULL)
	{
		temp = pool->next;
		free(pool->Name);
		geRam_Free(pool);
		pool = temp;
	}
}

/* ----------------------------------- END OF FILE ------------------------------------ */


text:
"""
    Swaggy Jenkins

    Jenkins API clients generated from Swagger / Open API specification  # noqa: E501

    The version of the OpenAPI document: 1.5.1-pre.0
    Contact: blah@cliffano.com
    Generated by: https://openapi-generator.tech
"""

import unittest

import openapi_client
from openapi_client.model.default_crumb_issuer import DefaultCrumbIssuer

class TestDefaultCrumbIssuer(unittest.TestCase):
    """DefaultCrumbIssuer unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_DefaultCrumbIssuer(self):
        """Test DefaultCrumbIssuer"""
        # FIXME: construct object with mandatory attributes with example values
        # model = DefaultCrumbIssuer()  # noqa: E501
        pass

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.pulsar.broker.limiter;

import com.google.common.annotations.VisibleForTesting;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang3.mutable.MutableInt;
import org.apache.pulsar.common.tls.InetAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public interface ConnectionController {

    /**
     * Increase the number of connections counter.
     * @param remoteAddress
     * @return
     */
    State increaseConnection(SocketAddress remoteAddress);

    /**
     * Decrease the number of connections counter.
     * @param remoteAddress
     */
    void decreaseConnection(SocketAddress remoteAddress);

    enum State {
        OK, REACH_MAX_CONNECTION_PER_IP, REACH_MAX_CONNECTION;
    }

    class DefaultConnectionController implements ConnectionController {
        private static final Logger log = LoggerFactory.getLogger(DefaultConnectionController.class);
        private static final Map<String, MutableInt> CONNECTIONS = new HashMap<>();
        private static final ReentrantLock lock = new ReentrantLock();
        private static int totalConnectionNum = 0;

        private final int maxConnections;
        private final int maxConnectionPerIp;
        private final boolean maxConnectionsLimitEnabled;
        private final boolean maxConnectionsLimitPerIpEnabled;

        public DefaultConnectionController(int maxConnections, int maxConnectionPerIp) {
            this.maxConnections = maxConnections;
            this.maxConnectionPerIp = maxConnectionPerIp;
            this.maxConnectionsLimitEnabled = maxConnections > 0;
            this.maxConnectionsLimitPerIpEnabled = maxConnectionPerIp > 0;
        }

        @Override
        public State increaseConnection(SocketAddress remoteAddress) {
            if (!maxConnectionsLimitEnabled && !maxConnectionsLimitPerIpEnabled) {
                return State.OK;
            }
            if (!(remoteAddress instanceof InetSocketAddress)
                    || !isLegalIpAddress(((InetSocketAddress) remoteAddress).getHostString())) {
                return State.OK;
            }
            lock.lock();
            try {
                String ip = ((InetSocketAddress) remoteAddress).getHostString();
                if (maxConnectionsLimitPerIpEnabled) {
                    CONNECTIONS.computeIfAbsent(ip, (x) -> new MutableInt(0)).increment();
                }
                if (maxConnectionsLimitEnabled) {
                    totalConnectionNum++;
                }
                if (maxConnectionsLimitEnabled && totalConnectionNum > maxConnections) {
                    log.info("Reject connect request from {}, because reached the maximum number of connections {}",
                            remoteAddress, totalConnectionNum);
                    return State.REACH_MAX_CONNECTION;
                }
                if (maxConnectionsLimitPerIpEnabled && CONNECTIONS.get(ip).getValue() > maxConnectionPerIp) {
                    log.info("Reject connect request from {}, because reached the maximum number "
                                    + "of connections per Ip {}",
                            remoteAddress, CONNECTIONS.get(ip).getValue());
                    return State.REACH_MAX_CONNECTION_PER_IP;
                }
            } catch (Exception e) {
                log.error("increase connection failed", e);
            } finally {
                lock.unlock();
            }
            return State.OK;
        }

        @Override
        public void decreaseConnection(SocketAddress remoteAddress) {
            if (!maxConnectionsLimitEnabled && !maxConnectionsLimitPerIpEnabled) {
                return;
            }
            if (!(remoteAddress instanceof InetSocketAddress)
                    || !isLegalIpAddress(((InetSocketAddress) remoteAddress).getHostString())) {
                return;
            }
            lock.lock();
            try {
                String ip = ((InetSocketAddress) remoteAddress).getHostString();
                MutableInt mutableInt = CONNECTIONS.get(ip);
                if (maxConnectionsLimitPerIpEnabled && mutableInt != null && mutableInt.decrementAndGet() <= 0) {
                    CONNECTIONS.remove(ip);
                }
                if (maxConnectionsLimitEnabled) {
                    totalConnectionNum--;
                }
            } finally {
                lock.unlock();
            }
        }

        private boolean isLegalIpAddress(String address) {
            return InetAddressUtils.isIPv4Address(address) || InetAddressUtils.isIPv6Address(address);
        }

        @VisibleForTesting
        public static int getTotalConnectionNum() {
            return totalConnectionNum;
        }

        @VisibleForTesting
        public static Map<String, MutableInt> getConnections() {
            return CONNECTIONS;
        }

    }

}


text:
package com.neulevel.epp.ext;

import org.w3c.dom.Node;

import com.neulevel.cn.CNCDNExt;
import com.neulevel.cn.CNContactCreateExt;
import com.neulevel.cn.CNContactInfoExt;
import com.neulevel.cn.CNContactUpdateExt;
import com.neulevel.epp.core.EppEntity;
import com.neulevel.epp.core.EppUtil;
import com.neulevel.epp.ext.command.EppCommandCheckLaunchRegistration;
import com.neulevel.epp.ext.command.EppCommandCreateLaunchRegistration;
import com.neulevel.epp.ext.command.EppCommandCreateSecDns;
import com.neulevel.epp.ext.command.EppCommandDeleteLaunchRegistration;
import com.neulevel.epp.ext.command.EppCommandInfoLaunchRegistration;
import com.neulevel.epp.ext.command.EppCommandUpdateLaunchRegistration;
import com.neulevel.epp.ext.command.EppCommandUpdateSecDns;
import com.neulevel.epp.ext.fee.command.EppCommandCheckFee;
import com.neulevel.epp.ext.fee.command.EppCommandCreateFee;
import com.neulevel.epp.ext.fee.command.EppCommandInfoFee;
import com.neulevel.epp.ext.fee.command.EppCommandRenewFee;
import com.neulevel.epp.ext.fee.command.EppCommandTransferFee;
import com.neulevel.epp.ext.fee.response.EppResponseCheckFee;
import com.neulevel.epp.ext.fee.response.EppResponseCreateFee;
import com.neulevel.epp.ext.fee.response.EppResponseInfoFee;
import com.neulevel.epp.ext.fee.response.EppResponseRenewFee;
import com.neulevel.epp.ext.fee.response.EppResponseTransferFee;
import com.neulevel.epp.ext.response.EppResponseDataCheckClaims;
import com.neulevel.epp.ext.response.EppResponseDataCreateLaunchRegistration;
import com.neulevel.epp.ext.response.EppResponseDataInfoLaunchRegistration;
import com.neulevel.epp.ext.response.EppResponseDataInfoSecDns;

/**
 * This EppExtension class implements EPP Extension entity.
 *
 * @author Ning Zhang ning.zhang@neustar.com
 * @version $Revision: 1.9 $ $Date: 2013/07/08 21:36:29 $
 */
abstract public class EppExtension extends EppEntity
{
	/**
	 * Converts an XML element into an EppExtension object. The
	 * caller of this method must make sure that the root node is a child node
	 * of an EPP extension tag
	 *
	 * @param root
	 *            root node for an EppExtension object in XML
	 *            format
	 *
	 * @return an EppEntity object, or null if the node is invalid
	 */
	public static EppEntity fromXML(Node root)
	{
		if (root == null)
		{
			return null;
		}

		String prefix = root.getPrefix();
		String name = root.getLocalName();

		if ((prefix == null) || (name == null))
		{
			return null;
		}

		EppExtension entity = null;

		if (prefix.equals("secDNS"))
		{
			if (name.equals("create"))
			{
				entity = (EppExtension) EppCommandCreateSecDns.fromXML(root);
				if (null != entity)
				{
					String maj_min[] = EppUtil.getDnsSecMajorMinor(root);
					if (null != maj_min)
					{
						entity.secDnsMajor = maj_min[0];
						entity.secDnsMinor = maj_min[1];
					}
				}
			} else if (name.equals("update"))
			{
				entity = (EppExtension) EppCommandUpdateSecDns.fromXML(root);
				if (null != entity)
				{
					String maj_min[] = EppUtil.getDnsSecMajorMinor(root);
					if (null != maj_min)
					{
						entity.secDnsMajor = maj_min[0];
						entity.secDnsMinor = maj_min[1];
					}
				}
			} else if (name.equals("infData"))
			{
				entity = (EppExtension) EppResponseDataInfoSecDns.fromXML(root);
				if (null != entity)
				{
					String maj_min[] = EppUtil.getDnsSecMajorMinor(root);
					if (null != maj_min)
					{
						entity.secDnsMajor = maj_min[0];
						entity.secDnsMinor = maj_min[1];
					}
				}
			}
		} else if (prefix.equals("launch"))
		{
			if (name.equals("check"))
			{
				entity = (EppExtension) EppCommandCheckLaunchRegistration
						.fromXML(root);
			} else if (name.equals("create"))
			{
				entity = (EppExtension) EppCommandCreateLaunchRegistration
						.fromXML(root);
			} else if (name.equals("update"))
			{
				entity = (EppExtension) EppCommandUpdateLaunchRegistration
						.fromXML(root);
			} else if (name.equals("delete"))
			{
				entity = (EppExtension) EppCommandDeleteLaunchRegistration
						.fromXML(root);
			} else if (name.equals("info"))
			{
				entity = (EppExtension) EppCommandInfoLaunchRegistration
						.fromXML(root);
			} else if (name.equals("infData"))
			{
				entity = (EppExtension) EppResponseDataInfoLaunchRegistration
						.fromXML(root);
			} else if (name.equals("creData"))
			{
				entity = (EppExtension) EppResponseDataCreateLaunchRegistration
						.fromXML(root);
			} else if (name.equals("chkData"))
			{
				entity = (EppExtension) EppResponseDataCheckClaims
						.fromXML(root);
			}
		} else if (prefix.equals("idn"))
		{
			if (name.equals("data"))
			{
				entity = (EppExtension) EppIDNData.fromXML(root);
			}
		} else if (prefix.equals("allocationToken"))
		{
			if (name.equals("allocationToken"))
			{
				entity = (EppExtension) EppAllocationToken.fromXML(root);
			}
		} else if (prefix.equals("fee"))
		{
			if (name.equals("info")) {
				entity = (EppExtension) EppCommandInfoFee.fromXML(root);
			} else if (name.equals("infData")) {
				entity = (EppExtension) EppResponseInfoFee.fromXML(root);
			} else if (name.equals("check")) {
				entity = (EppExtension) EppCommandCheckFee.fromXML(root);
			} else if (name.equals("chkData")){
				entity = (EppExtension) EppResponseCheckFee.fromXML(root);
			} else if (name.equals("create")) {
				entity = (EppExtension) EppCommandCreateFee.fromXML(root);
			} else if (name.equals("creData")) {
				entity = (EppExtension) EppResponseCreateFee.fromXML(root);
			} else if (name.equals("transfer")) {
				entity = (EppExtension) EppCommandTransferFee.fromXML(root);
			} else if (name.equals("trnData")) {
				entity = (EppExtension) EppResponseTransferFee.fromXML(root);
			} else if (name.equals("renew")) {
				entity = (EppExtension) EppCommandRenewFee.fromXML(root);
			} else if (name.equals("renData")) {
				entity = (EppExtension) EppResponseRenewFee.fromXML(root);
			}
		} else if (prefix.equals("changePoll") && name.equals("changeData") )
		{
			entity = (EppExtension) EppChangePollExt.fromXML(root);

		} else if (prefix.equals("cnnic-contact") && name.equals("create") )
		{
			entity = (EppExtension) CNContactCreateExt.fromXML(root);

		} else if (prefix.equals("cnnic-contact") && name.equals("infData") )
		{
			entity = (EppExtension) CNContactInfoExt.fromXML(root);

		} else if (prefix.equals("cnnic-contact") && name.equals("update") )
		{
			entity = (EppExtension) CNContactUpdateExt.fromXML(root);

		} else if (prefix.equals("cdn") && name.equals("infData") )
		{
			entity = (EppExtension) CNCDNExt.fromXML(root);

		}
		return (EppEntity) entity;
	}

	protected String secDnsMajor = "1";
	protected String secDnsMinor = "1";
}


text:
{% extends "submit/submit_base.html" %}
{# Copyright The IETF Trust 2015, All Rights Reserved #}
{% load origin %}
{% load staticfiles %}
{% load bootstrap3 %}
{% load submit_tags %}

{% block pagehead %}
  {{ block.super }}
  <link rel="stylesheet" href="{% static 'select2/select2.css' %}">
  <link rel="stylesheet" href="{% static 'select2-bootstrap-css/select2-bootstrap.min.css' %}">
{% endblock %}

{% block title %}Adjust meta-data of submitted {{ submission.name }}{% endblock %}

{% block submit_content %}
  {% origin %}
  {% bootstrap_messages %}

	  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

First two pages of {{ submission.name }}-{{ submission.rev }}

	  {{ submission|two_pages_decorated_with_errors:errors }}

	  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Adjust meta-data of submitted {{ submission.name }}

      Document

        {{ submission.name }}
        <button class="btn btn-default btn-xs pull-right" data-toggle="modal" data-target="#twopages">View first two pages</button>
        {% show_submission_files submission %}

Submission date	{{ submission.submission_date }}

      Group
      {{ submission.group|default:"Individual Submission" }}
        {% if errors.group %}
{{ errors.group }} (Note: the Secretariat will be notified of this)
{% endif %}

File size	{{ submission.file_size|filesizeformat }}

Adjust meta-data

  {% if form_errors %}

      Please fix the errors in the form below.

  {% endif %}

  <form class="idsubmit" method="post">
    {% csrf_token %}

    {% bootstrap_form edit_form %}

Submitter

    {% include "submit/submitter_form.html" %}
    {% include "submit/replaces_form.html" %}

    {% for form in author_forms %}

Author {{ forloop.counter }}

        {% bootstrap_form form %}
        <input type="hidden" name="authors-prefix" value="{{ form.prefix  }}">

    {% endfor %}

    {% buttons %}
      <input class="btn btn-default" type="button" value="Add another author" id="add-author">
      <input class="btn btn-primary" type="submit" value="Submit for manual posting">
    {% endbuttons %}
  </form>

    {% include "submit/problem-reports-footer.html" %}

{% endblock %}

{% block js %}

{% endblock %}


text:
package org.cybcode.tools.bixtractor.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import org.cybcode.tools.bixtractor.api.BiXource;
import org.cybcode.tools.bixtractor.api.BiXtractor;
import org.cybcode.tools.bixtractor.api.MonoPushParameter;
import org.cybcode.tools.bixtractor.api.XecutionContext;
import org.cybcode.tools.bixtractor.api.XpressionRegistrator;
import org.cybcode.tools.bixtractor.ops.RootXtractor;
import org.cybcode.tools.bixtractor.ops.SubroutineXtractor;
import org.cybcode.tools.bixtractor.ops.XtractorFormatter;
import org.cybcode.tools.lists.SmallListCollector;

class BiXpressionBuilder
{
	private BiXpressionBuilder() {}

	private static NodeEntry createEntry(BiXtractor<?> op, NodeEntry container, Map<BiXtractor<?>, NodeEntry> nodeMap)
	{
		NodeEntry result = nodeMap.get(op);
		if (result == null) {
			result = NodeEntryFactory.newEntry(op, container);
			nodeMap.put(op, result);
		}
		if (container != null) {
			result.addOutlet(container);
		}
		return result;
	}

	private static NodeEntry createEntry(NodeEntry entry, int paramIndex, Map<BiXtractor<?>, NodeEntry> nodeMap)
	{
		return createEntry(entry.params.get(paramIndex).getExtractor(), entry, nodeMap);
	}

	private static List<NodeEntry> leafEntries(BiXtractor<?> op)
	{
		Map<BiXtractor<?>, NodeEntry> nodeMap = new IdentityHashMap<>();
		NodeEntry entry = createEntry(op, null, nodeMap);

		Queue<NodeEntry> inQueue = new LinkedList<>();
		Map<Object, NodeEntry> leafs = new HashMap<>();
		do {
			entry.visitNode();
			int sz = entry.params.size();
			if (sz == 0) {
				Object leafKey = entry.op.getOperationToken();
				if (leafKey == null) {
					leafKey = entry.op.getClass();
				}
				NodeEntry existingEntry = leafs.get(leafKey);
				if (existingEntry != null) {
					existingEntry.addOutletsOf(entry);
				} else {
					leafs.put(leafKey, entry);
				}
				entry = inQueue.poll();
				continue;
			}

			NodeEntry nextEntry = createEntry(entry, 0, nodeMap);
			for (int i = 1; i < sz; i++) {
				inQueue.add(createEntry(entry, i, nodeMap));
			}
			entry = nextEntry;
		} while (entry != null);

		throw new UnsupportedOperationException();
//		leafs.ensureCapacity(nodeMap.size());
//		return leafs;
	}

	public static List<OpNode> flatten(BiXtractor<?> op, List<OpNode> outNodes)
	{
		List<NodeEntry> nodes = leafEntries(op);
		if (nodes.isEmpty()) return Collections.emptyList();

		int generationStartIndex = 0;
		int nextGenerationNumber = 1;

		do {
			int generationEndIndex = nodes.size();
			for (int i = generationStartIndex; i < generationEndIndex; i++) {
				NodeEntry node = nodes.get(i);
				node.pullupOutlets(nodes, nextGenerationNumber);
			}
			generationStartIndex = generationEndIndex;
			nextGenerationNumber++;
		} while (generationStartIndex < nodes.size());

		Collections.sort(nodes);

		int outSize = nodes.size();
		if (outNodes == null) {
			outNodes = new ArrayList<>(outSize);
		} else if (outNodes instanceof ArrayList) {
			((ArrayList<?>) outNodes).ensureCapacity(outSize);
		}

		new NodeEntryMapper(nodes.size()).entriesToOpNodes(nodes, outNodes);

		return outNodes;
	}

	private static class NodeEntryMapper
	{
		private final Map<BiXtractor<?>, OpNode> nodeMap;

		NodeEntryMapper(int capacity)
		{
			nodeMap = new IdentityHashMap<>(capacity);
		}

		void entriesToOpNodes(List<NodeEntry> nodes, List<OpNode> outNodes)
		{
			for (NodeEntry node : nodes) {
				OpNode opNode = nodeMap.get(node.op);
				if (opNode == null) {
					opNode = node.createOpNode();
					opNode.nodeIndex = outNodes.size();
					opNode.distanceFromRoot = node.complexityFromRoot;

					switch (node.params.size()) {
						case 0: break;
						case 1: opNode.setParameter(mapParameter(opNode, node.params.get(0), 0)); break;
						default: opNode.setParameters(mapParameters(opNode, node.params)); break;
					}

					nodeMap.put(node.op, opNode);
				}
				outNodes.add(opNode);
			}
		}

		private OpLink[] mapParameters(OpNode opNode, SmallListCollector<? extends Parameter<?>> params)
		{
			OpLink[] result = new OpLink[params.size()];
			for (int i = 0; i < result.length; i++) {
				result[i] = mapParameter(opNode, params.get(i), i);
			}
			return result;
		}

		private OpLink mapParameter(OpNode opNode, Parameter<?> param, int paramIndex)
		{
			OpNode paramSource = nodeMap.get(param.getExtractor());
			if (paramSource == null) {
				throw new IllegalArgumentException("Circular link: param=" + param);
			}
			param.setParamIndex(paramIndex, false); //TODO paramSource.isMultiValue()
			return paramSource.addOutlet(opNode, param);
		}
	}
}

class NodeEntry extends SmallListCollector<NodeEntry> implements Comparable<NodeEntry>
{
	int generationNumber;
	final int complexityFromRoot;
	final int distanceFromRoot;
	final BiXtractor<?> op;
	final SubroutineEntry parentJunction;
	final Params params;

	static class Params extends SmallListCollector<Parameter<?>> implements XpressionRegistrator
	{
		@Override public void registerParameter(Parameter<?> param) { add(param); }
	}

	public NodeEntry(BiXtractor<?> op, NodeEntry containerEntry)
	{
		this.op = op;
		this.params = new Params();

		if (containerEntry == null) {
			this.parentJunction = null;
			this.complexityFromRoot = 0;
			this.distanceFromRoot = 0;
		} else {
			this.parentJunction = containerEntry.getCurrentJunction();
			this.complexityFromRoot = containerEntry.complexityFromRoot + Math.max(1, op.getOperationComplexity());
			this.distanceFromRoot = containerEntry.distanceFromRoot + 1;
		}
	}

	public void addOutletsOf(NodeEntry entry)
	{
		for (int outletIndex = 0; outletIndex < entry.size(); outletIndex++) {
			addOutlet(entry.get(outletIndex));
		}
	}

	public OpNode createOpNode()
	{
		return new OpValueNode(op);
	}

	public void pullupOutlets(List<NodeEntry> entries, int generationNumber)
	{
		for (int i = size() - 1; i >= 0; i--) {
			NodeEntry entry = get(i);
			if (entry.generationNumber > 0) continue;
			entry.generationNumber = generationNumber;
			entries.add(entry);
		}
	}

	public void addOutlet(NodeEntry container)
	{
		this.add(container);
	}

	public boolean hasParameters()
	{
		return params.size() > 0;
	}

	public SubroutineEntry getCurrentJunction()
	{
		return parentJunction;
	}

	public BiXtractor<?> getSubroutineVar()
	{
		if (parentJunction == null) return RootXtractor.getInstance();
		return parentJunction.getSubroutineVar();
	}

	public void visitNode()
	{
		op.visit(params);
	}

	@Override public int compareTo(NodeEntry o)
	{
		if (this.generationNumber < o.generationNumber) return -1;
		if (this.generationNumber > o.generationNumber) return 1;
		if (this.complexityFromRoot < o.complexityFromRoot) return -1;
		if (this.complexityFromRoot > o.complexityFromRoot) return 1;
		return 0;
	}

	@Override public String toString()
	{
		return XtractorFormatter.nameAndTokenOf(op).toString();
	}
}

class SubroutineEntry extends NodeEntry
{
	private SubroutineVarXtractor<?>	varSource;

	public SubroutineEntry(SubroutineXtractor<?> op, NodeEntry currentEntry)
	{
		super(op, currentEntry);
	}

	public SubroutineEntry getCurrentJunction()
	{
		return this;
	}

	public BiXtractor<?> getSubroutineVar()
	{
		if (varSource == null) throw new IllegalStateException();
		return varSource;
	}
}

enum NodeEntryFactory
{
	DEFAULT {
		@Override public NodeEntry createEntry(BiXtractor<?> op, NodeEntry containerEntry) { return new NodeEntry(op, containerEntry); }
	},
	SUBROUTINE {
		@Override public SubroutineEntry createEntry(BiXtractor<?> op, NodeEntry containerEntry) { return new SubroutineEntry((SubroutineXtractor<?>) op, containerEntry); }
	},
	SOURCE {
		@Override public NodeEntry createEntry(BiXtractor<?> op, NodeEntry containerEntry)
		{
			return new NodeEntry(op, containerEntry)
			{
				@Override public OpNode createOpNode() { return new OpSourceNode((BiXource) op); }
			};
		}
	};

	protected abstract NodeEntry createEntry(BiXtractor<?> op, NodeEntry containerEntry);

	public static NodeEntry newEntry(BiXtractor<?> op, NodeEntry container)
	{
		if (op instanceof SubroutineXtractor) return SUBROUTINE.createEntry(op, container);
		if (op instanceof BiXource) return SOURCE.createEntry(op, container);
		return DEFAULT.createEntry(op, container);
	}
}

class SubroutineVarXtractor<T> implements BiXtractor<T>
{
	private final MonoPushParameter<T> p0;

	SubroutineVarXtractor(BiXtractor<? extends T> p0)
	{
		this.p0 = new MonoPushParameter<T>(p0);
	}

	@Override public void visit(XpressionRegistrator registry)
	{
		registry.registerParameter(p0);
	}

	@Override public T evaluate(XecutionContext context)
	{
		return p0.get(context);
	}

	@Override public Object getOperationToken()
	{
		return null;
	}

	@Override public int getOperationComplexity()
	{
		return COMPLEXITY_VAR;
	}

	@Override public String toString()
	{
		return "VAR" + "(" + p0.getExtractor() + ")";
		//(isRepeatable() ? "*" : "") +
	}
}


text:
package com.dazito.java.akkademy.client;

import akka.actor.AbstractActorWithStash;
import akka.japi.pf.ReceiveBuilder;
import com.dazito.java.akkademy.client.exception.ConnectionTimeoutException;
import com.dazito.java.dakkabase.messages.CheckConnected;
import com.dazito.java.dakkabase.messages.Connected;
import com.dazito.java.dakkabase.messages.GetRequest;
import scala.PartialFunction;
import scala.concurrent.ExecutionContextExecutor;
import scala.concurrent.duration.Duration;
import scala.runtime.BoxedUnit;

import java.util.concurrent.TimeUnit;

/**
 * Created by daz on 09/03/2016.
 */
public class RemoteActorProxyWihtBecome extends AbstractActorWithStash {

    private final ExecutionContextExecutor executor;

    public RemoteActorProxyWihtBecome() {

        // Schedule a message to check if we are connected, if it is not connected we escalate it.
        // This is in order to avoid stash leaks.

        executor = getContext().system().dispatcher();
        getContext().system().scheduler().scheduleOnce(Duration.create(1000, TimeUnit.MILLISECONDS), self(), new CheckConnected(), executor, null);

        receive(ReceiveBuilder
                        .match(GetRequest.class, message -> {
                            context().unbecome();
                            stash();
                        })
                        .match(Connected.class, message -> {
                            context().become(online());
                            unstash();
                        })
                        .match(CheckConnected.class, message -> {
                            throw new ConnectionTimeoutException("Connection timed out");
                        })
                        .build()
        );
    }

    private PartialFunction<Object, BoxedUnit> online () {
        return ReceiveBuilder.match(GetRequest.class, message -> processMessage(message)).build();
    }

    private void processMessage(Object message) {
        // Do something
    }
}


text:
import { createSelector } from 'reselect';
import * as deps from '../deps';

export const getMenuItemOpen = state => state.starterProTheme.menuItemOpen;
export const getCurrentMenuItems = state => state.starterProTheme.currentMenuItems;
export const getCategoriesList = state => state.starterProTheme.categoriesList;
export const getPagesList = state => state.starterProTheme.pagesList;
export const getThemeSettings = state =>
  deps.selectorCreators.getSettings('starterProTheme')(state);
export const getCategoriesStatus = state => state.starterProTheme.categoriesStatus;
export const getPagesStatus = state => state.starterProTheme.pagesStatus;
export const getStatus = createSelector(
  getCategoriesStatus,
  getPagesStatus,
  (categories, pages) => {
    if (categories === 'error' || pages === 'error') return 'error';
    else if (categories === 'fetching' || pages === 'fetching') return 'fetching';
    else if (categories === 'succeed' && pages === 'succeed') return 'succeed';
    return 'idle';
  }
);


text:
layout: photo
title: "Fox at dusk"
date: 2014-06-25 18:35
flickr: https://www.flickr.com/photos/prhayes/14334398000/
500px: https://500px.com/photo/75799135/fox-at-dusk-by-paul-hayes

exif: true
camera: "Canon EOS 500D"
lens: "Canon EF 70-200mm f/4L IS"
aperture: "ƒ/5.6"
shutter: "1/500"
iso: 400
focal: "70.0mm"

tags:
  - wildlife
  - mammal
  - fox
  - evening
  - summer
  - shortlisted
---

__Shortlisted in Outdoor Photographer of the Year 2015 (OPOTY), "[Wildlife insight](http://www.opoty.co.uk/pages/2015%2Bwinners/)" category.__

The evening light at the British Wildlife Centre was perfect, I couldn't have asked for anything better. Lying down in the grass, I angled the camera upwards to capture the warm orange fur of the fox which formed a glowing halo.


text:
package com.iyzipay.model.marketplace.onboarding.settlementtobalance.exception;

public class SubMerchantOnboardingInvalidSecretKeyException extends RuntimeException {
    public SubMerchantOnboardingInvalidSecretKeyException(String message) {
        super(message);
    }
}


text:
import React from 'react'
import { Rating } from 'shengnian-ui-react'

const RatingExampleStar = () => (
  <Rating icon='star' defaultRating={3} maxRating={4} />
)

export default RatingExampleStar


text:
Epysteme
========

Epysteme is a data analysis and machine learning package under somewhat
irregular development. The goal is to provide a uniform (functional and
object-oriented) interface to data sets of any size and many different origins
such as single files, multiple files, relational databases and web services.

Epysteme extends and glues pandas and scikit-learn together, along with a few
other packages.

Requirements
------------
- Python 3
- pandas
- numpy

.. Installation
.. ------------
.. Epysteme is conveniently available on pypi. Simply install using either::
..
..     pip install epysteme
..
.. or::
..
..     easy_install epysteme


text:
package com.cloud.model.enumeration;

public enum Event {
    AgentConnected(false, "Agent connected"),
    PingTimeout(false, "Agent is behind on ping"),
    ShutdownRequested(false, "Shutdown requested by the agent"),
    AgentDisconnected(false, "Agent disconnected"),
    HostDown(false, "Host is found to be down by the investigator"),
    Ping(false, "Ping is received from the host"),
    ManagementServerDown(false, "Management Server that the agent is connected is going down"),
    WaitedTooLong(false, "Waited too long from the agent to reconnect on its own.  Time to do HA"),
    Remove(true, "Host is removed"),
    Ready(false, "Host is ready for commands"),
    RequestAgentRebalance(false, "Request rebalance for the certain host"),
    StartAgentRebalance(false, "Start rebalance for the certain host"),
    RebalanceCompleted(false, "Host is rebalanced successfully"),
    RebalanceFailed(false, "Failed to rebalance the host"),
    Error(false, "An internal error happened");

    private final boolean isUserRequest;
    private final String comment;

    private Event(final boolean isUserRequest, final String comment) {
        this.isUserRequest = isUserRequest;
        this.comment = comment;
    }

    public String getDescription() {
        return comment;
    }

    public boolean isUserRequest() {
        return isUserRequest;
    }
}


text:
namespace swift {

/// This class manages and owns source buffers.
class SourceManager {
  llvm::SourceMgr LLVMSourceMgr;
  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FileSystem;
  unsigned CodeCompletionBufferID = 0U;
  unsigned CodeCompletionOffset;

  /// Associates buffer identifiers to buffer IDs.
  llvm::DenseMap<StringRef, unsigned> BufIdentIDMap;

  /// A cache mapping buffer identifiers to vfs Status entries.
  ///
  /// This is as much a hack to prolong the lifetime of status objects as it is
  /// to speed up stats.
  mutable llvm::DenseMap<StringRef, llvm::vfs::Status> StatusCache;

  // \c #sourceLocation directive handling.
  struct VirtualFile {
    CharSourceRange Range;
    std::string Name;
    int LineOffset;
  };
  std::map<const char *, VirtualFile> VirtualFiles;
  mutable std::pair<const char *, const VirtualFile*> CachedVFile = {nullptr, nullptr};

  Optional<unsigned> findBufferContainingLocInternal(SourceLoc Loc) const;
public:
  SourceManager(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS =
                    llvm::vfs::getRealFileSystem())
    : FileSystem(FS) {}

  llvm::SourceMgr &getLLVMSourceMgr() {
    return LLVMSourceMgr;
  }
  const llvm::SourceMgr &getLLVMSourceMgr() const {
    return LLVMSourceMgr;
  }

  void setFileSystem(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
    FileSystem = FS;
  }

  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> getFileSystem() {
    return FileSystem;
  }

  void setCodeCompletionPoint(unsigned BufferID, unsigned Offset) {
    assert(BufferID != 0U && "Buffer should be valid");

    CodeCompletionBufferID = BufferID;
    CodeCompletionOffset = Offset;
  }

  bool hasCodeCompletionBuffer() const {
    return CodeCompletionBufferID != 0U;
  }

  unsigned getCodeCompletionBufferID() const {
    return CodeCompletionBufferID;
  }

  unsigned getCodeCompletionOffset() const {
    return CodeCompletionOffset;
  }

  SourceLoc getCodeCompletionLoc() const;

  /// Returns true if \c LHS is before \c RHS in the source buffer.
  bool isBeforeInBuffer(SourceLoc LHS, SourceLoc RHS) const {
    return LHS.Value.getPointer() < RHS.Value.getPointer();
  }

  /// Returns true if range \c R contains the location \c Loc.  The location
  /// \c Loc should point at the beginning of the token.
  bool rangeContainsTokenLoc(SourceRange R, SourceLoc Loc) const {
    return Loc == R.Start || Loc == R.End ||
           (isBeforeInBuffer(R.Start, Loc) && isBeforeInBuffer(Loc, R.End));
  }

  /// Returns true if range \c Enclosing contains the range \c Inner.
  bool rangeContains(SourceRange Enclosing, SourceRange Inner) const {
    return rangeContainsTokenLoc(Enclosing, Inner.Start) &&
           rangeContainsTokenLoc(Enclosing, Inner.End);
  }

  /// Returns true if range \p R contains the code-completion location, if any.
  bool rangeContainsCodeCompletionLoc(SourceRange R) const {
    return CodeCompletionBufferID
               ? rangeContainsTokenLoc(R, getCodeCompletionLoc())
               : false;
  }

  /// Returns the buffer ID for the specified *valid* location.
  ///
  /// Because a valid source location always corresponds to a source buffer,
  /// this routine always returns a valid buffer ID.
  unsigned findBufferContainingLoc(SourceLoc Loc) const;

  /// Whether the source location is pointing to any buffer owned by the SourceManager.
  bool isOwning(SourceLoc Loc) const;

  /// Adds a memory buffer to the SourceManager, taking ownership of it.
  unsigned addNewSourceBuffer(std::unique_ptr<llvm::MemoryBuffer> Buffer);

  /// Add a \c #sourceLocation-defined virtual file region.
  ///
  /// By default, this region continues to the end of the buffer.
  ///
  /// \returns True if the new file was added, false if the file already exists.
  /// The name and line offset must match exactly in that case.
  ///
  /// \sa closeVirtualFile
  bool openVirtualFile(SourceLoc loc, StringRef name, int lineOffset);

  /// Close a \c #sourceLocation-defined virtual file region.
  void closeVirtualFile(SourceLoc end);

  /// Creates a copy of a \c MemoryBuffer and adds it to the \c SourceManager,
  /// taking ownership of the copy.
  unsigned addMemBufferCopy(llvm::MemoryBuffer *Buffer);

  /// Creates and adds a memory buffer to the \c SourceManager, taking
  /// ownership of the newly created copy.
  ///
  /// \p InputData and \p BufIdentifier are copied, so that this memory can go
  /// away as soon as this function returns.
  unsigned addMemBufferCopy(StringRef InputData, StringRef BufIdentifier = "");

  /// Returns a buffer ID for a previously added buffer with the given
  /// buffer identifier, or None if there is no such buffer.
  Optional<unsigned> getIDForBufferIdentifier(StringRef BufIdentifier);

  /// Returns the identifier for the buffer with the given ID.
  ///
  /// \p BufferID must be a valid buffer ID.
  ///
  /// This should not be used for displaying information about the \e contents
  /// of a buffer, since lines within the buffer may be marked as coming from
  /// other files using \c #sourceLocation. Use #getDisplayNameForLoc instead
  /// in that case.
  StringRef getIdentifierForBuffer(unsigned BufferID) const;

  /// Returns a SourceRange covering the entire specified buffer.
  ///
  /// Note that the start location might not point at the first token: it
  /// might point at whitespace or a comment.
  CharSourceRange getRangeForBuffer(unsigned BufferID) const;

  /// Returns the SourceLoc for the beginning of the specified buffer
  /// (at offset zero).
  ///
  /// Note that the resulting location might not point at the first token: it
  /// might point at whitespace or a comment.
  SourceLoc getLocForBufferStart(unsigned BufferID) const {
    return getRangeForBuffer(BufferID).getStart();
  }

  /// Returns the offset in bytes for the given valid source location.
  unsigned getLocOffsetInBuffer(SourceLoc Loc, unsigned BufferID) const;

  /// Returns the distance in bytes between the given valid source
  /// locations.
  unsigned getByteDistance(SourceLoc Start, SourceLoc End) const;

  /// Returns the SourceLoc for the byte offset in the specified buffer.
  SourceLoc getLocForOffset(unsigned BufferID, unsigned Offset) const {
    return getLocForBufferStart(BufferID).getAdvancedLoc(Offset);
  }

  /// Returns a buffer identifier suitable for display to the user containing
  /// the given source location.
  ///
  /// This respects \c #sourceLocation directives and the 'use-external-names'
  /// directive in VFS overlay files. If you need an on-disk file name, use
  /// #getIdentifierForBuffer instead.
  StringRef getDisplayNameForLoc(SourceLoc Loc) const;

  /// Returns the line and column represented by the given source location.
  ///
  /// If \p BufferID is provided, \p Loc must come from that source buffer.
  ///
  /// This respects \c #sourceLocation directives.
  std::pair<unsigned, unsigned>
  getPresumedLineAndColumnForLoc(SourceLoc Loc, unsigned BufferID = 0) const {
    assert(Loc.isValid());
    int LineOffset = getLineOffset(Loc);
    int l, c;
    std::tie(l, c) = LLVMSourceMgr.getLineAndColumn(Loc.Value, BufferID);
    assert(LineOffset+l > 0 && "bogus line offset");
    return { LineOffset + l, c };
  }

  /// Returns the real line and column for a source location.
  ///
  /// If \p BufferID is provided, \p Loc must come from that source buffer.
  ///
  /// This does not respect \c #sourceLocation directives.
  std::pair<unsigned, unsigned>
  getLineAndColumnInBuffer(SourceLoc Loc, unsigned BufferID = 0) const {
    assert(Loc.isValid());
    return LLVMSourceMgr.getLineAndColumn(Loc.Value, BufferID);
  }

  StringRef getEntireTextForBuffer(unsigned BufferID) const;

  StringRef extractText(CharSourceRange Range,
                        Optional<unsigned> BufferID = None) const;

  llvm::SMDiagnostic GetMessage(SourceLoc Loc, llvm::SourceMgr::DiagKind Kind,
                                const Twine &Msg,
                                ArrayRef<llvm::SMRange> Ranges,
                                ArrayRef<llvm::SMFixIt> FixIts) const;

  /// Verifies that all buffers are still valid.
  void verifyAllBuffers() const;

  /// Translate line and column pair to the offset.
  /// If the column number is the maximum unsinged int, return the offset of the end of the line.
  llvm::Optional<unsigned> resolveFromLineCol(unsigned BufferId, unsigned Line,
                                              unsigned Col) const;

  /// Translate the end position of the given line to the offset.
  llvm::Optional<unsigned> resolveOffsetForEndOfLine(unsigned BufferId,
                                                     unsigned Line) const;

  /// Get the length of the line
  llvm::Optional<unsigned> getLineLength(unsigned BufferId, unsigned Line) const;

  SourceLoc getLocForLineCol(unsigned BufferId, unsigned Line, unsigned Col) const {
    auto Offset = resolveFromLineCol(BufferId, Line, Col);
    return Offset.hasValue() ? getLocForOffset(BufferId, Offset.getValue()) :
                               SourceLoc();
  }

  std::string getLineString(unsigned BufferID, unsigned LineNumber);

  SourceLoc getLocFromExternalSource(StringRef Path, unsigned Line, unsigned Col);
private:
  const VirtualFile *getVirtualFile(SourceLoc Loc) const;
  unsigned getExternalSourceBufferId(StringRef Path);
  int getLineOffset(SourceLoc Loc) const {
    if (auto VFile = getVirtualFile(Loc))
      return VFile->LineOffset;
    else
      return 0;
  }

public:
  bool isLocInVirtualFile(SourceLoc Loc) const {
    return getVirtualFile(Loc) != nullptr;
  }
};

} // end namespace swift

#endif // SWIFT_BASIC_SOURCEMANAGER_H


text:
package net.runelite.client.plugins.corp;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import javax.inject.Inject;
import net.runelite.api.NPC;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayUtil;

class CoreOverlay extends Overlay
{
	private final CorpPlugin corpPlugin;
	private final CorpConfig config;

	@Inject
	private CoreOverlay(CorpPlugin corpPlugin, CorpConfig corpConfig)
	{
		setPosition(OverlayPosition.DYNAMIC);
		setLayer(OverlayLayer.ABOVE_SCENE);
		this.corpPlugin = corpPlugin;
		this.config = corpConfig;
	}

	@Override
	public Dimension render(Graphics2D graphics)
	{
		NPC core = corpPlugin.getCore();
		if (core != null && config.markDarkCore())
		{
			Polygon canvasTilePoly = core.getCanvasTilePoly();
			if (canvasTilePoly != null)
			{
				OverlayUtil.renderPolygon(graphics, canvasTilePoly, Color.RED.brighter());
			}
		}

		return null;
	}
}


text:
#pragma once
#include <aws/config/ConfigService_EXPORTS.h>
#include <aws/config/ConfigServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/config/model/ResourceKey.h>
#include <utility>

namespace Aws
{
namespace ConfigService
{
namespace Model
{

  /**
   */
  class AWS_CONFIGSERVICE_API StartRemediationExecutionRequest : public ConfigServiceRequest
  {
  public:
    StartRemediationExecutionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "StartRemediationExecution"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline const Aws::String& GetConfigRuleName() const{ return m_configRuleName; }

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline bool ConfigRuleNameHasBeenSet() const { return m_configRuleNameHasBeenSet; }

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline void SetConfigRuleName(const Aws::String& value) { m_configRuleNameHasBeenSet = true; m_configRuleName = value; }

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline void SetConfigRuleName(Aws::String&& value) { m_configRuleNameHasBeenSet = true; m_configRuleName = std::move(value); }

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline void SetConfigRuleName(const char* value) { m_configRuleNameHasBeenSet = true; m_configRuleName.assign(value); }

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline StartRemediationExecutionRequest& WithConfigRuleName(const Aws::String& value) { SetConfigRuleName(value); return *this;}

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline StartRemediationExecutionRequest& WithConfigRuleName(Aws::String&& value) { SetConfigRuleName(std::move(value)); return *this;}

    /**
     *
The list of names of AWS Config rules that you want to run remediation
     * execution for.

     */
    inline StartRemediationExecutionRequest& WithConfigRuleName(const char* value) { SetConfigRuleName(value); return *this;}

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline const Aws::Vector<ResourceKey>& GetResourceKeys() const{ return m_resourceKeys; }

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline bool ResourceKeysHasBeenSet() const { return m_resourceKeysHasBeenSet; }

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline void SetResourceKeys(const Aws::Vector<ResourceKey>& value) { m_resourceKeysHasBeenSet = true; m_resourceKeys = value; }

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline void SetResourceKeys(Aws::Vector<ResourceKey>&& value) { m_resourceKeysHasBeenSet = true; m_resourceKeys = std::move(value); }

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline StartRemediationExecutionRequest& WithResourceKeys(const Aws::Vector<ResourceKey>& value) { SetResourceKeys(value); return *this;}

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline StartRemediationExecutionRequest& WithResourceKeys(Aws::Vector<ResourceKey>&& value) { SetResourceKeys(std::move(value)); return *this;}

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline StartRemediationExecutionRequest& AddResourceKeys(const ResourceKey& value) { m_resourceKeysHasBeenSet = true; m_resourceKeys.push_back(value); return *this; }

    /**
     *
A list of resource keys to be processed with the current request. Each
     * element in the list consists of the resource type and resource ID.

     */
    inline StartRemediationExecutionRequest& AddResourceKeys(ResourceKey&& value) { m_resourceKeysHasBeenSet = true; m_resourceKeys.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_configRuleName;
    bool m_configRuleNameHasBeenSet;

    Aws::Vector<ResourceKey> m_resourceKeys;
    bool m_resourceKeysHasBeenSet;
  };

} // namespace Model
} // namespace ConfigService
} // namespace Aws


text:
import * as React from 'react';
import * as classNames from 'classnames';
import { IToggleSwitchProps } from './ToggleSwitch.Props';
import './ToggleSwitch.scss';
import { autobind } from '../../utilities/autobind';

export class ToggleSwitch extends React.Component<IToggleSwitchProps, any> {
    constructor(props) {
        super(props);
        this.state = {
            checked: props.checked === undefined ? false : props.checked
        };
    }

    public render(): JSX.Element {
        let {
            checked,
            onChange,
            disabled,
            className,
            label
        } = this.props;

        const isChecked = checked === undefined ? this.state.checked : checked;

        const switchClassName = classNames(
            className,
            'toggle-switch',
            {
                'checked': isChecked
            }
        );

        const slidersClassName = classNames(
            'toggle-slider'
        );
        return (

                <input type="checkbox" disabled={disabled} onChange={this._onChange} checked={isChecked} />

                {label &&
                    {label}
                }

        );
    }

    @autobind
    private _onChange(ev: React.FormEvent<HTMLInputElement>): void {
        const isChecked = (ev.target as HTMLInputElement).checked;
        if (this.props.onChange) {
            this.props.onChange(isChecked);
        }
        if (this.props.checked === undefined) {
            this.setState({ checked: isChecked });
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea intermediella Nyl.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" />
<title>Using OpenGL</title>
<link rel="stylesheet" href="doc.css" type="text/css" />

Previous: The OpenGL interfaceNext: Resizing the windowProgramming Guide » The OpenGL interface » Using OpenGL

Using OpenGL

Documentation of OpenGL and GLU are provided at the OpenGL website and
(more comprehensively) in the OpenGL Programming Guide.

Importing the package gives access to OpenGL, GLU, and all OpenGL registered
extensions.   This is sufficient for all but the most advanced uses of
OpenGL:

from pyglet.gl import *

All function names and constants are identical to the C counterparts.  For
example, the following program draws a triangle on the screen:

from pyglet.gl import *

# Direct OpenGL commands to this window.
window = pyglet.window.Window()

@window.event
def on_draw():
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glBegin(GL_TRIANGLES)
    glVertex2f(0, 0)
    glVertex2f(window.width, 0)
    glVertex2f(window.width, window.height)
    glEnd()

pyglet.app.run()

Some OpenGL functions require an array of data.  These arrays must be
constructed as <tt class="docutils literal">ctypes</tt> arrays of the correct type.  The following example
draw the same triangle as above, but uses a vertex array instead of the
immediate-mode functions.  Note the construction of the vertex array using a
one-dimensional <tt class="docutils literal">ctypes</tt> array of <tt class="docutils literal">GLfloat</tt>:

from pyglet.gl import *

window = pyglet.window.Window()

vertices = [
    0, 0,
    window.width, 0,
    window.width, window.height]
vertices_gl = (GLfloat * len(vertices))(*vertices)

glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(2, GL_FLOAT, 0, vertices_gl)

@window.event
def on_draw():
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glDrawArrays(GL_TRIANGLES, 0, len(vertices) // 2)

pyglet.app.run()

Similar array constructions can be used to create data for vertex buffer
objects, texture data, polygon stipple data and the map functions.

Previous: The OpenGL interfaceNext: Resizing the windowProgramming Guide » The OpenGL interface » Using OpenGL


text:
#include <QtWidgets/QMainWindow>
#include "ui_CryptoWorkbench.h"
#include "CodeEditor.h"

class JavascriptInterface;
class QLabel;

class CryptoWorkbench : public QMainWindow
{
	Q_OBJECT

public:
	CryptoWorkbench(QWidget *parent = 0);
	~CryptoWorkbench();

private:
	void createUi();
	QWidget* createWorkspaceEditor(QWidget* parent);
	QWidget* createCodeEditor(QWidget* parent);
	QWidget* createHelpViewer(QWidget* parent);
	void loadDefaultFiles();
	void saveActiveScript();

private slots:
	void shortcutActivatedComment();
	void shortcutActivatedUncomment();
	void openClicked();
	void saveAsClicked();
	void runClicked();
	void helpClicked();
	void codeChanged();

private:
	Ui::CryptoWorkbenchClass ui;
	JavascriptInterface* js;
	CodeEditor* workspaceEditor;
	CodeEditor* codeEditor;
	QString currentFileName;
	bool isCodeChanged;
	QWidget* helpWidget;
};

#endif // CRYPTOWORKBENCH_H


text:
using Entitas;
using Entitas.CodeGenerator;

[Input,SingleEntity]
public sealed class FoodPointsComponent : IComponent
{
    public int value;
}


text:
package com.intellij.util;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.TabbedContent;
import com.intellij.ui.content.impl.TabbedContentImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Konstantin Bulenkov
 */
public class ContentUtilEx extends ContentsUtil {
  public static void addTabbedContent(ContentManager manager, JComponent contentComponent, String groupPrefix, String tabName, boolean select) {
    addTabbedContent(manager, contentComponent, groupPrefix, tabName, select, null);
  }

  public static void addTabbedContent(ContentManager manager, JComponent contentComponent, String groupPrefix, String tabName, boolean select, @Nullable Disposable childDisposable) {
    if (PropertiesComponent.getInstance().getBoolean(TabbedContent.SPLIT_PROPERTY_PREFIX + groupPrefix)) {
      final Content content = ContentFactory.SERVICE.getInstance().createContent(contentComponent, getFullName(groupPrefix, tabName), true);
      content.putUserData(Content.TABBED_CONTENT_KEY, Boolean.TRUE);
      content.putUserData(Content.TAB_GROUP_NAME_KEY, groupPrefix);

      for (Content c : manager.getContents()) {
        if (c.getComponent() == contentComponent) {
          if (select) {
            manager.setSelectedContent(c);
          }
          return;
        }
      }
      addContent(manager, content, select);
      return;
    }

    TabbedContent tabbedContent = findTabbedContent(manager, groupPrefix);

    if (tabbedContent == null) {
      final Disposable disposable = Disposer.newDisposable();
      tabbedContent = new TabbedContentImpl(contentComponent, tabName, true, groupPrefix);
      ContentsUtil.addOrReplaceContent(manager, tabbedContent, select);
      Disposer.register(tabbedContent, disposable);
    }
    else {
      for (Pair<String, JComponent> tab : new ArrayList<Pair<String, JComponent>>(tabbedContent.getTabs())) {
        if (Comparing.equal(tab.second, contentComponent)) {
          tabbedContent.removeContent(tab.second);
        }
      }
      if (select) {
        manager.setSelectedContent(tabbedContent, true, true);
      }
      tabbedContent.addContent(contentComponent, tabName, true);
    }

    if (childDisposable != null) {
      Disposer.register(tabbedContent, childDisposable);
    }
  }

  @Nullable
  public static TabbedContent findTabbedContent(ContentManager manager, String groupPrefix) {
    TabbedContent tabbedContent = null;
    for (Content content : manager.getContents()) {
      if (content instanceof TabbedContent && content.getTabName().startsWith(getFullPrefix(groupPrefix))) {
        tabbedContent = (TabbedContent)content;
        break;
      }
    }
    return tabbedContent;
  }

  @NotNull
  public static String getFullName(@NotNull String groupPrefix, @NotNull String tabName) {
    return getFullPrefix(groupPrefix) + tabName;
  }

  @NotNull
  private static String getFullPrefix(@NotNull String groupPrefix) {
    return groupPrefix + ": ";
  }

  /**
   * Searches through all {@link Content simple} and {@link TabbedContent tabbed} contents of the given ContentManager,
   * and selects the one which holds the specified {@code contentComponent}.
   *
   * @return true if the necessary content was found (and thus selected) among content components of the given ContentManager.
   */
  public static boolean selectContent(@NotNull ContentManager manager, @NotNull final JComponent contentComponent, boolean requestFocus) {
    for (Content content : manager.getContents()) {
      if (content instanceof TabbedContentImpl) {
        boolean found = ((TabbedContentImpl)content).findAndSelectContent(contentComponent);
        if (found) {
          manager.setSelectedContent(content, requestFocus);
          return true;
        }
      }
      else if (Comparing.equal(content.getComponent(), contentComponent)) {
        manager.setSelectedContent(content, requestFocus);
        return true;
      }
    }
    return false;
  }

  /**
   * Searches through all {@link Content simple} and {@link TabbedContent tabbed} contents of the given ContentManager,
   * trying to find the first one which matches the given condition.
   */
  @Nullable
  public static JComponent findContentComponent(@NotNull ContentManager manager, @NotNull Condition<JComponent> condition) {
    for (Content content : manager.getContents()) {
      if (content instanceof TabbedContentImpl) {
        List<Pair<String, JComponent>> tabs = ((TabbedContentImpl)content).getTabs();
        for (Pair<String, JComponent> tab : tabs) {
          if (condition.value(tab.second)) {
            return tab.second;
          }
        }
      }
      else if (condition.value(content.getComponent())) {
        return content.getComponent();
      }
    }
    return null;
  }

  public static int getSelectedTab(@NotNull TabbedContent content) {
    final JComponent current = content.getComponent();
    int index = 0;
    for (Pair<String,JComponent> tab : content.getTabs()) {
      if (tab.second == current) {
        return index;
      }
      index++;
    }
    return -1;
  }
}


text:
/*
 * null
 *
 * [FhirComposite("ConditionEvidenceComponent")]
 * [Serializable]
 */

#import "FHIRElement.h"

#import "FHIRCondition.h"

@class FHIRCodeableConcept;
@class FHIRResource;

@interface FHIRConditionEvidenceComponent : FHIRElement

/*
 * Manifestation/symptom
 */
@property (nonatomic, strong) FHIRCodeableConcept *code;

/*
 * Supporting information found elsewhere
 */
@property (nonatomic, strong) NSArray/*<ResourceReference>*/ *detail;

- (FHIRErrorList *)validate;

@end


text:
{-# Language CPP #-}

module HsImport.PrettyPrint
   ( prettyPrint
   ) where

import qualified Language.Haskell.Exts as HS

#if __GLASGOW_HASKELL__ < 710
import Data.Monoid (mconcat)
#endif

prettyPrint :: HS.ImportDecl -> String
prettyPrint importDecl =
   -- remove newlines from pretty printed ImportDecl
   case lines $ HS.prettyPrint importDecl of
        (fst : []  ) -> fst
        (fst : rest) -> mconcat $ fst : (map (' ' :) . map (dropWhile (== ' ')) $ rest)
        _            -> ""


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is subject to the terms and conditions defined in the
files 'LICENSE' and 'NOTICE', which are part of this source
code package.
-->

<forms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/widget-form.xsd">
    <form name="FindCatalog" type="single" target="FindCatalog" title="" default-map-name="catalog"
        header-row-style="header-row" > <!-- orig: default-table-style=-style="basic-table" -->
        <field name="prodCatalogId" title="${uiLabelMap.ProdCatalogId}"><text-find/></field>
        <field name="catalogName"><text-find/></field>
        <field name="submitAction" title="${uiLabelMap.CommonFind}" widget-style="${styles.link_run_sys} ${styles.action_find}">
            <submit button-type="button"/>
        </field>
    </form>

    <form name="ListCatalog" list-name="listIt" target="" title="" type="list" paginate-target="FindCatalog"
        odd-row-style="alternate-row" header-row-style="header-row-2"> <!-- orig: default-table-style=-style="basic-table hover-bar" -->
        <actions>
            <set field="entityName" value="ProdCatalog"/>
            <set field="parameters.sortField" from-field="parameters.sortField" default-value="+catalogName"/>
            <service service-name="performFind" result-map="result" result-map-list="listIt">
                <field-map field-name="inputFields" from-field="parameters"/>
                <field-map field-name="entityName" from-field="entityName"/>
                <field-map field-name="orderBy" from-field="parameters.sortField"/>
                <field-map field-name="viewIndex" from-field="viewIndex"/>
                <field-map field-name="viewSize" from-field="viewSize"/>
                <field-map field-name="noConditionFind" value="Y"/>
            </service>
        </actions>
        <field name="prodCatalogId" sort-field="true" widget-style="${styles.link_nav_info_id}">
            <hyperlink also-hidden="false" description="${prodCatalogId}" target="EditCatalog">
                <parameter param-name="prodCatalogId"/>
            </hyperlink>
        </field>

        <field name="prodCatalogId" sort-field="true" widget-style="${styles.link_nav_info_id}">
            <hyperlink target="EditProdCatalog?prodCatalogId=${prodCatalogId}" description="${prodCatalogId}"></hyperlink>
        </field>
        <field name="catalogName" sort-field="true"><display/></field>
        <field name="useQuickAdd" title="${uiLabelMap.ProductUseQuickAdd}" sort-field="true"><display/></field>
    </form>

    <form name="EditProdCatalog" type="single" target="updateProdCatalog" title="" default-map-name="prodCatalog"
        header-row-style="header-row" default-entity-name="ProdCatalog"> <!-- orig: default-table-style=-style="basic-table" -->

        <alt-target use-when="prodCatalog==null" target="createProdCatalog"/>

        <field use-when="prodCatalog!=null" name="prodCatalogId" title="${uiLabelMap.ProductCatalogId}" tooltip="${uiLabelMap.ProductNotModificationRecreatingProductCatalog}."><display/></field>
        <field use-when="prodCatalog==null&&prodCatalogId!=null" name="prodCatalogId" title="${uiLabelMap.ProductCatalogId}" tooltip="${uiLabelMap.ProductCouldNotFindProductCatalogWithId} [${prodCatalogId}]"><text size="20" maxlength="20"/></field>
        <!-- this to be taken care of with auto-fields-service as soon as it uses entity field info too -->
        <field use-when="prodCatalog==null&&prodCatalogId==null" name="prodCatalogId" title="${uiLabelMap.ProductCatalogId}"><text size="20" maxlength="20"/></field>

        <field name="catalogName" position="2"><text size="30" maxlength="60"/></field>
        <field name="styleSheet" title="${uiLabelMap.ProductStyleSheet}"><text size="60" maxlength="250"/></field>
        <field name="headerLogo" title="${uiLabelMap.ProductHeaderLogo}"><text size="60" maxlength="250"/></field>
        <field name="contentPathPrefix" title="${uiLabelMap.ProductContentPathPrefix}" tooltip="${uiLabelMap.ProductPrependedImageContentPaths}"><text size="60" maxlength="250"/></field>
        <field name="templatePathPrefix" title="${uiLabelMap.ProductTemplatePathPrefix}" tooltip="${uiLabelMap.ProductPrependedTemplatePaths}"><text size="60" maxlength="250"/></field>

        <field name="useQuickAdd" title="${uiLabelMap.ProductUseQuickAdd}">
            <drop-down allow-empty="false" no-current-selected-key="Y"><option key="Y" description="${uiLabelMap.CommonY}"/><option key="N" description="${uiLabelMap.CommonN}"/></drop-down>
        </field>
        <field name="viewAllowPermReqd" title="${uiLabelMap.ProductCategoryViewAllowPermReqd}">
            <drop-down allow-empty="false" no-current-selected-key="N"><option key="Y" description="${uiLabelMap.CommonY}"/><option key="N" description="${uiLabelMap.CommonN}"/></drop-down>
        </field>
        <field name="purchaseAllowPermReqd" title="${uiLabelMap.ProductCategoryPurchaseAllowPermReqd}" position="2">
            <drop-down allow-empty="false" no-current-selected-key="N"><option key="Y" description="${uiLabelMap.CommonY}"/><option key="N" description="${uiLabelMap.CommonN}"/></drop-down>
        </field>

        <field name="submitAction" title="${uiLabelMap.CommonUpdate}" widget-style="${styles.link_run_sys} ${styles.action_update}"><submit button-type="button"/></field>
    </form>

    <form name="AddProdCatalogToParty" type="single" target="addProdCatalogToParty" title=""
        header-row-style="header-row"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="addProdCatalogToParty"/>
        <field name="prodCatalogId" map-name="prodCatalog"><hidden/></field>
        <field name="partyId" title="${uiLabelMap.PartyPartyId}"><lookup target-form-name="LookupPartyName"></lookup></field>
        <field name="roleTypeId" title="${uiLabelMap.PartyRole}">
            <drop-down no-current-selected-key="_NA_">
                <entity-options entity-name="RoleType" description="${description}">
                    <entity-order-by field-name="description"/>
                </entity-options>
            </drop-down>
        </field>
        <field name="submitAction" title="${uiLabelMap.CommonAdd}" widget-style="${styles.link_run_sys} ${styles.action_add}"><submit button-type="button"/></field>
    </form>

    <form name="UpdateProdCatalogToParty" type="list" target="updateProdCatalogToParty" title="" list-name="prodCatalogRoleList"
        odd-row-style="alternate-row"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="updateProdCatalogToParty"/>
        <field name="prodCatalogId"><hidden/></field>
        <!-- three possibilities for the Party: person, partyGroup, neither... just print everything and if it's empty, no biggie -->
        <field name="partyId" title="${uiLabelMap.PartyParty}">
            <display-entity entity-name="PartyNameView" description="${personalTitle} ${firstName} ${middleName} ${lastName} ${suffix} ${groupName}" also-hidden="true" cache="false">
                <sub-hyperlink target-type="inter-app" link-style="${styles.link_nav_info_id}" target="/partymgr/control/viewprofile" description="${partyId}">
                    <parameter param-name="party_id" from-field="partyId"/>
                </sub-hyperlink>
            </display-entity>
        </field>
        <field name="roleTypeId" title="${uiLabelMap.PartyRole}"><display-entity entity-name="RoleType"/></field>
        <field name="fromDate" title="${uiLabelMap.CommonFrom}"><display/></field>
        <field name="thruDate" title="${uiLabelMap.CommonThru}"></field>
        <field name="submitAction" title="${uiLabelMap.CommonUpdate}" widget-style="${styles.link_run_sys} ${styles.action_update}"><submit button-type="button"/></field>
        <field name="deleteAction" title=" " widget-style="${styles.link_run_sys} ${styles.action_remove}">
            <hyperlink target="removeProdCatalogFromParty" description="${uiLabelMap.CommonDelete}" also-hidden="false">
              <parameter param-name="prodCatalogId"/>
              <parameter param-name="partyId"/>
              <parameter param-name="roleTypeId"/>
              <parameter param-name="fromDate"/>
            </hyperlink>
        </field>
    </form>
    <form name="CreateProductStoreCatalog" type="single" target="createProdCatalogStore" title=""
        header-row-style="header-row"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="createProductStoreCatalog"/>
        <field name="prodCatalogId" map-name="prodCatalog"><hidden/></field>
        <field name="productStoreId" title="${uiLabelMap.ProductStore}">
            <drop-down>
                <entity-options entity-name="ProductStore" description="${storeName}">
                    <entity-order-by field-name="storeName"/>
                </entity-options>
            </drop-down>
        </field>
        <field name="submitAction" title="${uiLabelMap.CommonAdd}" widget-style="${styles.link_run_sys} ${styles.action_add}"><submit button-type="button"/></field>
    </form>
    <form name="UpdateProductStoreCatalog" type="list" target="updateProdCatalogStore" title="" list-name="productStoreCatalogList"
        odd-row-style="alternate-row"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="updateProductStoreCatalog"/>
        <field name="prodCatalogId"><hidden/></field>
        <field name="productStoreId" title="${uiLabelMap.ProductStoreId}">
            <display-entity entity-name="ProductStore" description="${storeName}" also-hidden="true" cache="true">
                <sub-hyperlink link-style="${styles.link_nav_info_id}" target="EditProductStore" description="${productStoreId}">
                    <parameter param-name="productStoreId"/>
                </sub-hyperlink>
            </display-entity>
        </field>
        <field name="fromDate" title="${uiLabelMap.CommonFrom}"><display/></field>
        <field name="thruDate" title="${uiLabelMap.CommonThru}"></field>
        <field name="submitAction" title="${uiLabelMap.CommonUpdate}" widget-style="${styles.link_run_sys} ${styles.action_update}"><submit button-type="button"/></field>
        <field name="deleteAction" title=" " widget-style="${styles.link_run_sys} ${styles.action_remove}">
            <hyperlink target="deleteProdCatalogStore" description="${uiLabelMap.CommonDelete}" also-hidden="false">
              <parameter param-name="prodCatalogId"/>
              <parameter param-name="productStoreId"/>
              <parameter param-name="fromDate"/>
            </hyperlink>
        </field>
    </form>
    <form name="EditProdCatalogCategories" type="list" target="updateProductCategoryToProdCatalog" title="" list-name="prodCatalogCategories"
        odd-row-style="alternate-row" paginate-target="EditProdCatalogCategories"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="updateProductCategoryToProdCatalog"/>
        <field name="prodCatalogId"><hidden/></field>
        <field name="productCategoryId" title="${uiLabelMap.ProductCategoryId}">
            <display-entity entity-name="ProductCategory" description="${description}" also-hidden="true" cache="true">
                <sub-hyperlink link-style="${styles.link_nav_info_id}" target="EditCategory" description="${productCategoryId}">
                    <parameter param-name="productCategoryId"/>
                </sub-hyperlink>
            </display-entity>
        </field>
        <field name="prodCatalogCategoryTypeId" title="${uiLabelMap.ProductCatalogCategoryType}"><display-entity entity-name="ProdCatalogCategoryType" also-hidden="true" cache="true"/></field>
        <field name="fromDate" title="${uiLabelMap.CommonFrom}"><display/></field>
        <field name="thruDate" title="${uiLabelMap.CommonThru}"></field>
        <field name="sequenceNum" title="${uiLabelMap.CommonSequenceNum}"></field>
        <field name="deleteAction" title=" " widget-style="${styles.link_run_sys} ${styles.action_remove}">
            <hyperlink target="removeProductCategoryFromProdCatalog" description="${uiLabelMap.CommonDelete}" also-hidden="false">
              <parameter param-name="prodCatalogId"/>
              <parameter param-name="productCategoryId"/>
              <parameter param-name="partyId"/>
              <parameter param-name="fromDate"/>
              <parameter param-name="prodCatalogCategoryTypeId"/>
            </hyperlink>
        </field>
        <field name="makeTopAction" title=" " widget-style="${styles.link_run_session} ${styles.action_update}">
            <hyperlink target="EditCategory" description="${uiLabelMap.ProductMakeTop}" also-hidden="false">
                <parameter param-name="CATALOG_TOP_CATEGORY" from-field="productCategoryId"/>
                <parameter param-name="productCategoryId"/>
            </hyperlink>
        </field>
        <field name="submitAction" title="${uiLabelMap.CommonUpdate}" widget-style="${styles.link_run_sys} ${styles.action_update}"><submit button-type="button"/></field>
    </form>
    <form name="addProductCategoryToProdCatalog" type="single" target="addProductCategoryToProdCatalog" title=""
        header-row-style="header-row"> <!-- orig: default-table-style=-style="basic-table" -->
        <auto-fields-service service-name="addProductCategoryToProdCatalog"/>
        <field name="prodCatalogId"><hidden/></field>
        <field name="productCategoryId" title="${uiLabelMap.ProductCategoryId}"><lookup target-form-name="LookupProductCategory"></lookup></field>
        <field name="prodCatalogCategoryTypeId" title="${uiLabelMap.ProductCatalogCategoryType}">
            <drop-down>
                <entity-options entity-name="ProdCatalogCategoryType" description="${description}">
                    <entity-order-by field-name="description"/>
                </entity-options>
            </drop-down>
        </field>
        <field name="fromDate" title="${uiLabelMap.CommonFrom}"/>
        <field name="thruDate" title="${uiLabelMap.CommonThru}"/>
        <field name="sequenceNum" title="${uiLabelMap.CommonSequenceNum}"/>
        <field name="submitAction" title="${uiLabelMap.CommonAdd}" widget-style="${styles.link_run_sys} ${styles.action_add}"><submit button-type="button"/></field>
    </form>
</forms>


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { TasksService } from './tasks.service';

describe('TasksService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TasksService]
    });
  });

  it('should ...', inject([TasksService], (service: TasksService) => {
    expect(service).toBeTruthy();
  }));
});


text:
.PHONY: install
.PHONY: compile

compile:
	xbuild src/abanu.sln


text:
package ustc.maomao.patterns.factorymethod;

import ustc.maomao.patterns.support.PatternTester;

public class FactoryMethodTester implements PatternTester{

	/* (non-Javadoc)
	 * @see ustc.maomao.patterns.support.PatternTester#test()
	 */
	@Override
	public void test() {
		String fileName="test";
		DocumentCreator dc=new PdfDocumentCreator();
		dc.exportDocument(fileName);
	}

}