text:
#include "thingdef.h"
#include "actor.h"
#include "d_player.h"
#include "p_effect.h"
#include "autosegs.h"

static TArray<FPropertyInfo*> properties;
static TArray<AFuncDesc> AFTable;
static TArray<FVariableInfo*> variables;

//==========================================================================
//
// List of all flags
//
//==========================================================================

// [RH] Keep GCC quiet by not using offsetof on Actor types.
#define DEFINE_FLAG(prefix, name, type, variable) { prefix##_##name, #name, (int)(size_t)&((type*)1)->variable - 1, sizeof(((type *)0)->variable) }
#define DEFINE_FLAG2(symbol, name, type, variable) { symbol, #name, (int)(size_t)&((type*)1)->variable - 1, sizeof(((type *)0)->variable) }
#define DEFINE_DEPRECATED_FLAG(name) { DEPF_##name, #name, -1, 0 }
#define DEFINE_DUMMY_FLAG(name) { DEPF_UNUSED, #name, -1, 0 }

static FFlagDef ActorFlagDefs[]=
{
	DEFINE_FLAG(MF, PICKUP, APlayerPawn, flags),
	DEFINE_FLAG(MF, SPECIAL, APlayerPawn, flags),
	DEFINE_FLAG(MF, SOLID, AActor, flags),
	DEFINE_FLAG(MF, SHOOTABLE, AActor, flags),
	DEFINE_FLAG(MF, NOSECTOR, AActor, flags),
	DEFINE_FLAG(MF, NOBLOCKMAP, AActor, flags),
	DEFINE_FLAG(MF, AMBUSH, AActor, flags),
	DEFINE_FLAG(MF, JUSTHIT, AActor, flags),
	DEFINE_FLAG(MF, JUSTATTACKED, AActor, flags),
	DEFINE_FLAG(MF, SPAWNCEILING, AActor, flags),
	DEFINE_FLAG(MF, NOGRAVITY, AActor, flags),
	DEFINE_FLAG(MF, DROPOFF, AActor, flags),
	DEFINE_FLAG(MF, NOCLIP, AActor, flags),
	DEFINE_FLAG(MF, FLOAT, AActor, flags),
	DEFINE_FLAG(MF, TELEPORT, AActor, flags),
	DEFINE_FLAG(MF, MISSILE, AActor, flags),
	DEFINE_FLAG(MF, DROPPED, AActor, flags),
	DEFINE_FLAG(MF, SHADOW, AActor, flags),
	DEFINE_FLAG(MF, NOBLOOD, AActor, flags),
	DEFINE_FLAG(MF, CORPSE, AActor, flags),
	DEFINE_FLAG(MF, INFLOAT, AActor, flags),
	DEFINE_FLAG(MF, COUNTKILL, AActor, flags),
	DEFINE_FLAG(MF, COUNTITEM, AActor, flags),
	DEFINE_FLAG(MF, SKULLFLY, AActor, flags),
	DEFINE_FLAG(MF, NOTDMATCH, AActor, flags),
	DEFINE_FLAG(MF, SPAWNSOUNDSOURCE, AActor, flags),
	DEFINE_FLAG(MF, FRIENDLY, AActor, flags),
	DEFINE_FLAG(MF, NOLIFTDROP, AActor, flags),
	DEFINE_FLAG(MF, STEALTH, AActor, flags),
	DEFINE_FLAG(MF, ICECORPSE, AActor, flags),

	DEFINE_FLAG(MF2, DONTREFLECT, AActor, flags2),
	DEFINE_FLAG(MF2, WINDTHRUST, AActor, flags2),
	DEFINE_FLAG(MF2, DONTSEEKINVISIBLE, AActor, flags2),
	DEFINE_FLAG(MF2, BLASTED, AActor, flags2),
	DEFINE_FLAG(MF2, FLOORCLIP, AActor, flags2),
	DEFINE_FLAG(MF2, SPAWNFLOAT, AActor, flags2),
	DEFINE_FLAG(MF2, NOTELEPORT, AActor, flags2),
	DEFINE_FLAG2(MF2_RIP, RIPPER, AActor, flags2),
	DEFINE_FLAG(MF2, PUSHABLE, AActor, flags2),
	DEFINE_FLAG2(MF2_SLIDE, SLIDESONWALLS, AActor, flags2),
	DEFINE_FLAG2(MF2_PASSMOBJ, CANPASS, AActor, flags2),
	DEFINE_FLAG(MF2, CANNOTPUSH, AActor, flags2),
	DEFINE_FLAG(MF2, THRUGHOST, AActor, flags2),
	DEFINE_FLAG(MF2, BOSS, AActor, flags2),
	DEFINE_FLAG2(MF2_NODMGTHRUST, NODAMAGETHRUST, AActor, flags2),
	DEFINE_FLAG(MF2, DONTTRANSLATE, AActor, flags2),
	DEFINE_FLAG(MF2, TELESTOMP, AActor, flags2),
	DEFINE_FLAG(MF2, FLOATBOB, AActor, flags2),
	DEFINE_FLAG(MF2, THRUACTORS, AActor, flags2),
	DEFINE_FLAG2(MF2_IMPACT, ACTIVATEIMPACT, AActor, flags2),
	DEFINE_FLAG2(MF2_PUSHWALL, CANPUSHWALLS, AActor, flags2),
	DEFINE_FLAG2(MF2_MCROSS, ACTIVATEMCROSS, AActor, flags2),
	DEFINE_FLAG2(MF2_PCROSS, ACTIVATEPCROSS, AActor, flags2),
	DEFINE_FLAG(MF2, CANTLEAVEFLOORPIC, AActor, flags2),
	DEFINE_FLAG(MF2, NONSHOOTABLE, AActor, flags2),
	DEFINE_FLAG(MF2, INVULNERABLE, AActor, flags2),
	DEFINE_FLAG(MF2, DORMANT, AActor, flags2),
	DEFINE_FLAG(MF2, SEEKERMISSILE, AActor, flags2),
	DEFINE_FLAG(MF2, REFLECTIVE, AActor, flags2),

	DEFINE_FLAG(MF3, FLOORHUGGER, AActor, flags3),
	DEFINE_FLAG(MF3, CEILINGHUGGER, AActor, flags3),
	DEFINE_FLAG(MF3, NORADIUSDMG, AActor, flags3),
	DEFINE_FLAG(MF3, GHOST, AActor, flags3),
	DEFINE_FLAG(MF3, SPECIALFLOORCLIP, AActor, flags3),
	DEFINE_FLAG(MF3, ALWAYSPUFF, AActor, flags3),
	DEFINE_FLAG(MF3, DONTSPLASH, AActor, flags3),
	DEFINE_FLAG(MF3, DONTOVERLAP, AActor, flags3),
	DEFINE_FLAG(MF3, DONTMORPH, AActor, flags3),
	DEFINE_FLAG(MF3, DONTSQUASH, AActor, flags3),
	DEFINE_FLAG(MF3, EXPLOCOUNT, AActor, flags3),
	DEFINE_FLAG(MF3, FULLVOLACTIVE, AActor, flags3),
	DEFINE_FLAG(MF3, ISMONSTER, AActor, flags3),
	DEFINE_FLAG(MF3, SKYEXPLODE, AActor, flags3),
	DEFINE_FLAG(MF3, STAYMORPHED, AActor, flags3),
	DEFINE_FLAG(MF3, DONTBLAST, AActor, flags3),
	DEFINE_FLAG(MF3, CANBLAST, AActor, flags3),
	DEFINE_FLAG(MF3, NOTARGET, AActor, flags3),
	DEFINE_FLAG(MF3, DONTGIB, AActor, flags3),
	DEFINE_FLAG(MF3, NOBLOCKMONST, AActor, flags3),
	DEFINE_FLAG(MF3, FULLVOLDEATH, AActor, flags3),
	DEFINE_FLAG(MF3, AVOIDMELEE, AActor, flags3),
	DEFINE_FLAG(MF3, SCREENSEEKER, AActor, flags3),
	DEFINE_FLAG(MF3, FOILINVUL, AActor, flags3),
	DEFINE_FLAG(MF3, NOTELEOTHER, AActor, flags3),
	DEFINE_FLAG(MF3, BLOODLESSIMPACT, AActor, flags3),
	DEFINE_FLAG(MF3, NOEXPLODEFLOOR, AActor, flags3),
	DEFINE_FLAG(MF3, PUFFONACTORS, AActor, flags3),

	DEFINE_FLAG(MF4, QUICKTORETALIATE, AActor, flags4),
	DEFINE_FLAG(MF4, NOICEDEATH, AActor, flags4),
	DEFINE_FLAG(MF4, RANDOMIZE, AActor, flags4),
	DEFINE_FLAG(MF4, FIXMAPTHINGPOS , AActor, flags4),
	DEFINE_FLAG(MF4, ACTLIKEBRIDGE, AActor, flags4),
	DEFINE_FLAG(MF4, STRIFEDAMAGE, AActor, flags4),
	DEFINE_FLAG(MF4, CANUSEWALLS, AActor, flags4),
	DEFINE_FLAG(MF4, MISSILEMORE, AActor, flags4),
	DEFINE_FLAG(MF4, MISSILEEVENMORE, AActor, flags4),
	DEFINE_FLAG(MF4, FORCERADIUSDMG, AActor, flags4),
	DEFINE_FLAG(MF4, DONTFALL, AActor, flags4),
	DEFINE_FLAG(MF4, SEESDAGGERS, AActor, flags4),
	DEFINE_FLAG(MF4, INCOMBAT, AActor, flags4),
	DEFINE_FLAG(MF4, LOOKALLAROUND, AActor, flags4),
	DEFINE_FLAG(MF4, STANDSTILL, AActor, flags4),
	DEFINE_FLAG(MF4, SPECTRAL, AActor, flags4),
	DEFINE_FLAG(MF4, NOSPLASHALERT, AActor, flags4),
	DEFINE_FLAG(MF4, SYNCHRONIZED, AActor, flags4),
	DEFINE_FLAG(MF4, NOTARGETSWITCH, AActor, flags4),
	DEFINE_FLAG(MF4, DONTHARMCLASS, AActor, flags4),
	DEFINE_FLAG2(MF4_DONTHARMCLASS, DONTHURTSPECIES, AActor, flags4), // Deprecated name as an alias
	DEFINE_FLAG(MF4, SHIELDREFLECT, AActor, flags4),
	DEFINE_FLAG(MF4, DEFLECT, AActor, flags4),
	DEFINE_FLAG(MF4, ALLOWPARTICLES, AActor, flags4),
	DEFINE_FLAG(MF4, EXTREMEDEATH, AActor, flags4),
	DEFINE_FLAG(MF4, NOEXTREMEDEATH, AActor, flags4),
	DEFINE_FLAG(MF4, FRIGHTENED, AActor, flags4),
	DEFINE_FLAG(MF4, NOSKIN, AActor, flags4),
	DEFINE_FLAG(MF4, BOSSDEATH, AActor, flags4),

	DEFINE_FLAG(MF5, DONTDRAIN, AActor, flags5),
	DEFINE_FLAG(MF5, NODROPOFF, AActor, flags5),
	DEFINE_FLAG(MF5, NOFORWARDFALL, AActor, flags5),
	DEFINE_FLAG(MF5, COUNTSECRET, AActor, flags5),
	DEFINE_FLAG(MF5, NODAMAGE, AActor, flags5),
	DEFINE_FLAG(MF5, BLOODSPLATTER, AActor, flags5),
	DEFINE_FLAG(MF5, OLDRADIUSDMG, AActor, flags5),
	DEFINE_FLAG(MF5, DEHEXPLOSION, AActor, flags5),
	DEFINE_FLAG(MF5, PIERCEARMOR, AActor, flags5),
	DEFINE_FLAG(MF5, NOBLOODDECALS, AActor, flags5),
	DEFINE_FLAG(MF5, USESPECIAL, AActor, flags5),
	DEFINE_FLAG(MF5, NOPAIN, AActor, flags5),
	DEFINE_FLAG(MF5, ALWAYSFAST, AActor, flags5),
	DEFINE_FLAG(MF5, NEVERFAST, AActor, flags5),
	DEFINE_FLAG(MF5, ALWAYSRESPAWN, AActor, flags5),
	DEFINE_FLAG(MF5, NEVERRESPAWN, AActor, flags5),
	DEFINE_FLAG(MF5, DONTRIP, AActor, flags5),
	DEFINE_FLAG(MF5, NOINFIGHTING, AActor, flags5),
	DEFINE_FLAG(MF5, NOINTERACTION, AActor, flags5),
	DEFINE_FLAG(MF5, NOTIMEFREEZE, AActor, flags5),
	DEFINE_FLAG(MF5, PUFFGETSOWNER, AActor, flags5), // [BB] added PUFFGETSOWNER
	DEFINE_FLAG(MF5, SPECIALFIREDAMAGE, AActor, flags5),
	DEFINE_FLAG(MF5, SUMMONEDMONSTER, AActor, flags5),
	DEFINE_FLAG(MF5, NOVERTICALMELEERANGE, AActor, flags5),
	DEFINE_FLAG(MF5, BRIGHT, AActor, flags5),
	DEFINE_FLAG(MF5, CANTSEEK, AActor, flags5),
	DEFINE_FLAG(MF5, PAINLESS, AActor, flags5),
	DEFINE_FLAG(MF5, MOVEWITHSECTOR, AActor, flags5),

	DEFINE_FLAG(MF6, NOBOSSRIP, AActor, flags6),
	DEFINE_FLAG(MF6, THRUSPECIES, AActor, flags6),
	DEFINE_FLAG(MF6, MTHRUSPECIES, AActor, flags6),
	DEFINE_FLAG(MF6, FORCEPAIN, AActor, flags6),
	DEFINE_FLAG(MF6, NOFEAR, AActor, flags6),
	DEFINE_FLAG(MF6, BUMPSPECIAL, AActor, flags6),
	DEFINE_FLAG(MF6, DONTHARMSPECIES, AActor, flags6),
	DEFINE_FLAG(MF6, STEPMISSILE, AActor, flags6),
	DEFINE_FLAG(MF6, NOTELEFRAG, AActor, flags6),
	DEFINE_FLAG(MF6, TOUCHY, AActor, flags6),
	DEFINE_FLAG(MF6, CANJUMP, AActor, flags6),
	DEFINE_FLAG(MF6, JUMPDOWN, AActor, flags6),
	DEFINE_FLAG(MF6, VULNERABLE, AActor, flags6),
	DEFINE_FLAG(MF6, NOTRIGGER, AActor, flags6),
	DEFINE_FLAG(MF6, ADDITIVEPOISONDAMAGE, AActor, flags6),
	DEFINE_FLAG(MF6, ADDITIVEPOISONDURATION, AActor, flags6),
	DEFINE_FLAG(MF6, BLOCKEDBYSOLIDACTORS, AActor, flags6),
	DEFINE_FLAG(MF6, NOMENU, AActor, flags6),
	DEFINE_FLAG(MF6, SEEINVISIBLE, AActor, flags6),
	DEFINE_FLAG(MF6, DONTCORPSE, AActor, flags6),
	DEFINE_FLAG(MF6, DOHARMSPECIES, AActor, flags6),
	DEFINE_FLAG(MF6, POISONALWAYS, AActor, flags6),
	DEFINE_FLAG(MF6, NOTAUTOAIMED, AActor, flags6),
	DEFINE_FLAG(MF6, NOTONAUTOMAP, AActor, flags6),
	DEFINE_FLAG(MF6, RELATIVETOFLOOR, AActor, flags6),

	DEFINE_FLAG(MF7, NEVERTARGET, AActor, flags7),
	DEFINE_FLAG(MF7, NOTELESTOMP, AActor, flags7),
	DEFINE_FLAG(MF7, ALWAYSTELEFRAG, AActor, flags7),
	DEFINE_FLAG(MF7, WEAPONSPAWN, AActor, flags7),
	DEFINE_FLAG(MF7, HARMFRIENDS, AActor, flags7),
	DEFINE_FLAG(MF7, BUDDHA, AActor, flags7),
	DEFINE_FLAG(MF7, FOILBUDDHA, AActor, flags7),
	DEFINE_FLAG(MF7, DONTTHRUST, AActor, flags7),
	DEFINE_FLAG(MF7, ALLOWPAIN, AActor, flags7),
	DEFINE_FLAG(MF7, CAUSEPAIN, AActor, flags7),
	DEFINE_FLAG(MF7, THRUREFLECT, AActor, flags7),
	DEFINE_FLAG(MF7, MIRRORREFLECT, AActor, flags7),
	DEFINE_FLAG(MF7, AIMREFLECT, AActor, flags7),
	DEFINE_FLAG(MF7, HITTARGET, AActor, flags7),
	DEFINE_FLAG(MF7, HITMASTER, AActor, flags7),
	DEFINE_FLAG(MF7, HITTRACER, AActor, flags7),
	DEFINE_FLAG(MF7, NODECAL, AActor, flags7),		// [ZK] Decal flags
	DEFINE_FLAG(MF7, FORCEDECAL, AActor, flags7),
	DEFINE_FLAG(MF7, LAXTELEFRAGDMG, AActor, flags7),
	DEFINE_FLAG(MF7, ICESHATTER, AActor, flags7),

	// Effect flags
	DEFINE_FLAG(FX, VISIBILITYPULSE, AActor, effects),
	DEFINE_FLAG2(FX_ROCKET, ROCKETTRAIL, AActor, effects),
	DEFINE_FLAG2(FX_GRENADE, GRENADETRAIL, AActor, effects),
	DEFINE_FLAG(RF, INVISIBLE, AActor, renderflags),
	DEFINE_FLAG(RF, FORCEYBILLBOARD, AActor, renderflags),
	DEFINE_FLAG(RF, FORCEXYBILLBOARD, AActor, renderflags),

	// Bounce flags
	DEFINE_FLAG2(BOUNCE_Walls, BOUNCEONWALLS, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_Floors, BOUNCEONFLOORS, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_Ceilings, BOUNCEONCEILINGS, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_Actors, ALLOWBOUNCEONACTORS, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_AutoOff, BOUNCEAUTOOFF, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_HereticType, BOUNCELIKEHERETIC, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_CanBounceWater, CANBOUNCEWATER, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_NoWallSound, NOWALLBOUNCESND, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_Quiet, NOBOUNCESOUND, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_AllActors, BOUNCEONACTORS, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_ExplodeOnWater, EXPLODEONWATER, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_MBF, MBFBOUNCER, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_AutoOffFloorOnly, BOUNCEAUTOOFFFLOORONLY, AActor, BounceFlags),
	DEFINE_FLAG2(BOUNCE_UseBounceState, USEBOUNCESTATE, AActor, BounceFlags),

	// Deprecated flags. Handling must be performed in HandleDeprecatedFlags
	DEFINE_DEPRECATED_FLAG(FIREDAMAGE),
	DEFINE_DEPRECATED_FLAG(ICEDAMAGE),
	DEFINE_DEPRECATED_FLAG(LOWGRAVITY),
	DEFINE_DEPRECATED_FLAG(SHORTMISSILERANGE),
	DEFINE_DEPRECATED_FLAG(LONGMELEERANGE),
	DEFINE_DEPRECATED_FLAG(QUARTERGRAVITY),
	DEFINE_DEPRECATED_FLAG(FIRERESIST),
	DEFINE_DEPRECATED_FLAG(HERETICBOUNCE),
	DEFINE_DEPRECATED_FLAG(HEXENBOUNCE),
	DEFINE_DEPRECATED_FLAG(DOOMBOUNCE),

	// Deprecated flags with no more existing functionality.
	DEFINE_DUMMY_FLAG(FASTER),				// obsolete, replaced by 'Fast' state flag
	DEFINE_DUMMY_FLAG(FASTMELEE),			// obsolete, replaced by 'Fast' state flag

	// Various Skulltag flags that are quite irrelevant to ZDoom
	DEFINE_DUMMY_FLAG(NONETID),				// netcode-based
	DEFINE_DUMMY_FLAG(ALLOWCLIENTSPAWN),	// netcode-based
	DEFINE_DUMMY_FLAG(CLIENTSIDEONLY),	    // netcode-based
	DEFINE_DUMMY_FLAG(SERVERSIDEONLY),		// netcode-based
	DEFINE_DUMMY_FLAG(EXPLODEONDEATH),	    // seems useless
};

static FFlagDef InventoryFlagDefs[] =
{
	// Inventory flags
	DEFINE_FLAG(IF, QUIET, AInventory, ItemFlags),
	DEFINE_FLAG(IF, AUTOACTIVATE, AInventory, ItemFlags),
	DEFINE_FLAG(IF, UNDROPPABLE, AInventory, ItemFlags),
	DEFINE_FLAG(IF, INVBAR, AInventory, ItemFlags),
	DEFINE_FLAG(IF, HUBPOWER, AInventory, ItemFlags),
	DEFINE_FLAG(IF, UNTOSSABLE, AInventory, ItemFlags),
	DEFINE_FLAG(IF, ADDITIVETIME, AInventory, ItemFlags),
	DEFINE_FLAG(IF, ALWAYSPICKUP, AInventory, ItemFlags),
	DEFINE_FLAG(IF, FANCYPICKUPSOUND, AInventory, ItemFlags),
	DEFINE_FLAG(IF, BIGPOWERUP, AInventory, ItemFlags),
	DEFINE_FLAG(IF, KEEPDEPLETED, AInventory, ItemFlags),
	DEFINE_FLAG(IF, IGNORESKILL, AInventory, ItemFlags),
	DEFINE_FLAG(IF, NOATTENPICKUPSOUND, AInventory, ItemFlags),
	DEFINE_FLAG(IF, PERSISTENTPOWER, AInventory, ItemFlags),
	DEFINE_FLAG(IF, RESTRICTABSOLUTELY, AInventory, ItemFlags),
	DEFINE_FLAG(IF, NEVERRESPAWN, AInventory, ItemFlags),
	DEFINE_FLAG(IF, NOSCREENFLASH, AInventory, ItemFlags),
	DEFINE_FLAG(IF, TOSSED, AInventory, ItemFlags),
	DEFINE_FLAG(IF, ALWAYSRESPAWN, AInventory, ItemFlags),
	DEFINE_FLAG(IF, TRANSFER, AInventory, ItemFlags),
	DEFINE_FLAG(IF, NOTELEPORTFREEZE, AInventory, ItemFlags),

	DEFINE_DEPRECATED_FLAG(PICKUPFLASH),
	DEFINE_DEPRECATED_FLAG(INTERHUBSTRIP),
};

static FFlagDef WeaponFlagDefs[] =
{
	// Weapon flags
	DEFINE_FLAG(WIF, NOAUTOFIRE, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, READYSNDHALF, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, DONTBOB, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, AXEBLOOD, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, NOALERT, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, AMMO_OPTIONAL, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, ALT_AMMO_OPTIONAL, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, PRIMARY_USES_BOTH, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, WIMPY_WEAPON, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, POWERED_UP, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, STAFF2_KICKBACK, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF_BOT, EXPLOSIVE, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, MELEEWEAPON, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF_BOT, BFG, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, CHEATNOTWEAPON, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, NO_AUTO_SWITCH, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, AMMO_CHECKBOTH, AWeapon, WeaponFlags),
	DEFINE_FLAG(WIF, NOAUTOAIM, AWeapon, WeaponFlags),

	DEFINE_DUMMY_FLAG(NOLMS),
	DEFINE_FLAG(WIF, ALT_USES_BOTH, AWeapon, WeaponFlags),
	DEFINE_DUMMY_FLAG(ALLOW_WITH_RESPAWN_INVUL),
};

static FFlagDef PlayerPawnFlagDefs[] =
{
	// PlayerPawn flags
	DEFINE_FLAG(PPF, NOTHRUSTWHENINVUL, APlayerPawn, PlayerFlags),
	DEFINE_FLAG(PPF, CANSUPERMORPH, APlayerPawn, PlayerFlags),
	DEFINE_FLAG(PPF, CROUCHABLEMORPH, APlayerPawn, PlayerFlags),
};

static FFlagDef PowerSpeedFlagDefs[] =
{
	// PowerSpeed flags
	DEFINE_FLAG(PSF, NOTRAIL, APowerSpeed, SpeedFlags),
};

static const struct FFlagList { const PClass *Type; FFlagDef *Defs; int NumDefs; } FlagLists[] =
{
	{ RUNTIME_CLASS(AActor), 		ActorFlagDefs,		countof(ActorFlagDefs) },
	{ RUNTIME_CLASS(AInventory), 	InventoryFlagDefs,	countof(InventoryFlagDefs) },
	{ RUNTIME_CLASS(AWeapon), 		WeaponFlagDefs,		countof(WeaponFlagDefs) },
	{ RUNTIME_CLASS(APlayerPawn),	PlayerPawnFlagDefs,	countof(PlayerPawnFlagDefs) },
	{ RUNTIME_CLASS(APowerSpeed),	PowerSpeedFlagDefs,	countof(PowerSpeedFlagDefs) },
};
#define NUM_FLAG_LISTS (countof(FlagLists))

//==========================================================================
//
// Find a flag by name using a binary search
//
//==========================================================================
static FFlagDef *FindFlag (FFlagDef *flags, int numflags, const char *flag)
{
	int min = 0, max = numflags - 1;

	while (min <= max)
	{
		int mid = (min + max) / 2;
		int lexval = stricmp (flag, flags[mid].name);
		if (lexval == 0)
		{
			return &flags[mid];
		}
		else if (lexval > 0)
		{
			min = mid + 1;
		}
		else
		{
			max = mid - 1;
		}
	}
	return NULL;
}

//==========================================================================
//
// Finds a flag that may have a qualified name
//
//==========================================================================

FFlagDef *FindFlag (const PClass *type, const char *part1, const char *part2)
{
	FFlagDef *def;
	size_t i;

	if (part2 == NULL)
	{ // Search all lists
		for (i = 0; i < NUM_FLAG_LISTS; ++i)
		{
			if (type->IsDescendantOf (FlagLists[i].Type))
			{
				def = FindFlag (FlagLists[i].Defs, FlagLists[i].NumDefs, part1);
				if (def != NULL)
				{
					return def;
				}
			}
		}
	}
	else
	{ // Search just the named list
		for (i = 0; i < NUM_FLAG_LISTS; ++i)
		{
			if (stricmp (FlagLists[i].Type->TypeName.GetChars(), part1) == 0)
			{
				if (type->IsDescendantOf (FlagLists[i].Type))
				{
					return FindFlag (FlagLists[i].Defs, FlagLists[i].NumDefs, part2);
				}
				else
				{
					return NULL;
				}
			}
		}
	}
	return NULL;
}

//==========================================================================
//
// Gets the name of an actor flag
//
//==========================================================================

const char *GetFlagName(unsigned int flagnum, int flagoffset)
{
	for(unsigned i = 0; i < countof(ActorFlagDefs); i++)
	{
		if (ActorFlagDefs[i].flagbit == flagnum && ActorFlagDefs[i].structoffset == flagoffset)
		{
			return ActorFlagDefs[i].name;
		}
	}
	return "(unknown)";	// return something printable
}

//==========================================================================
//
// Find a property by name using a binary search
//
//==========================================================================

FPropertyInfo *FindProperty(const char * string)
{
	int min = 0, max = properties.Size()-1;

	while (min <= max)
	{
		int mid = (min + max) / 2;
		int lexval = stricmp (string, properties[mid]->name);
		if (lexval == 0)
		{
			return properties[mid];
		}
		else if (lexval > 0)
		{
			min = mid + 1;
		}
		else
		{
			max = mid - 1;
		}
	}
	return NULL;
}

//==========================================================================
//
// Find a function by name using a binary search
//
//==========================================================================

AFuncDesc *FindFunction(const char * string)
{
	int min = 0, max = AFTable.Size()-1;

	while (min <= max)
	{
		int mid = (min + max) / 2;
		int lexval = stricmp (string, AFTable[mid].Name);
		if (lexval == 0)
		{
			return &AFTable[mid];
		}
		else if (lexval > 0)
		{
			min = mid + 1;
		}
		else
		{
			max = mid - 1;
		}
	}
	return NULL;
}

//==========================================================================
//
// Find a variable by name using a binary search
//
//==========================================================================

FVariableInfo *FindVariable(const char * string, const PClass *cls)
{
	int min = 0, max = variables.Size()-1;

	while (min <= max)
	{
		int mid = (min + max) / 2;
		int lexval;

		if (cls < variables[mid]->owner) lexval = -1;
		else if (cls > variables[mid]->owner) lexval = 1;
		else lexval = stricmp (string, variables[mid]->name);

		if (lexval == 0)
		{
			return variables[mid];
		}
		else if (lexval > 0)
		{
			min = mid + 1;
		}
		else
		{
			max = mid - 1;
		}
	}
	return NULL;
}

//==========================================================================
//
// Find an action function in AActor's table
//
//==========================================================================

PSymbolActionFunction *FindGlobalActionFunction(const char *name)
{
	PSymbol *sym = RUNTIME_CLASS(AActor)->Symbols.FindSymbol(name, false);
	if (sym != NULL && sym->SymbolType == SYM_ActionFunction)
		return static_cast<PSymbolActionFunction*>(sym);
	else
		return NULL;
}

//==========================================================================
//
// Sorting helpers
//
//==========================================================================

static int STACK_ARGS flagcmp (const void * a, const void * b)
{
	return stricmp( ((FFlagDef*)a)->name, ((FFlagDef*)b)->name);
}

static int STACK_ARGS propcmp(const void * a, const void * b)
{
	return stricmp( (*(FPropertyInfo**)a)->name, (*(FPropertyInfo**)b)->name);
}

static int STACK_ARGS funccmp(const void * a, const void * b)
{
	return stricmp( ((AFuncDesc*)a)->Name, ((AFuncDesc*)b)->Name);
}

static int STACK_ARGS varcmp(const void * a, const void * b)
{
	FVariableInfo *A = *(FVariableInfo**)a;
	FVariableInfo *B = *(FVariableInfo**)b;
	if (A->owner < B->owner) return -1;
	if (A->owner > B->owner) return 1;
	return stricmp(A->name, B->name);
}

//==========================================================================
//
// Initialization
//
//==========================================================================

void InitThingdef()
{
	// Sort the flag lists
	for (size_t i = 0; i < NUM_FLAG_LISTS; ++i)
	{
		qsort (FlagLists[i].Defs, FlagLists[i].NumDefs, sizeof(FFlagDef), flagcmp);
	}

	// Create a sorted list of properties
	if (properties.Size() == 0)
	{
		FAutoSegIterator probe(GRegHead, GRegTail);

		while (*++probe != NULL)
		{
			properties.Push((FPropertyInfo *)*probe);
		}
		properties.ShrinkToFit();
		qsort(&properties[0], properties.Size(), sizeof(properties[0]), propcmp);
	}

	// Create a sorted list of native action functions
	if (AFTable.Size() == 0)
	{
		FAutoSegIterator probe(ARegHead, ARegTail);

		while (*++probe != NULL)
		{
			AFTable.Push(*(AFuncDesc *)*probe);
		}
		AFTable.ShrinkToFit();
		qsort(&AFTable[0], AFTable.Size(), sizeof(AFTable[0]), funccmp);
	}

	// Create a sorted list of native variables
	if (variables.Size() == 0)
	{
		FAutoSegIterator probe(MRegHead, MRegTail);

		while (*++probe != NULL)
		{
			variables.Push((FVariableInfo *)*probe);
		}
		variables.ShrinkToFit();
		qsort(&variables[0], variables.Size(), sizeof(variables[0]), varcmp);
	}
}


text:
typedef AcArray<void*> AcDbVoidPtrArray;
#endif

redpajama_set_name: RedPajamaGithub


text:
"ClientId" => <?php echo $ClientId ?>

Imagine a world in which every single person on the planet has free access to the sum of all human knowledge.


text:
package com.org.restMeaurant.data;

public class Dish {
    private String name;

    public Dish(){
        name = "";
    }
    public Dish(String name){
        this.name = name;
    }
}


text:
/*
 * File: NumberPair.java
 * Author: Jyoti Parwatikar
 * Email:  jp@arl.wustl.edu
 * Organization: Washington University
 *
 * Derived from: none
 *
 * Date Created: 10/23/2003
 *
 * Description:
 *
 * Modification History:
 *
 */
import java.lang.String;

public class NumberPair implements DataPair
{
  protected double value1;
  protected double value2;
  protected boolean error;

    public NumberPair(){ this(0,0,false);}

    public NumberPair(double v1, double v2, boolean e)
    {
	error = e;
	value1 = v1;
	value2 = v2;
    }
  public NumberPair(double v1, double v2)
    {
	this(v1,v2,false);
    }

  public double getValue() { return value2;}
  public String getID() { return String.valueOf((int)value1);}
  public double getX() { return value1;}
  public double getY() { return value2;}
  public void setX(double v1) { value1 = v1;}
  public void setY(double v2) { value2 = v2;}
  public boolean isError() { return error;}
  public void setError(boolean e) { error = e; }

  public void printOut()
    {
	System.out.println("(" + String.valueOf(value1) + "," + String.valueOf(value2) + "," + String.valueOf(error) + ")");
    }
}


text:
<?php

namespace Slick\Tests\Filter;

use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit_Framework_TestCase as TestCase;
use Slick\Filter\FilterChain;
use Slick\Filter\FilterInterface;

/**
 * Filter Chain test case
 *
 * @package Slick\Tests\Filter
 * @author  Filipe Silva <silvam.filipe@gmail.com>
 */
class FilterChainTest extends TestCase
{

    /**
     * @var FilterChain
     */
    protected $chain;

    /**
     * Sets up the SUT filter chain object
     */
    protected function setUp()
    {
        parent::setUp();
        $this->chain = new FilterChain();
    }

    /**
     * Should apply the filter on top of the previous result through
     * the filter chain.
     * @test
     */
    public function filter()
    {
        $value = 'test';
        $filter = $this->createFilterMock();
        $filter->expects($this->once())
            ->method('filter')
            ->with($value)
            ->willReturn(ucfirst($value));
        $this->chain->add($filter);
        $this->assertEquals('Test', $this->chain->filter($value));
    }

    /**
     * Gets a mocked service
     * @return MockObject|FilterInterface
     */
    protected function createFilterMock()
    {
        $class = 'Slick\Filter\FilterInterface';
        $methods = ['filter'];
        /** @var FilterInterface|MockObject $filter */
        $filter = $this->getMockBuilder($class)
            ->setMethods($methods)
            ->getMock();
        return $filter;
    }
}


text:
package exec

import (
	"os"
	"strings"
)

// ErrNotFound is the error resulting if a path search failed to find an executable file.
var ErrNotFound = os.NewError("executable file not found in $PATH")

func findExecutable(file string) os.Error {
	d, err := os.Stat(file)
	if err != nil {
		return err
	}
	if d.IsRegular() && d.Permission()&0111 != 0 {
		return nil
	}
	return os.EPERM
}

// LookPath searches for an executable binary named file
// in the directories named by the PATH environment variable.
// If file contains a slash, it is tried directly and the PATH is not consulted.
func LookPath(file string) (string, os.Error) {
	// NOTE(rsc): I wish we could use the Plan 9 behavior here
	// (only bypass the path if file begins with / or ./ or ../)
	// but that would not match all the Unix shells.

	if strings.Contains(file, "/") {
		err := findExecutable(file)
		if err == nil {
			return file, nil
		}
		return "", &Error{file, err}
	}
	pathenv := os.Getenv("PATH")
	for _, dir := range strings.Split(pathenv, ":") {
		if dir == "" {
			// Unix shell semantics: path element "" means "."
			dir = "."
		}
		if err := findExecutable(dir + "/" + file); err == nil {
			return dir + "/" + file, nil
		}
	}
	return "", &Error{file, ErrNotFound}
}


text:
class Vector3d
{
	double x, y, z;

public:
	Vector3d(){};
	Vector3d(double xi, double yi, double zi) : x(xi), y(yi), z(zi){};
	void set(double xi, double yi, double zi);
	Vector3d get();

	double magnitude();
	Vector3d unitVector();

	friend std::ostream& operator<<(std::ostream& out, const Vector3d& object);
	friend Vector3d operator * (double alpha, const Vector3d& object);
	friend Vector3d operator * (const Vector3d& object, double alpha);
	friend Vector3d operator / (const Vector3d& object, double alpha);
	friend double operator * (const Vector3d& object1, const Vector3d& object2);
};


text:
package org.sisioh.aws4s.cfn.model

import com.amazonaws.services.cloudformation.model.EstimateTemplateCostResult
import org.sisioh.aws4s.PimpedType

object EstimateTemplateCostResultFactory {

  def create(): EstimateTemplateCostResult = new EstimateTemplateCostResult()

}

class RichEstimateTemplateCostResult(val underlying: EstimateTemplateCostResult)
    extends AnyVal with PimpedType[EstimateTemplateCostResult] {

  def urlOpt: Option[String] = Option(underlying.getUrl)

  def urlOpt_=(value: Option[String]): Unit =
    underlying.setUrl(value.orNull)

  def witUrlOpt(value: Option[String]): EstimateTemplateCostResult =
    underlying.withUrl(value.orNull)

}


text:
#include <async_safe/log.h>

extern "C" void __cxa_pure_virtual() {
  async_safe_fatal("Pure virtual function called. Are you calling virtual methods from a destructor?");
}


text:
function runAtlasWalking(example_options)
% Example running walking QP controller from
% Scott Kuindersma, Frank Permenter, and Russ Tedrake.
% An efficiently solvable quadratic program for stabilizing dynamic
% locomotion. In Proceedings of the International Conference on
% Robotics and Automation, Hong Kong, China, May 2014. IEEE.
%
% @option use_mex
% @option use_bullet
% @option use_angular_momentum
% @options navgoal
%

checkDependency('gurobi');

if nargin<1, example_options=struct(); end
if ~isfield(example_options,'use_mex'), example_options.use_mex = true; end
if ~isfield(example_options,'use_bullet') example_options.use_bullet = false; end
if ~isfield(example_options,'use_angular_momentum') example_options.use_angular_momentum = false; end
if ~isfield(example_options,'navgoal')
%  navgoal = [2*rand();0.25*randn();0;0;0;0];
  example_options.navgoal = [1.5;0;0;0;0;0];
end
if ~isfield(example_options,'terrain'), example_options.terrain = RigidBodyFlatTerrain; end

% silence some warnings
warning('off','Drake:RigidBodyManipulator:UnsupportedContactPoints')
warning('off','Drake:RigidBodyManipulator:UnsupportedVelocityLimits')

% construct robot model
options.floating = true;
options.ignore_self_collisions = true;
options.ignore_friction = true;
options.dt = 0.001;
options.terrain = example_options.terrain;
r = Atlas(fullfile(getDrakePath,'examples','Atlas','urdf','atlas_minimal_contact.urdf'),options);
r = r.removeCollisionGroupsExcept({'heel','toe'});
r = compile(r);

% set initial state to fixed point
load(fullfile(getDrakePath,'examples','Atlas','data','atlas_fp.mat'));
if isfield(options,'initial_pose'), xstar(1:6) = options.initial_pose; end
xstar = r.resolveConstraints(xstar);
r = r.setInitialState(xstar);

v = r.constructVisualizer;
v.display_dt = 0.03;

nq = getNumPositions(r);

x0 = xstar;

% Find the initial positions of the feet
R=rotz(example_options.navgoal(6));

rfoot_navgoal = example_options.navgoal;
lfoot_navgoal = example_options.navgoal;

rfoot_navgoal(1:3) = rfoot_navgoal(1:3) + R*[0;-0.13;0];
lfoot_navgoal(1:3) = lfoot_navgoal(1:3) + R*[0;0.13;0];

% Plan footsteps to the goal
goal_pos = struct('right', rfoot_navgoal, 'left', lfoot_navgoal);
footstep_plan = r.planFootsteps(x0(1:nq), goal_pos);

walking_plan_data = r.planWalkingZMP(x0(1:r.getNumPositions()), footstep_plan);

traj = atlasUtil.simulateWalking(r, walking_plan_data, example_options.use_mex, false, example_options.use_bullet, example_options.use_angular_momentum, true);

playback(v,traj,struct('slider',true));

[com, rms_com] = atlasUtil.plotWalkingTraj(r, traj, walking_plan_data);

if rms_com > length(footstep_plan.footsteps)*0.5
  error('runAtlasWalking unit test failed: error is too large');
  example_options.navgoal
end

% make sure we're at least vaguely close to the goal
valuecheck(com(1:3,end), [example_options.navgoal(1:2); 0.9], 0.2);

end

% TIMEOUT 1500


text:
Simple Frappe-like Python wrapper for Frappe REST API

### Install

```
git clone https://github.com/frappe/frappe-client
pip install -e frappe-client
```

### API

FrappeClient has a frappe like API

#### Login

Login to the Frappe HTTP Server by creating a new FrappeClient object

```py
from frappeclient import FrappeClient

conn = FrappeClient("example.com")
conn.login("user@example.com", "password")
```

#### Use token based authentication

```py
from frappeclient import FrappeClient

client = FrappeClient("https://example.com")
client.authenticate("my_api_key", "my_api_secret")
```

For demonstration purposes only! Never store any credentials in your source code. Instead, you could set them as environment variables and fetch them with `os.getenv()`.

#### get_list

Get a list of documents from the server

Arguments:
- `doctype`
- `fields`: List of fields to fetch
- `filters`: Dict of filters
- `limit_start`: Start at row ID (default 0)
- `limit_page_length`: Page length
- `order_by`: sort key and order (default is `modified desc`)

```py
users = conn.get_list('User', fields = ['name', 'first_name', 'last_name'], , filters = {'user_type':'System User'})
```

Example of filters:
- `{ "user_type": ("!=", "System User") }`
- `{ "creation": (">", "2020-01-01") }`
- `{ "name": "test@example.com" }`

#### insert

Insert a new document to the server

Arguments:

- `doc`: Document object

```python
doc = conn.insert({
	"doctype": "Customer",
	"customer_name": "Example Co",
	"customer_type": "Company",
	"website": "example.net"
})
```

#### get_doc

Fetch a document from the server

Arguments
- `doctype`
- `name`

```py
doc = conn.get_doc('Customer', 'Example Co')
```

#### get_value

Fetch a single value from the server

Arguments:

- `doctype`
- `fieldname`
- `filters`

```py
customer_name = conn.get_value("Customer", "name", {"website": "example.net"})
```

#### update

Update a document (if permitted)

Arguments:
- `doc`: JSON document object

```py
doc = conn.get_doc('Customer', 'Example Co')
doc['phone'] = '000000000'
conn.update(doc)
```

#### delete

Delete a document (if permitted)

Arguments:
- `doctype`
- `name`

```py
conn.delete('Customer', 'Example Co')
```

### Example

```python
from frappeclient import FrappeClient

conn = FrappeClient("example.com", "user@example.com", "password")
new_notes = [
	{"doctype": "Note", "title": "Sing", "public": True},
	{"doctype": "Note", "title": "a", "public": True},
	{"doctype": "Note", "title": "Song", "public": True},
	{"doctype": "Note", "title": "of", "public": True},
	{"doctype": "Note", "title": "sixpence", "public": True}
]

for note in new_notes:
	print(conn.insert(note))

# get note starting with s
notes = conn.get_list('Note',
	filters={'title': ('like', 's')},
	fields=["title", "public"]
)
```

### Example

See example.py for more info

### License

MIT


text:
package net.floodlightcontroller.traceroute;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.floodlightcontroller.core.IOFSwitch;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class TraceRouteResource extends ServerResource {
	@Get("json")
	public LinkedList retrieve() {
		TraceRouteService traceRouteService = (TraceRouteService) getContext()
				.getAttributes()
				.get(TraceRouteService.class.getCanonicalName());

		LinkedList map = traceRouteService.getPath();

		return map;
	}
}


text:
import datetime
from collections import OrderedDict

class FormRegister(Form):

	def __init__(self, data = None, items = None, post = None, **args):

		if data is None: data = {}
		if post is None: post = {}

		if 'id' not in data:
			data['id'] = 'FormRegister'

		# set always to 0,
		# after validation it may have value
		self.nabar_id = 0

		super().__init__(data, items, **args)

		set = self.add('FieldSet', {
			'id' : 'registerset',
			'css' : ['i-form-row i-margin-large']
		})

		set.add('TextBox', {
			'id' : 'name',
			'value' : post.get('name', ''),
			'title' : s('Your name'),
			'placeholder' : s('Your name'),
			'required' :  True,
			'validation_rule' : ['Length', 3, '>', 0, 'The name length should be greater than 3.'],
			'css' : ['i-width-1-1 i-form-large']
		})
		set.add('TextBoxEmail', {
			'id' : 'email',
			'value' : post.get('email', ''),
			'title' : s('E-mail address'),
			'placeholder' : s('E-mail address'),
			'required' :  True,
			'validation_rule' : ['Email', 'Invalid E-mail address.'],
			'css' : ['i-width-1-1 i-form-large']
		})

		#set.add('TextBox', {
			#'id' : 'nabarname',
			#'value' : post.get('nabarname', ''),
			#'title' : s('Login name'),
			#'placeholder' : s('Login name'),
			#'validation_rule' : ['Length', 5, '>', 0, 'The loginname length should be greater than 5.'],
			#'css' : ['i-width-1-1 i-form-large']
		#})
		pwd = post.get('password', '')
		repwd = post.get('repassword', '')

		set.add('Password', {
			'id' : 'password',
			'value' : pwd,
			'title' : s('Password'),
			'placeholder' : s('Password'),
			'validation_rule' : ['Length', 5, '>', 0, 'The password length should be greater than 5!'],
			'css' : ['i-width-1-1 i-form-large'],
		})

		set.add('Password', {
			'id' : 'repassword',
			'value' : repwd,
			'title' : s('Retype password'),
			'placeholder' : s('Retype password'),
			'validation_rule' : ['Equal', pwd,  '=', 0, 'Two passwords must match!'],
			'css' : ['i-width-1-1 i-form-large'],
		})

		options = OrderedDict()
		options['male'] = s('Male')
		options['female'] = s('Female')
		options['shemale'] = s('Shemale')

		set.add('RadioBoxes', {
			'id' : 'gender',
			'name' : 'gender',
			'title' : s('Gender'),
			'options' : options,
			'value' : post.get('gender', 'female'),
			'css' : ['i-width-1-1 i-form-large'],
		})

		#options = OrderedDict()
		set.add('DateSelect', {
			'id' : 'dob',
			'name' : 'dob',
			'options' : options,
			'title' : s('Date of birth'),
			'value' : post.get('dob', None),
			'required' : True,
			'validation_rule' : ['Equal', datetime.date.today() - datetime.timedelta(days = 13*365), '<', 0, 'The Age should be greater than 13 years.'],
			'css' : ['i-width-1-1 i-form-large'],
		})

		set = self.add('FieldSet', {
			'id' : 'actionset',
			'css' : ['i-form-row i-text-primary']
		})
		tpath = IN.APP.config.paths['term_condition']
		tlink = ''.join(('', s('Terms & Conditions'), ''))
		set.add('TextDiv',{
			'id' : 'terms',
			'value' : s('''By registering to our site you are accepting our {term_link}.''', {'term_link' : tlink}),
			'css' : ['i-text-primary']
		})

		set.add('Submit',{
			'id' : 'submit',
			'value' : s('Register new account'),
			'css' : ['i-button i-button-primary i-button-large']
		})

		#set.add('CheckBox',{
			#'id' : 'accept',
			#'label' : s('I Accept Terms & Conditions'),
			#'value' : 'on',
			#'checked' : 'on' == post.get('accept', ''),
			#'css' : ['']
		#})

		set = self.add('FieldSet', {
			'id' : 'linkset',
			'css' : ['i-form-row']
		})

		#set.add('Link',{
			#'id' : 'login_link',
			#'href' : 'nabar/login',
			#'value' : ' ' + s('Login'),
			#'css' : ['ajax i-button']
		#})

		self.css.append('i-panel i-panel-box i-margin-large')

@IN.register('FormRegister', type = 'Former')
class FormRegisterFormer(FormFormer):

	def validate(self, form, post):

		if form.has_errors: # fields may have errors
			return

		name = form['registerset']['name'].value.strip()
		#loginname = form['registerset']['loginname'].value
		email = form['registerset']['email'].value.strip()
		gender = form['registerset']['gender'].value
		password = form['registerset']['password'].value
		dob = form['registerset']['dob'].value

		if not name or not email or not gender or not password or not dob:
			form.error_message = s('Unknown error occurred! Please try again later!')
			form.has_errors = True
			return False

		# TODO: make it as Valuator?

		# email already exists

		try:
			cursor = IN.db.execute('''select l.nabar_id
				FROM account.login l
				JOIN account.nabar a ON l.nabar_id = a.id
				where l.type = %(type)s and l.value = %(email)s AND
				l.status > 0 and a.status > 0 LIMIT 1''', {
				'type' : 'email',
				'email' : email,
			})
		except Exception as e:
			IN.logger.debug()
			form.error_message = s('Unknown error occurred! Please try again later!')
			form.has_errors = True
			return False

		if cursor.rowcount > 0:
			form['registerset']['email'].has_errors = True
			form['registerset']['email'].error_message = s('Someone already having account with this E-mail address!')
			form.has_errors = True
			return False

		# register
		# email verification mail, save token to db
		auth = None

		# form.has_errors = False dont set, field validations may have errors

	def submit(self, form, post):

		if form.has_errors:
			return

		name = form['registerset']['name'].value
		email = form['registerset']['email'].value
		gender = form['registerset']['gender'].value
		password = form['registerset']['password'].value
		dob = form['registerset']['dob'].value

		if not name or not email or not gender or not password or not dob:
			form.error_message = s('Unknown error occurred! Please try again later!')
			form.has_errors = True
			return False

		nabar = None
		try:
			nabar = IN.nabar.register(email, password, name, gender, dob, None)
			form.info = form.info or ''
			form.info = form.info + s('''

Your account has been created!

Please check your e-mail for verification link!

''')

		except Exception as e:
			IN.logger.debug()
			form.error_message = s('Unknown error occurred! Please try again later!')
			form.has_errors = True
			return False

		if not nabar:
			form.error_message = s('Unknown error occurred! Please try again later!')
			form.has_errors = True
			return False

		# TODO: display error message
		form.redirect = None # non ajax redirect on register forms


text:
//-----------------------------------------------------------------------
// <copyright file="GlobalsTest.cs" company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Research.Wwt.Excel.Common.Tests
{
    /// <summary>
    /// This is a test class for GlobalsTest and is intended to contain all GlobalsTest Unit Tests
    /// </summary>
    [TestClass()]
    public class GlobalsTest
    {
        /// <summary>
        /// Test context instance.
        /// </summary>
        private TestContext testContextInstance;

        /// <summary>
        /// Gets or sets the test context which provides
        /// information about and functionality for the current test run.
        /// </summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        /// <summary>
        /// A test for AddinTraceSource
        /// </summary>
        [TestMethod()]
        public void AddinTraceSourceTest()
        {
            TraceSource actual = Globals.AddinTraceSource;
            Assert.IsNotNull(actual);
            Assert.AreEqual(actual.Name, "WWTEarthAddin");
        }
    }
}


text:
(function($) {
    /** global: Craft */
    /** global: Garnish */
    var SystemMessages = Garnish.Base.extend(
        {
            messages: null,

            init: function() {
                this.messages = [];

                var $container = $('#messages'),
                    $messages = $container.find('.message');

                for (var i = 0; i < $messages.length; i++) {
                    var message = new Message($messages[i]);
                    this.messages.push(message);
                }
            }

        });

    var Message = Garnish.Base.extend(
        {
            $container: null,
            key: null,
            $subject: null,
            $body: null,
            modal: null,

            init: function(container) {
                this.$container = $(container);
                this.key = this.$container.attr('data-key');
                this.$subject = this.$container.find('.subject:first');
                this.$body = this.$container.find('.body:first');

                this.addListener(this.$container, 'click', 'edit');
            },

            edit: function() {
                if (!this.modal) {
                    this.modal = new MessageSettingsModal(this);
                }
                else {
                    this.modal.show();
                }
            },

            updateHtmlFromModal: function() {
                var subject = this.modal.$subjectInput.val(),
                    body = Craft.escapeHtml(this.modal.$bodyInput.val()).replace(/\n/g, '<br>');

                this.$subject.text(subject);
                this.$body.html(body);
            }

        });

    var MessageSettingsModal = Garnish.Modal.extend(
        {
            message: null,

            $languageSelect: null,
            $subjectInput: null,
            $bodyInput: null,
            $saveBtn: null,
            $cancelBtn: null,
            $spinner: null,

            loading: false,

            init: function(message) {
                this.message = message;

                this.base(null, {
                    resizable: true
                });

                this.loadContainer();
            },

            loadContainer: function(language) {
                var data = {
                    key: this.message.key,
                    language: language
                };

                // If CSRF protection isn't enabled, these won't be defined.
                if (typeof Craft.csrfTokenName !== 'undefined' && typeof Craft.csrfTokenValue !== 'undefined') {
                    // Add the CSRF token
                    data[Craft.csrfTokenName] = Craft.csrfTokenValue;
                }

                Craft.postActionRequest('system-messages/get-message-modal', data, $.proxy(function(response, textStatus) {
                    if (textStatus === 'success') {
                        if (!this.$container) {
                            var $container = $('<form class="modal fitted message-settings" accept-charset="UTF-8">' + response.body + '</form>').appendTo(Garnish.$bod);
                            this.setContainer($container);
                            this.show();
                        }
                        else {
                            this.$container.html(response.body);
                        }

                        this.$languageSelect = this.$container.find('.language:first > select');
                        this.$subjectInput = this.$container.find('.message-subject:first');
                        this.$bodyInput = this.$container.find('.message-body:first');
                        this.$saveBtn = this.$container.find('.submit:first');
                        this.$cancelBtn = this.$container.find('.cancel:first');
                        this.$spinner = this.$container.find('.spinner:first');

                        this.addListener(this.$languageSelect, 'change', 'switchLanguage');
                        this.addListener(this.$container, 'submit', 'saveMessage');
                        this.addListener(this.$cancelBtn, 'click', 'cancel');

                        setTimeout($.proxy(function() {
                            this.$subjectInput.trigger('focus');
                        }, this), 100);
                    }

                }, this));
            },

            switchLanguage: function() {
                this.loadContainer(this.$languageSelect.val());
            },

            saveMessage: function(event) {
                event.preventDefault();

                if (this.loading) {
                    return;
                }

                var data = {
                    key: this.message.key,
                    language: (this.$languageSelect.length ? this.$languageSelect.val() : Craft.language),
                    subject: this.$subjectInput.val(),
                    body: this.$bodyInput.val()
                };

                this.$subjectInput.removeClass('error');
                this.$bodyInput.removeClass('error');

                if (!data.subject || !data.body) {
                    if (!data.subject) {
                        this.$subjectInput.addClass('error');
                    }

                    if (!data.body) {
                        this.$bodyInput.addClass('error');
                    }

                    Garnish.shake(this.$container);
                    return;
                }

                this.loading = true;
                this.$saveBtn.addClass('active');
                this.$spinner.show();

                Craft.postActionRequest('system-messages/save-message', data, $.proxy(function(response, textStatus) {
                    this.$saveBtn.removeClass('active');
                    this.$spinner.hide();
                    this.loading = false;

                    if (textStatus === 'success') {
                        if (response.success) {
                            // Only update the page if we're editing the current language's message
                            if (data.language === Craft.language) {
                                this.message.updateHtmlFromModal();
                            }

                            this.hide();
                            Craft.cp.displayNotice(Craft.t('app', 'Message saved.'));
                        }
                        else {
                            Craft.cp.displayError();
                        }
                    }

                }, this));
            },

            cancel: function() {
                this.hide();

                if (this.message) {
                    this.message.modal = null;
                }
            }

        });

    new SystemMessages();
})(jQuery);


text:
getCannonLocs = function(colorIndex, xTile, yTile, xDir, yDir, dMapWidth, dMapHeight, numCannons)
    tileSize = 12
    for yOff = 0, dMapHeight, 1 do
        for xOff = dMapWidth, 0, -1 do

            if xDir == 1 then
                xAttempt = xTile + xOff
            else
                xAttempt = dMapWidth + xTile - xOff
            end

            if yDir == 1 then
                yAttempt = yTile + yOff
            else
                yAttempt = dMapHeight + yTile - yOff
            end

            xAttempt = xAttempt % dMapWidth
                yAttempt = yAttempt % dMapHeight

            if test:isValidCannonLoc(colorIndex, numCannons,xAttempt, yAttempt) then
                xPos = xAttempt * tileSize  --dMapWidth + dMapWidth / 2
                yPos = yAttempt * tileSize  --dMapHeight + dMapHeight / 2
                test:setDAITarget(colorIndex, xPos, yPos)
            	return true
            end
        end
    end
	return false
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addons>
	<addon id="script.showgrabber" name="Show Grabber" provider-name="Tim Leisti" version="0.9.5">

		<requires>

			<import addon="xbmc.python" version="2.14.0"/>

			<import addon="script.module.requests" version="2.18.4"/>

			<import addon="script.module.beautifulsoup" version="3.2.1"/>

		</requires>

		<extension library="default.py" point="xbmc.python.script"/>

		<extension point="xbmc.addon.metadata">

			<summary lang="en">An interface to managing automatic episode downloads. Integrates with the Transmission BitTorrent client.</summary>

			<description lang="en">Provides a nice interface for editing an XML file used by a cron-trigger script to search for and download new episodes of shows using the Transmission BitTorrent client.</description>

			<platform>all</platform>

		</extension>

		<extension name="Corvust Addons" point="xbmc.addon.repository">

			<info compressed="false">https://raw.githubusercontent.com/corvust/repo-XBMC/master/addons.xml</info>

			<checksum>https://raw.githubusercontent.com/corvust/repo-XBMC/master/addons.xml.md5</checksum>

			<datadir zip="true">https://raw.githubusercontent.com/corvust/repo-XBMC/master</datadir>

		</extension>

	</addon>
</addons>


text:
/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', [])
.controller('CarouselController', ['$scope', '$element', '$interval', '$animate', function ($scope, $element, $interval, $animate) {
  var self = this,
    slides = self.slides = $scope.slides = [],
    NO_TRANSITION = 'uib-noTransition',
    SLIDE_DIRECTION = 'uib-slideDirection',
    currentIndex = -1,
    currentInterval, isPlaying;
  self.currentSlide = null;

  var destroyed = false;
  /* direction: "prev" or "next" */
  self.select = $scope.select = function(nextSlide, direction) {
    var nextIndex = self.indexOfSlide(nextSlide);
    //Decide direction if it's not given
    if (direction === undefined) {
      direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
    }
    //Prevent this user-triggered transition from occurring if there is already one in progress
    if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
      goNext(nextSlide, nextIndex, direction);
    }
  };

  function goNext(slide, index, direction) {
    // Scope has been destroyed, stop here.
    if (destroyed) { return; }

    angular.extend(slide, {direction: direction, active: true});
    angular.extend(self.currentSlide || {}, {direction: direction, active: false});
    if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition &&
      slide.$element) {
      slide.$element.data(SLIDE_DIRECTION, slide.direction);
      $scope.$currentTransition = true;
      slide.$element.one('$animate:close', function closeFn() {
        $scope.$currentTransition = null;
      });
    }

    self.currentSlide = slide;
    currentIndex = index;

    //every time you change slides, reset the timer
    restartTimer();
  }

  $scope.$on('$destroy', function () {
    destroyed = true;
  });

  function getSlideByIndex(index) {
    if (angular.isUndefined(slides[index].index)) {
      return slides[index];
    }
    var i, len = slides.length;
    for (i = 0; i < slides.length; ++i) {
      if (slides[i].index == index) {
        return slides[i];
      }
    }
  }

  self.getCurrentIndex = function() {
    if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
      return +self.currentSlide.index;
    }
    return currentIndex;
  };

  /* Allow outside people to call indexOf on slides array */
  self.indexOfSlide = function(slide) {
    return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
  };

  $scope.next = function() {
    var newIndex = (self.getCurrentIndex() + 1) % slides.length;

    if (newIndex === 0 && $scope.noWrap()) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'next');
  };

  $scope.prev = function() {
    var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;

    if ($scope.noWrap() && newIndex === slides.length - 1){
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'prev');
  };

  $scope.isActive = function(slide) {
     return self.currentSlide === slide;
  };

  $scope.$watch('interval', restartTimer);
  $scope.$on('$destroy', resetTimer);

  function restartTimer() {
    resetTimer();
    var interval = +$scope.interval;
    if (!isNaN(interval) && interval > 0) {
      currentInterval = $interval(timerFn, interval);
    }
  }

  function resetTimer() {
    if (currentInterval) {
      $interval.cancel(currentInterval);
      currentInterval = null;
    }
  }

  function timerFn() {
    var interval = +$scope.interval;
    if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
      $scope.next();
    } else {
      $scope.pause();
    }
  }

  $scope.play = function() {
    if (!isPlaying) {
      isPlaying = true;
      restartTimer();
    }
  };
  $scope.pause = function() {
    if (!$scope.noPause) {
      isPlaying = false;
      resetTimer();
    }
  };

  self.addSlide = function(slide, element) {
    slide.$element = element;
    slides.push(slide);
    //if this is the first slide or the slide is set to active, select it
    if(slides.length === 1 || slide.active) {
      self.select(slides[slides.length-1]);
      if (slides.length == 1) {
        $scope.play();
      }
    } else {
      slide.active = false;
    }
  };

  self.removeSlide = function(slide) {
    if (angular.isDefined(slide.index)) {
      slides.sort(function(a, b) {
        return +a.index > +b.index;
      });
    }
    //get the index of the slide inside the carousel
    var index = slides.indexOf(slide);
    slides.splice(index, 1);
    if (slides.length > 0 && slide.active) {
      if (index >= slides.length) {
        self.select(slides[index-1]);
      } else {
        self.select(slides[index]);
      }
    } else if (currentIndex > index) {
      currentIndex--;
    }
  };

  $scope.$watch('noTransition', function(noTransition) {
    $element.data(NO_TRANSITION, noTransition);
  });

}])

/**
 * @ngdoc directive
 * @name ui.bootstrap.carousel.directive:carousel
 * @restrict EA
 *
 * @description
 * Carousel is the outer container for a set of image 'slides' to showcase.
 *
 * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
 * @param {boolean=} noTransition Whether to disable transitions on the carousel.
 * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
    <carousel>
      <slide>

Beautiful!

      </slide>
      <slide>

D'aww!

      </slide>
    </carousel>
  </file>
  <file name="demo.css">
    .carousel-indicators {
      top: auto;
      bottom: 15px;
    }
  </file>
</example>
 */
.directive('carousel', [function() {
  return {
    restrict: 'EA',
    transclude: true,
    replace: true,
    controller: 'CarouselController',
    require: 'carousel',
    templateUrl: 'template/carousel/carousel.html',
    scope: {
      interval: '=',
      noTransition: '=',
      noPause: '=',
      noWrap: '&'
    }
  };
}])

/**
 * @ngdoc directive
 * @name ui.bootstrap.carousel.directive:slide
 * @restrict EA
 *
 * @description
 * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}.  Must be placed as a child of a carousel element.
 *
 * @param {boolean=} active Model binding, whether or not this slide is currently active.
 * @param {number=} index The index of the slide. The slides will be sorted by this parameter.
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">

  <carousel>
    <slide ng-repeat="slide in slides" active="slide.active" index="$index">

Slide {{$index}}

{{slide.text}}

    </slide>
  </carousel>
  Interval, in milliseconds: <input type="number" ng-model="myInterval">

Enter a negative number to stop the interval.

  </file>
  <file name="script.js">
function CarouselDemoCtrl($scope) {
  $scope.myInterval = 5000;
}
  </file>
  <file name="demo.css">
    .carousel-indicators {
      top: auto;
      bottom: 15px;
    }
  </file>
</example>
*/

.directive('slide', function() {
  return {
    require: '^carousel',
    restrict: 'EA',
    transclude: true,
    replace: true,
    templateUrl: 'template/carousel/slide.html',
    scope: {
      active: '=?',
      index: '=?'
    },
    link: function (scope, element, attrs, carouselCtrl) {
      carouselCtrl.addSlide(scope, element);
      //when the scope is destroyed then remove the slide from the current slides array
      scope.$on('$destroy', function() {
        carouselCtrl.removeSlide(scope);
      });

      scope.$watch('active', function(active) {
        if (active) {
          carouselCtrl.select(scope);
        }
      });
    }
  };
})

.animation('.item', [
         '$animate',
function ($animate) {
  var NO_TRANSITION = 'uib-noTransition',
    SLIDE_DIRECTION = 'uib-slideDirection';

  return {
    beforeAddClass: function (element, className, done) {
      // Due to transclusion, noTransition property is on parent's scope
      if (className == 'active' && element.parent() &&
          !element.parent().data(NO_TRANSITION)) {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction == 'next' ? 'left' : 'right';
        element.addClass(direction);
        $animate.addClass(element, directionClass).then(function () {
          if (!stopped) {
            element.removeClass(directionClass + ' ' + direction);
          }
          done();
        });

        return function () {
          stopped = true;
        };
      }
      done();
    },
    beforeRemoveClass: function (element, className, done) {
      // Due to transclusion, noTransition property is on parent's scope
      if (className == 'active' && element.parent() &&
          !element.parent().data(NO_TRANSITION)) {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction == 'next' ? 'left' : 'right';
        $animate.addClass(element, directionClass).then(function () {
          if (!stopped) {
            element.removeClass(directionClass);
          }
          done();
        });
        return function () {
          stopped = true;
        };
      }
      done();
    }
  };

}])

;


text:
function(doc) {
    if (doc.document_type == 'Entity' && !doc.void) {
        for (index in doc.aggregation_paths._type) {
            emit(doc.aggregation_paths._type[index], 1);
        }
    }
}


text:
from __future__ import annotations

import os.path
import subprocess
from textwrap import dedent

import pytest

from pants.backend.go import target_type_rules
from pants.backend.go.goals import package_binary
from pants.backend.go.goals.package_binary import GoBinaryFieldSet
from pants.backend.go.target_types import GoBinaryTarget, GoModTarget, GoPackageTarget
from pants.backend.go.util_rules import (
    assembly,
    build_pkg,
    build_pkg_target,
    first_party_pkg,
    go_mod,
    import_analysis,
    link,
    sdk,
    third_party_pkg,
)
from pants.core.goals.package import BuiltPackage
from pants.engine.addresses import Address
from pants.engine.rules import QueryRule
from pants.engine.target import Target
from pants.testutil.rule_runner import RuleRunner

@pytest.fixture()
def rule_runner() -> RuleRunner:
    rule_runner = RuleRunner(
        rules=[
            *assembly.rules(),
            *import_analysis.rules(),
            *package_binary.rules(),
            *build_pkg.rules(),
            *build_pkg_target.rules(),
            *first_party_pkg.rules(),
            *go_mod.rules(),
            *link.rules(),
            *target_type_rules.rules(),
            *third_party_pkg.rules(),
            *sdk.rules(),
            QueryRule(BuiltPackage, (GoBinaryFieldSet,)),
        ],
        target_types=[GoBinaryTarget, GoModTarget, GoPackageTarget],
    )
    rule_runner.set_options([], env_inherit={"PATH"})
    return rule_runner

def build_package(rule_runner: RuleRunner, binary_target: Target) -> BuiltPackage:
    field_set = GoBinaryFieldSet.create(binary_target)
    result = rule_runner.request(BuiltPackage, [field_set])
    rule_runner.write_digest(result.digest)
    return result

def test_package_simple(rule_runner: RuleRunner) -> None:
    rule_runner.write_files(
        {
            "go.mod": dedent(
                """\
                module foo.example.com
                go 1.17
                """
            ),
            "main.go": dedent(
                """\
                package main

                import (
                    "fmt"
                )

                func main() {
                    fmt.Println("Hello world!")
                }
                """
            ),
            "BUILD": dedent(
                """\
                go_mod(name='mod')
                go_package(name='pkg')
                go_binary(name='bin')
                """
            ),
        }
    )
    binary_tgt = rule_runner.get_target(Address("", target_name="bin"))
    built_package = build_package(rule_runner, binary_tgt)
    assert len(built_package.artifacts) == 1
    assert built_package.artifacts[0].relpath == "bin"

    result = subprocess.run([os.path.join(rule_runner.build_root, "bin")], stdout=subprocess.PIPE)
    assert result.returncode == 0
    assert result.stdout == b"Hello world!\n"

def test_package_with_dependencies(rule_runner: RuleRunner) -> None:
    rule_runner.write_files(
        {
            "lib/lib.go": dedent(
                """\
                package lib

                import (
                    "fmt"
                    "rsc.io/quote"
                )

                func Quote(s string) string {
                    return fmt.Sprintf(">> %s <<", s)
                }

                func GoProverb() string {
                    return quote.Go()
                }
                """
            ),
            "lib/BUILD": "go_package()",
            "main.go": dedent(
                """\
                package main

                import (
                    "fmt"
                    "foo.example.com/lib"
                )

                func main() {
                    fmt.Println(lib.Quote("Hello world!"))
                    fmt.Println(lib.GoProverb())
                }
                """
            ),
            "go.mod": dedent(
                """\
                module foo.example.com
                go 1.17
                require (
                    golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect
                    rsc.io/quote v1.5.2
                    rsc.io/sampler v1.3.0 // indirect
                )
                """
            ),
            "go.sum": dedent(
                """\
                golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c h1:qgOY6WgZOaTkIIMiVjBQcw93ERBE4m30iBm00nkL0i8=
                golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
                rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y=
                rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=
                rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4=
                rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
                """
            ),
            "BUILD": dedent(
                """\
                go_mod(name='mod')
                go_package(name='pkg')
                go_binary(name='bin')
                """
            ),
        }
    )
    binary_tgt = rule_runner.get_target(Address("", target_name="bin"))
    built_package = build_package(rule_runner, binary_tgt)
    assert len(built_package.artifacts) == 1
    assert built_package.artifacts[0].relpath == "bin"

    result = subprocess.run([os.path.join(rule_runner.build_root, "bin")], stdout=subprocess.PIPE)
    assert result.returncode == 0
    assert result.stdout == (
        b">> Hello world! <<\n"
        b"Don't communicate by sharing memory, share memory by communicating.\n"
    )


text:
import * as mongodb from 'mongodb';

export default ((global as any).db as mongodb.Db).collection('posts');


text:
"""
byceps.blueprints.style_guide.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

import xml.etree.ElementTree as ET

from flask import current_app

from ...util.framework.blueprint import create_blueprint
from ...util.framework.templating import templated

blueprint = create_blueprint('style_guide', __name__)

ICONS_FILENAME = 'static/style/icons.svg'

@blueprint.route('/')
@templated
def index():
    """Show style guide."""
    icon_names = list(sorted(_get_icon_names()))

    return {
        'icon_names': icon_names,
    }

def _get_icon_names():
    """Extract icon names from SVG file."""
    with current_app.open_resource(ICONS_FILENAME) as f:
        tree = ET.parse(f)

    svg_namespace = 'http://www.w3.org/2000/svg'
    symbol_elems = tree.iterfind('.//{%s}symbol' % svg_namespace)
    return {elem.get('id') for elem in symbol_elems}


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

  <wicket:panel>

                <wicket:message key="menus" />

          <input type="button" wicket:id="newsave" />
          <input type="button" wicket:id="remove" />

[modal window goes here]

    <form wicket:id="menuForm"></form>
  </wicket:panel>


text:
import Client, {
    BasicCouchResponse,
    BulkDocumentError,
    BulkResponse,
    ClientOptions,
    configureDatabase,
    CouchDoc,
    DesignDocConfiguration,
    isDavenportError,
    PostPutCopyResponse,
    PropSelector,
    ViewRow,
    ViewRowWithDoc
    } from '../';
import inspect from 'logspect';
import {
    AsyncSetupFixture,
    AsyncTeardownFixture,
    AsyncTest,
    Expect,
    FocusTest,
    TestFixture,
    Timeout
    } from 'alsatian';
import { DavenportError } from '../index';
import range = require("lodash/range");

const DB_URL = "http://localhost:5984";
const DB_NAME = "davenport_tests";
const OPTIONS: ClientOptions = {
    // username: "test_admin",
    // password: "test_password"
    // proxy: {
    //     host: "127.0.0.1",
    //     port: 8888
    // }
}

declare const emit: (key, value) => void;

interface TestObject extends CouchDoc {
    hello: string;
    foo: number;
    bar: number;
}

function isClient(client): client is Client<any> {
    return client instanceof (Client);
}

function getClient(): Client<TestObject> {
    return new Client<TestObject>(DB_URL, DB_NAME, OPTIONS);
}

const designDoc: DesignDocConfiguration = {
    name: "list",
    views: [
        {
            name: "only-foos-greater-than-10",
            map: function (doc: TestObject) {
                if (doc.foo > 10) {
                    emit(doc._id, doc);
                }
            }.toString(),
            reduce: "_count"
        },
        {
            name: "by-foo-value",
            map: function (doc: TestObject) {
                emit(doc.foo, doc);
            }.toString(),
        },
        {
            name: "by-foo-complex-key",
            map: function (doc: TestObject) {
                emit([doc.hello, doc.foo], doc);
            }.toString(),
        }
    ]
}

@TestFixture("Davenport")
export class DavenportTestFixture {
    @AsyncSetupFixture
    @Timeout(5000)
    public async setupFixture() {
        const client = getClient();
        const result = await client.createDb();

        Expect(result.ok).toBe(true);

        // Insert at least one doc for list tests
        const insert = await client.post({
            bar: 117,
            foo: 22,
            hello: "world",
            _id: undefined,
            _rev: undefined
        })
    }

    @AsyncTeardownFixture
    @Timeout(5000)
    public async teardownFixture() {
        const client = getClient();
        const result = await client.deleteDb();
        Expect(result.ok).toBe(true);
    }

    @AsyncTest("Davenport.createDeleteDb")
    @Timeout(5000)
    public async createDeleteDbTest() {
        const dbName = "davenport_delete_me";
        const client = new Client(DB_URL, dbName, OPTIONS);
        const createResult = await client.createDb();

        Expect(createResult.ok).toBe(true);

        const dbInfo = await client.getDbInfo();
        Expect(dbInfo.db_name).toEqual(dbName);

        const deleteResult = await client.deleteDb();
        Expect(deleteResult.ok).toBe(true);

        try {
            await client.getDbInfo();
        } catch (err) {
            if (isDavenportError(err)) {
                Expect(err.status).toEqual(404);
            } else {
                throw err;
            }
        }
    }

    @AsyncTest("Davenport.createDb when database already exists")
    @Timeout(5000)
    public async createDbWhenItExistsTest() {
        const dbName = "davenport_delete-me";
        const client = new Client(DB_URL, dbName, OPTIONS);
        const firstResult = await client.createDb();

        Expect(firstResult.ok).toBe(true);

        const secondResult = await client.createDb();

        Expect(secondResult.ok).toBe(true);
        Expect(secondResult.alreadyExisted).toBe(true);
    }

    @AsyncTest("Davenport.configureDatabase")
    @Timeout(5000)
    public async configureTest() {
        const db = await configureDatabase<TestObject>(DB_URL, {
            name: DB_NAME,
            designDocs: [designDoc]
        }, OPTIONS)

        Expect(isClient(db)).toBe(true);
    }

    @AsyncTest("Davenport new Client()")
    @Timeout(5000)
    public async createClientTest() {
        const client = getClient();

        Expect(isClient(client)).toBe(true);
    }

    @AsyncTest("Davenport.post")
    @Timeout(5000)
    public async postTest() {
        const client = getClient();
        const result = await client.post({
            bar: 5,
            foo: 4,
            hello: "world",
            _id: undefined,
            _rev: undefined
        });

        Expect(typeof (result.id)).toBe("string");
        Expect(typeof (result.rev)).toBe("string");
    }

    @AsyncTest("Davenport.get")
    @Timeout(5000)
    public async getTest() {
        const client = getClient();
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: "world",
            _id: undefined,
            _rev: undefined
        });
        const result = await client.get(createResult.id);

        Expect(result.bar).toBe(5);
        Expect(result.foo).toBe(4);
        Expect(result.hello).toBe("world");
    }

    @AsyncTest("Davenport.put")
    @Timeout(5000)
    public async putTest() {
        const client = getClient();
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: "world",
            _id: undefined,
            _rev: undefined
        });
        const putResult = await client.put(createResult.id, {
            bar: 4,
            foo: 3,
            hello: "world",
            _id: undefined,
            _rev: undefined
        }, createResult.rev);
        const result = await client.get(putResult.id, putResult.rev);

        Expect(createResult.id).toBe(putResult.id);
        Expect(result.bar).toBe(4);
        Expect(result.foo).toBe(3);
        Expect(result.hello).toBe("world");
    }

    @AsyncTest("Davenport.listWithDocs")
    @Timeout(5000)
    public async listWithDocsTest() {
        const client = getClient();
        const list = await client.listWithDocs();

        Expect(list.offset).toBe(0);
        Expect(Array.isArray(list.rows)).toBe(true);
        Expect(list.total_rows).toBeGreaterThan(0);
        Expect(list.rows.every(r => {
            if (r._id.indexOf("_design") > -1) {
                return true;
            }

            return !!r &&
                typeof (r.bar) === "number" &&
                typeof (r.foo) === "number" &&
                typeof (r.hello) === "string" &&
                typeof (r._id) === "string" &&
                typeof (r._rev) === "string";
        })).toBe(true);
    }

    @AsyncTest("Davenport.listWithoutDocs")
    @Timeout(5000)
    public async listWithoutDocsTest() {
        const client = getClient();
        const list = await client.listWithoutDocs();

        Expect(list.offset).toBe(0);
        Expect(Array.isArray(list.rows)).toBe(true);
        Expect(list.total_rows).toBeGreaterThan(0);
        Expect(list.rows.every(r => typeof (r.rev) === "string" && typeof (r["id"]) === "undefined")).toBe(true);
    }

    @AsyncTest("Davenport.count")
    @Timeout(5000)
    public async countTest() {
        const client = getClient();
        const count = await client.count();

        Expect(count).toBeGreaterThan(0);
    }

    @AsyncTest("Davenport.count with selector")
    @Timeout(5000)
    public async countWithSelectorTest() {
        const client = getClient();
        const uuid = `a-unique-string-${Date.now()}`;

        for (let i = 0; i < 3; i++) {
            await client.post({
                bar: i,
                foo: i + 1,
                hello: uuid,
                _id: undefined,
                _rev: undefined
            })
        };

        const count = await client.countBySelector({
            hello: uuid
        });

        Expect(count).toBe(3);
    }

    @AsyncTest("Davenport.count with selector indexes")
    @Timeout(5000)
    public async countWithSelectorIndexesTest() {
        const client = getClient();
        const uuid = `a-unique-string-${Date.now()}`;

        for (let i = 0; i < 3; i++) {
            await client.post({
                bar: i,
                foo: i + 1,
                hello: uuid,
                _id: undefined,
                _rev: undefined
            })
        };

        const count = await client.countBySelector({
            hello: {
                $eq: uuid
            }
        });

        Expect(count).toBe(3);
    }

    @AsyncTest("Davenport.delete")
    @Timeout(5000)
    public async deleteTest() {
        const client = getClient();
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: "world",
            _id: undefined,
            _rev: undefined
        });
        let error;

        try {
            await client.delete(createResult.id, createResult.rev)
        } catch (e) {
            error = e;
        }

        Expect(error).not.toBeDefined();
    }

    @AsyncTest("Davenport.exists")
    @Timeout(5000)
    public async existsTest() {
        const client = getClient();
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: "world",
            _id: undefined,
            _rev: undefined
        });
        const exists = await client.exists(createResult.id);

        Expect(exists).toBe(true);
    }

    @AsyncTest("Davenport.exists with field value")
    @Timeout(5000)
    public async existsWithFieldValueTest() {
        const client = getClient();
        const uuid = `a-unique-string-${Date.now()}`;
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: uuid,
            _id: undefined,
            _rev: undefined
        })
        const exists = await client.existsByFieldValue(uuid, "hello");

        Expect(exists).toBe(true);
    }

    @AsyncTest("Davenport.exists with selector")
    @Timeout(5000)
    public async existsWithSelectorTest() {
        const client = getClient();
        const uuid = `a-unique-string-${Date.now()}`;
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: uuid,
            _id: undefined,
            _rev: undefined
        })
        const exists = await client.existsBySelector({
            hello: {
                $eq: uuid
            }
        });

        Expect(exists).toBe(true);
    }

    @AsyncTest("Davenport.copy")
    @Timeout(5000)
    public async copyTest() {
        const client = getClient();
        const uuid = `a-unique-string-${Date.now()}`;
        const createResult = await client.post({
            bar: 5,
            foo: 4,
            hello: uuid,
            _id: undefined,
            _rev: undefined
        });
        const copyResult = await client.copy(createResult.id, uuid);
        const result = await client.get(copyResult.id);

        Expect(result._id).toBe(uuid);
    }

    @AsyncTest("Davenport.find")
    @Timeout(5000)
    public async findTest() {
        const client = getClient();

        for (let i = 0; i < 3; i++) {
            await client.post({
                bar: 5,
                foo: 4,
                hello: "shwoop",
                _id: undefined,
                _rev: undefined
            })
        }

        const result = await client.find({
            selector: {
                hello: "shwoop"
            }
        });

        Expect(Array.isArray(result)).toBe(true);
        Expect(result.every(r => r.hello === "shwoop")).toBe(true);
    }

    @AsyncTest("Davenport.view")
    @Timeout(5000)
    public async viewTest() {
        await this.createFoosGreaterThan10();

        const client = getClient();
        const result = await client.view<TestObject>(designDoc.name, "only-foos-greater-than-10");

        const testRows = () => {
            this.checkViewRows(result.rows);
        }

        Expect(Array.isArray(result.rows)).toBe(true);
        Expect(result.rows.length > 0);
        Expect(testRows).not.toThrow();
        Expect(this.checkViewRows(result.rows)).toBe(true);
    }

    @AsyncTest("Davenport.viewWithDocs")
    @Timeout(5000)
    public async viewWithDocsTest() {
        await this.createFoosGreaterThan10();

        const client = getClient();
        const result = await client.viewWithDocs<TestObject>(designDoc.name, "only-foos-greater-than-10");

        const testRows = () => {
            this.checkViewRows(result.rows);
        }

        Expect(Array.isArray(result.rows)).toBe(true);
        Expect(result.rows.length > 0);
        Expect(testRows).not.toThrow();
        Expect(this.checkViewRows(result.rows)).toBe(true);
    }

    @AsyncTest("Davenport.view reduces result")
    @Timeout(5000)
    public async viewReducesTests() {
        const client = getClient();
        const result = await client.view<number>(designDoc.name, "only-foos-greater-than-10", {
            reduce: true,
            group: false
        });

        const sum = result.rows.reduce((sum, row) => sum + row.value, 0);

        Expect(Array.isArray(result.rows)).toBe(true);
        Expect(sum).toBeGreaterThan(0);
    }

    @AsyncTest("Davenport.view with start and end keys")
    @Timeout(5000)
    public async viewWithKeysTest() {
        await this.createFoosGreaterThan10();

        const client = getClient();
        const result = await client.view<TestObject>(designDoc.name, "by-foo-value", {
            start_key: 15,
            end_key: 20
        });

        const testRows = () => {
            this.checkViewRows(result.rows);
        }

        Expect(true).toBe(true);
        Expect(result.rows.length > 0).toBe(true);
        Expect(testRows).not.toThrow();
        Expect(this.checkViewRows(result.rows)).toBe(true);
        Expect(result.rows.every(row => row.value.foo >= 15 && row.value.foo <= 20)).toBe(true);
    }

    @AsyncTest("Davenport.view with complex start and end keys")
    @Timeout(5000)
    public async viewWithComplexKeyTest() {
        const keyPart = "keyPart";
        await this.createFoosGreaterThan10(keyPart);
        const client = getClient();
        let result = await client.view<TestObject>(designDoc.name, "by-foo-complex-key", {
            start_key: [keyPart],
            end_key: [keyPart, {}],
            inclusive_end: true
        });

        const testRows = () => {
            this.checkViewRows(result.rows);
        }

        Expect(result.rows.length).toEqual(6);
        Expect(testRows).not.toThrow();
        Expect(this.checkViewRows(result.rows)).toBe(true);

        result = await client.view<TestObject>(designDoc.name, "by-foo-complex-key", {
            start_key: [keyPart, 15],
            end_key: [keyPart, 20],
            inclusive_end: true
        });

        Expect(testRows).not.toThrow();
        Expect(this.checkViewRows(result.rows)).toBe(true);
        Expect(result.rows.every(row => (row.key[1] >= 15 && row.key[1] <= 20))).toBe(true);
        Expect(result.rows.every(row => row.value.foo >= 15 && row.value.foo <= 20)).toBe(true);
    }

    @AsyncTest("Davenport.bulk insert with auto-generated ids.")
    @Timeout(5000)
    public async bulkTest() {
        const docs = range(0, 100).map<TestObject>(i => ({
            bar: i,
            foo: i * 3,
            hello: "world",
            _id: undefined,
            _rev: undefined
        }))

        const client = getClient();
        const result = await client.bulk(docs);

        Expect(result.length).toEqual(100);
        Expect(result.every(item => !this.isBulkError(item))).toBe(true);
        Expect(result.every((item: PostPutCopyResponse) => !!item.id && !!item.rev)).toBe(true);
    }

    @AsyncTest("Davenport.bulk insert with custom ids.")
    @Timeout(5000)
    public async bulkWithCustomIdsTest() {
        const generatedIds: string[] = [];
        const docs = range(0, 100).map<TestObject>(i => {
            const id = this.guid();
            generatedIds.push(id);

            return {
                _id: id,
                bar: i,
                foo: i * 4,
                hello: "goodbye",
                _rev: undefined
            }
        })
        const client = getClient();
        const result = await client.bulk(docs);

        Expect(result.length).toEqual(100);
        Expect(result.every(item => !this.isBulkError(item))).toBe(true);
        Expect(result.every((item: PostPutCopyResponse) => generatedIds.indexOf(item.id) > -1 && !!item.rev)).toBe(true);
    }

    @AsyncTest("Davenport.bulk insert and update with conflicts")
    @Timeout(5000)
    public async bulkWithConflicts() {
        const client = getClient();
        const totalExisting = 10;
        const totalOperations = 100;
        const existingDocs = await client.bulk(range(0, totalExisting).map<TestObject>(i => ({
            bar: i,
            foo: i * 5,
            hello: "I'm an existing doc, used with the bulkWithConflicts test.",
            _id: undefined,
            _rev: undefined
        })));
        const result = await client.bulk(range(0, totalOperations).map<TestObject>(i => {
            const existingDoc = existingDocs[i];
            const id = existingDoc ? existingDoc.id : undefined;

            return {
                _id: id,
                _rev: undefined,
                bar: i,
                foo: i * 5,
                hello: "I'm a generated doc, used with the bulkWIthConflicts test."
            }
        }))

        Expect(result.length).toEqual(100);
        Expect(result.every(item => !!item.id)).toBe(true);

        const conflicts = result.filter(this.isBulkError);
        const rest = result.filter(item => !this.isBulkError(item));

        Expect(conflicts.length).toEqual(totalExisting);
        Expect(conflicts.every((item: BulkDocumentError) => item.error === "conflict" && !!item.reason)).toBe(true);
        Expect(rest.length).toEqual(totalOperations - totalExisting);
        Expect(rest.every((item: PostPutCopyResponse) => !!item.rev)).toBe(true);
    }

    private async createFoosGreaterThan10(hello: string = "world") {
        const client = getClient();

        await Promise.all([0, 1, 2, 3, 4, 5].map(i => client.post({
            bar: 5,
            foo: i === 0 ? 17 : Math.floor(Math.random() * 30),
            hello: hello,
            _id: undefined,
            _rev: undefined
        })));
    }

    private hasDoc(arg: ViewRow<TestObject>): arg is ViewRowWithDoc<TestObject> {
        return (arg as ViewRowWithDoc<TestObject>).doc !== undefined;
    }

    private isBulkError(arg): arg is BulkDocumentError {
        const typed: BulkDocumentError = arg;

        return !!typed.error;
    }

    private guid() {
        // From https://stackoverflow.com/a/2117523
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);

            return v.toString(16);
        });
    }

    private checkViewRows(rows: ViewRow<TestObject>[]) {
        const errors = rows.reduce((errors, row) => {
            function pushError(prop: string, expectedType: string) {
                errors.push({
                    property: prop,
                    message: `Property ${prop} was not of type ${expectedType}.`
                })
            };

            if (this.hasDoc(row)) {
                if (!row.doc) {
                    errors.push({ property: "row.doc", message: "row.doc was not found." });
                }
            }

            if (typeof (row.id) !== "string") {
                pushError("row.id", "string");
            }

            if (!row.key) {
                errors.push({ property: "row.key", message: "row.key was not found." })
            }

            if (!row.value) {
                errors.push({ property: "row.value", message: "row.value was not found." })

                return errors;
            }

            if (typeof (row.value.bar) !== "number") {
                pushError("row.value.bar", "number");
            }

            if (typeof (row.value.foo) !== "number") {
                pushError("row.value.foo", "number");
            }

            if (typeof (row.value.hello) !== "string") {
                pushError("row.value.hello", "string");
            }

            if (typeof (row.value._id) !== "string") {
                pushError("row.value._id", "string");
            }

            if (typeof (row.value._rev) !== "string") {
                pushError("row.value._rev", "string");
            }

            return errors;
        }, [] as { property: string; message: string; }[]);

        if (errors.length > 0) {
            inspect("View row errors: ", errors);

            throw new Error(`There were ${errors.length} errors in the view result.`);
        }

        return errors.length === 0;
    }
}


text:
require_relative './base_reddit_publisher'

class Gifs < BaseRedditPublisher
  def initialize(reddit_kit = RedditKit)
    @subreddit = 'gifs'
    @min_score = 1500
    super
  end

  def run
    super
    links.each do |l|
      next unless l.url[-4..-1] == '.gif'
      mark_link_as_visited l
      text = "Gif: #{l.title}
"
      hipchat[room].send('Gifs', text, message_format: 'html',
                                       color: 'purple')
      break
    end
  end
end


text:
require_relative 'minitest_helper'

describe TrackerApi::Resources::Project do
  let(:pt_user) { PT_USER_1 }
  let(:client) { TrackerApi::Client.new token: pt_user[:token] }
  let(:project_id) { pt_user[:project_id] }
  let(:project) { VCR.use_cassette('get project') { client.project(project_id) } }

  describe '.epics' do
    it 'gets all epics for this project' do
      VCR.use_cassette('get epics', record: :new_episodes) do
        epics = project.epics

        epics.wont_be_empty
        epic = epics.first
        epic.must_be_instance_of TrackerApi::Resources::Epic
      end
    end

    describe 'with eager loading of epics' do
      let(:project_with_epics) do
        VCR.use_cassette('get project with epics') do
          client.project(project_id, fields: ':default,epics(:default,label(name))')
        end
      end

      # does not raise VCR::Errors::UnhandledHTTPRequestError
      it 'does not make an extra request' do
        epics = project_with_epics.epics

        epics.wont_be_empty
        epic = epics.first
        epic.must_be_instance_of TrackerApi::Resources::Epic
      end
    end
  end

  describe '.iterations' do
    it 'can get only done iterations' do
      VCR.use_cassette('get done iterations', record: :new_episodes) do
        offset          = -project.number_of_done_iterations_to_show.to_i
        done_iterations = project.iterations(scope: :done, offset: offset)

        done_iterations.wont_be_empty
        done_iterations.length.must_be :<=, project.number_of_done_iterations_to_show

        iteration = done_iterations.first
        iteration.must_be_instance_of TrackerApi::Resources::Iteration
      end
    end

    it 'can get current iteration' do
      VCR.use_cassette('get current iteration', record: :new_episodes) do
        iterations = project.iterations(scope: :current)

        iterations.wont_be_empty

        current = iterations.first
        current.must_be_instance_of TrackerApi::Resources::Iteration
        current.stories.wont_be_empty

        story = current.stories.first
        story.must_be_instance_of TrackerApi::Resources::Story
      end
    end
  end

  describe '.stories' do
    it 'can get unscheduled stories' do
      VCR.use_cassette('get unscheduled stories', record: :new_episodes) do
        stories = project.stories(with_state: :unscheduled)

        stories.wont_be_empty

        story = stories.first
        story.must_be_instance_of TrackerApi::Resources::Story
        story.current_state.must_equal 'unscheduled'
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;

using Mono.Cecil.Rocks;

namespace N
{

    /// <summary>
    /// ID string generated is "T:N.X".
    /// </summary>
    public class X : IX<KVP<string, int>>
    {
        /// <summary>
        /// ID string generated is "M:N.X.#ctor".
        /// </summary>
        public X() { }

        /// <summary>
        /// ID string generated is "M:N.X.#ctor(System.Int32)".
        /// </summary>
        /// <param name="i">Describe parameter.</param>
        public X(int i) { }

        /// <summary>
        /// ID string generated is "F:N.X.q".
        /// </summary>
        public string q;

        /// <summary>
        /// ID string generated is "F:N.X.PI".
        /// </summary>
        public const double PI = 3.14;

        /// <summary>
        /// ID string generated is "M:N.X.f".
        /// </summary>
        public int f() { return 1; }

        /// <summary>
        /// ID string generated is "M:N.X.bb(System.String,System.Int32@)".
        /// </summary>
        public int bb(string s, ref int y) { return 1; }

        /// <summary>
        /// ID string generated is "M:N.X.gg(System.Int16[],System.Int32[0:,0:])".
        /// </summary>
        public int gg(short[] array1, int[,] array) { return 0; }

        /// <summary>
        /// ID string generated is "M:N.X.op_Addition(N.X,N.X)".
        /// </summary>
        public static X operator +(X x, X xx) { return x; }

        /// <summary>
        /// ID string generated is "P:N.X.prop".
        /// </summary>
        public int prop { get { return 1; } set { } }

        /// <summary>
        /// ID string generated is "E:N.X.d".
        /// </summary>
#pragma warning disable 67
        public event D d;
#pragma warning restore 67

		/// <summary>
		/// ID string generated is "P:N.X.Item(System.String)".
		/// </summary>
		public int this[string s] { get { return 1; } }

        /// <summary>
        /// ID string generated is "T:N.X.Nested".
        /// </summary>
        public class Nested { }

        /// <summary>
        /// ID string generated is "T:N.X.D".
        /// </summary>
        public delegate void D(int i);

        /// <summary>
        /// ID string generated is "M:N.X.op_Explicit(N.X)~System.Int32".
        /// </summary>
        public static explicit operator int(X x) { return 1; }

	    public static void Linq (IEnumerable<string> enumerable, Func<string> selector)
	    {
	    }

        /// <summary>
		/// ID string generated is "M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})"
        /// </summary>
        void IX<KVP<string, int>>.IXA (KVP<string, int> k) { }
    }

	public interface IX<K>
	{
		void IXA (K k);
	}

	public class KVP<K, T> { }
}

namespace Mono.Cecil.Tests {

	[TestFixture]
	public class DocCommentIdTests {

		[Test]
		public void TypeDef ()
		{
			AssertDocumentID ("T:N.X", GetTestType ());
		}

		[Test]
		public void ParameterlessCtor ()
		{
			var type = GetTestType ();
			var ctor = type.GetConstructors ().Single (m => m.Parameters.Count == 0);

			AssertDocumentID ("M:N.X.#ctor", ctor);
		}

		[Test]
		public void CtorWithParameters ()
		{
			var type = GetTestType ();
			var ctor = type.GetConstructors ().Single (m => m.Parameters.Count == 1);

			AssertDocumentID ("M:N.X.#ctor(System.Int32)", ctor);
		}

		[Test]
		public void Field ()
		{
			var type = GetTestType ();
			var field = type.Fields.Single (m => m.Name == "q");

			AssertDocumentID ("F:N.X.q", field);
		}

		[Test]
		public void ConstField ()
		{
			var type = GetTestType ();
			var field = type.Fields.Single (m => m.Name == "PI");

			AssertDocumentID ("F:N.X.PI", field);
		}

		[Test]
		public void ParameterlessMethod ()
		{
			var type = GetTestType ();
			var method = type.Methods.Single (m => m.Name == "f");

			AssertDocumentID ("M:N.X.f", method);
		}

		[Test]
		public void MethodWithByRefParameters ()
		{
			var type = GetTestType ();
			var method = type.Methods.Single (m => m.Name == "bb");

			AssertDocumentID ("M:N.X.bb(System.String,System.Int32@)", method);
		}

		[Test]
		public void MethodWithArrayParameters ()
		{
			var type = GetTestType ();
			var method = type.Methods.Single (m => m.Name == "gg");

			AssertDocumentID ("M:N.X.gg(System.Int16[],System.Int32[0:,0:])", method);
		}

		[Test]
		public void OpAddition ()
		{
			var type = GetTestType ();
			var op = type.Methods.Single (m => m.Name == "op_Addition");

			AssertDocumentID ("M:N.X.op_Addition(N.X,N.X)", op);
		}

		[Test]
		public void OpExplicit ()
		{
			var type = GetTestType ();
			var op = type.Methods.Single (m => m.Name == "op_Explicit");

			AssertDocumentID ("M:N.X.op_Explicit(N.X)~System.Int32", op);
		}

		[Test]
		public void Property ()
		{
			var type = GetTestType ();
			var property = type.Properties.Single (p => p.Name == "prop");

			AssertDocumentID ("P:N.X.prop", property);
		}

		[Test]
		public void Indexer ()
		{
			var type = GetTestType ();
			var indexer = type.Properties.Single (p => p.Name == "Item");

			AssertDocumentID ("P:N.X.Item(System.String)", indexer);
		}

		[Test]
		public void Event ()
		{
			var type = GetTestType ();
			var @event = type.Events.Single (e => e.Name == "d");

			AssertDocumentID ("E:N.X.d", @event);
		}

		[Test]
		public void Delegate ()
		{
			var type = GetTestType ();
			var @delegate = type.NestedTypes.Single (t => t.Name == "D");

			AssertDocumentID ("T:N.X.D", @delegate);
		}

		[Test]
		public void NestedType ()
		{
			var type = GetTestType ();
			var nestedType = type.NestedTypes.Single (t => t.Name == "Nested");

			AssertDocumentID ("T:N.X.Nested", nestedType);
		}

		[Test]
		public void Linq ()
		{
			var type = GetTestType ();
			var method = type.GetMethod ("Linq");

			AssertDocumentID ("M:N.X.Linq(System.Collections.Generic.IEnumerable{System.String},System.Func{System.String})", method);
		}

		[Test]
		public void EII ()
		{
			var type = GetTestType ();
			var method = type.Methods.Where (m => m.Name.Contains("IXA")).First ();

			AssertDocumentID ("M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})", method);
		}

		TypeDefinition GetTestType ()
		{
			return typeof (N.X).ToDefinition ();
		}

		static void AssertDocumentID (string docId, IMemberDefinition member)
		{
			Assert.AreEqual (docId, DocCommentId.GetDocCommentId (member));
		}
	}
}


text:
<?php

namespace App\Http\Middleware;
use Laravel\Lumen\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * Exclude API routes from CSRF protection.
     *
     * @var array
     */
    public function handle($request, \Closure $next) {
        if ($request->is('api/v*/action/*') || $request->is('api/v*/data/*')) {
            // Exclude public API from CSRF protection
            // but do not exclude private API endpoints
            return $next($request);
        }

        return parent::handle($request, $next);
    }
}