text:
using System;
using UnityEngine;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using UnityEngine.UI;

public class DosBox : MonoBehaviour
{
	public BoxInfo RightText;
	public GameObject Actors;
	public Arrow Arrow;
	public Box BoxPrefab;
	public Box[] Boxes;
	public bool ShowAdditionalInfo;
	public bool ShowAITD1Vars;
	public bool SpeedRunMode;
	public int CurrentCamera = -1;
	public int CurrentCameraRoom = -1;
	public int CurrentCameraFloor = -1;

	public ProcessMemory ProcessMemory;
	public Box Player;

	private int entryPoint;
	private readonly Dictionary<int, int> bodyIdToMemoryAddress = new Dictionary<int, int>();
	private readonly Dictionary<int, int> animIdToMemoryAddress = new Dictionary<int, int>();

	public GameVersion GameVersion;
	private GameConfig gameConfig;
	private readonly Dictionary<GameVersion, GameConfig> gameConfigs = new Dictionary<GameVersion, GameConfig>
	{
		{ GameVersion.AITD1        , new GameConfig(0x220CE, 160, 82) },
		{ GameVersion.AITD1_FLOPPY , new GameConfig(0x20542, 160, 82) },
		{ GameVersion.AITD1_DEMO   , new GameConfig(0x2050A, 160, 82) },
		{ GameVersion.AITD2        , new GameConfig(0x300D0, 180, 90) },
		{ GameVersion.AITD2_FLOPPY , new GameConfig(0x2F850, 180, 90) },
		{ GameVersion.AITD2_DEMO   , new GameConfig(0x38DC0, 176, 86) },
		{ GameVersion.AITD3        , new GameConfig(0x38180, 182, 90) },
		{ GameVersion.AITD3_DEMO   , new GameConfig(0x377A0, 182, 90) },
		{ GameVersion.JACK         , new GameConfig(0x39EC4, 180, 90) },
		{ GameVersion.TIMEGATE     , new GameConfig(0x00000, 202, 90, 0x2ADD0) },
		{ GameVersion.TIMEGATE_DEMO, new GameConfig(0x00000, 202, 90, 0x45B98) },
	};

	private Vector3 lastPlayerPosition;
	private int lastValidPlayerIndex = -1;
	private int linkfloor;
	private int linkroom;
	private readonly byte[] memory = new byte[640 * 1024];

	//fps
	private int oldFramesCount;
	private readonly Queue<KeyValuePair<int, float>> previousFrames = new Queue<KeyValuePair<int, float>>();
	private int frameCounter;

	//delay
	private float lastDelay;
	private readonly Timer delayCounter = new Timer();
	private readonly Timer totalDelay = new Timer();

	//frame time
	private readonly Timer frameTime = new Timer();
	private int oldFrames;
	private float frameTimeElapsed;

	private int inHand;
	private int redrawFlag;
	private bool allowInventory;
	private bool saveTimerFlag;
	private uint internalTimer1, internalTimer1Frozen;
	private int internalTimer2, internalTimer2Frozen;

	Box GetActor(int index)
	{
		Box box = Boxes[index];
		if (box == null)
		{
			box = Instantiate(BoxPrefab);
			box.transform.parent = Actors.transform;
			box.name = "Actor";
			box.Slot = index;
			box.DosBox = this;
			box.RoomLoader = GetComponent<RoomLoader>();
			Boxes[index] = box;
		}

		return box;
	}

	void RemoveActor(int index)
	{
		Box box = Boxes[index];
		if (box != null)
		{
			Destroy(box.gameObject);
			Boxes[index] = null;
		}
	}

	void OnDestroy()
	{
		if (ProcessMemory != null)
		{
			ProcessMemory.Close();
		}
	}

	bool AreActorsInitialized()
	{
		for (int i = 0 ; i < Boxes.Length ; i++)
		{
			int k = GetActorMemoryAddress(i);
			int id = memory.ReadShort(k);
			if (id != 0)
			{
				return true;
			}
		}

		return false;
	}

	public void RefreshMemory()
	{
		if (ProcessMemory != null && ProcessMemory.Read(memory, 0, memory.Length) == 0)
		{
			ProcessMemory.Close();
			ProcessMemory = null;
		}
	}

	public void UpdateAllActors()
	{
		if (gameConfig == null)
		{
			return;
		}

		Player = null;
		bool initialized = AreActorsInitialized();

		//read actors info
		for (int i = 0 ; i < Boxes.Length ; i++) //up to 50 actors max
		{
			int k = GetActorMemoryAddress(i);
			int id = memory.ReadShort(k + 0);

			if (id != -1 && initialized)
			{
				Box box = GetActor(i);
				box.ID = id;
				box.Body = memory.ReadShort(k + 2);
				box.Flags = memory.ReadShort(k + 4);
				box.ColFlags = memory.ReadShort(k + 6);

				memory.ReadBoundingBox(k + 8, out box.BoundingLower, out box.BoundingUpper);

				FixBoundingWrap(ref box.BoundingLower.x, ref box.BoundingUpper.x);
				FixBoundingWrap(ref box.BoundingLower.z, ref box.BoundingUpper.z);

				memory.ReadBoundingBox(k + 20, out box.Box2DLower, out box.Box2DUpper);

				box.LocalPosition = memory.ReadVector(k + 28);
				box.WorldPosition = memory.ReadVector(k + 34);
				box.Angles = memory.ReadVector(k + 40);

				box.Floor = memory.ReadShort(k + 46);
				box.Room = memory.ReadShort(k + 48);
				box.LifeMode = memory.ReadShort(k + 50);
				box.Life = memory.ReadShort(k + 52);
				box.Chrono = memory.ReadUnsignedInt(k + 54);
				box.RoomChrono = memory.ReadUnsignedInt(k + 58);
				box.Anim = memory.ReadShort(k + 62);
				box.AnimType = memory.ReadShort(k + 64);
				box.NextAnim = memory.ReadShort(k + 66);
				box.Keyframe = memory.ReadShort(k + 74);
				box.TotalFrames = memory.ReadShort(k + 76);
				box.EndFrame = memory.ReadShort(k + 78);
				box.EndAnim = memory.ReadShort(k + 80);

				box.TrackMode = memory.ReadShort(k + gameConfig.TrackModeOffset);
				box.TrackNumber = memory.ReadShort(k + 84);
				box.PositionInTrack = memory.ReadShort(k + 88);

				int bodyAddress, animAddress;
				if (bodyIdToMemoryAddress.TryGetValue(box.Body, out bodyAddress) &&
					animIdToMemoryAddress.TryGetValue(box.Anim, out animAddress) &&
					animAddress < memory.Length &&
					bodyAddress < memory.Length)
				{
					int bonesInAnim = memory.ReadShort(animAddress + 2);
					int keyframeAddress = animAddress + box.Keyframe * (bonesInAnim * 8 + 8);
					box.KeyFrameTime = memory.ReadUnsignedShort(bodyAddress + 20);
					box.KeyFrameLength = memory.ReadShort(keyframeAddress + 4);
				}

				if (GameVersion == GameVersion.AITD1)
				{
					box.Mod = memory.ReadVector(k + 90);
				}
				else
				{
					box.Mod = Vector3Int.Zero;
				}

				box.OldAngle = memory.ReadShort(k + 106);
				box.NewAngle = memory.ReadShort(k + 108);
				box.RotateParam = memory.ReadShort(k + 110);
				box.RotateTime = memory.ReadShort(k + 112);

				box.Speed = memory.ReadShort(k + 116);

				box.Col = memory.ReadVector(k + 126);
				box.ColBy = memory.ReadShort(k + 132);
				box.HardTrigger = memory.ReadShort(k + 134);
				box.HardCol = memory.ReadShort(k + 136);
				box.Hit = memory.ReadShort(k + 138);
				box.HitBy = memory.ReadShort(k + 140);
				box.ActionType = memory.ReadShort(k + 142);
				box.HotBoxSize = memory.ReadShort(k + 148);
				box.HitForce = memory.ReadShort(k + 150);
				box.HotPosition = memory.ReadVector(k + 154);
			}
			else
			{
				RemoveActor(i);
			}
		}

		//search current camera target (fallback if player not found)
		int cameraTargetID = -1;
		if (GameVersion == GameVersion.AITD1)
		{
			int currentCameraTarget = memory.ReadShort(entryPoint + 0x19B6C);
			foreach (Box box in Boxes)
			{
				if (box != null && box.Slot == currentCameraTarget)
				{
					cameraTargetID = box.ID;
					break;
				}
			}
		}

		//search player
		foreach (Box box in Boxes)
		{
			if (box != null && (box.TrackMode == 1 || box.ID == lastValidPlayerIndex))
			{
				//update player index
				lastValidPlayerIndex = cameraTargetID = box.ID;
				break;
			}
		}

		//automatically switch room and floor (has to be done before setting other actors positions)
		foreach (Box box in Boxes)
		{
			if (box != null && box.ID == cameraTargetID)
			{
				SwitchRoom(box.Floor, box.Room);
			}
		}

		//update all boxes
		foreach (Box box in Boxes)
		{
			if (box != null)
			{
				Vector3Int roomPosition;
				if (GetComponent<RoomLoader>().TryGetRoomPosition(box.Floor, box.Room, out roomPosition))
				{
					//local to global position
					Vector3 boxPosition = (Vector3)(box.BoundingUpper + box.BoundingLower) / 2000.0f + (Vector3)roomPosition / 1000.0f;
					boxPosition = new Vector3(boxPosition.x, -boxPosition.y, boxPosition.z);

					if (box.transform.position != boxPosition)
					{
						Vector3 offset = 1000.0f * (box.transform.position - boxPosition);
						float distance = new Vector3(Mathf.Round(offset.x), 0.0f, Mathf.Round(offset.z)).magnitude;
						box.LastOffset = Mathf.RoundToInt(distance);
						box.LastDistance += distance;
						box.transform.position = boxPosition;
					}

					//make actors appears slightly bigger than they are to be not covered by colliders
					Vector3 delta = Vector3.one;
					box.transform.localScale = (box.BoundingSize + delta) / 1000.0f;

					//make sure very small actors are visible
					box.transform.localScale = Vector3.Max(box.transform.localScale, Vector3.one * 0.1f);

					if (GameVersion == GameVersion.AITD1)
					{
						UpdateHotPointBox(box, roomPosition);
					}

					//camera target
					if(box.ID == cameraTargetID)
					{
						//check if player has moved
						if (box.transform.position.x != lastPlayerPosition.x || box.transform.position.z != lastPlayerPosition.z)
						{
							//center camera to player position
							GetComponent<RoomLoader>().CenterCamera(new Vector2(box.transform.position.x, box.transform.position.z));
							lastPlayerPosition = box.transform.position;
						}
					}

					//player
					bool isPlayer = box.ID == lastValidPlayerIndex;
					if (isPlayer)
					{
						//arrow follow player
						Arrow.transform.position = box.transform.position + new Vector3(0.0f, box.transform.localScale.y / 2.0f + 0.001f, 0.0f);

						//face camera
						float angle = box.Angles.y * 360.0f / 1024.0f;
						Arrow.transform.rotation = Quaternion.AngleAxis(90.0f, -Vector3.left);
						Arrow.transform.rotation *= Quaternion.AngleAxis((angle + 180.0f) % 360.0f, Vector3.forward);

						float minBoxScale = Mathf.Min(box.transform.localScale.x, box.transform.localScale.z);
						Arrow.transform.localScale = new Vector3(
							minBoxScale * 0.9f,
							minBoxScale * 0.9f,
							1.0f);

						//player is white
						box.Color = new Color32(255, 255, 255, 255);
						Arrow.AlwaysOnTop = Camera.main.orthographic;
						Player = box;
					}
					else
					{
						if (box.Slot == 0)
						{
							box.Color = new Color32(255, 255, 255, 255);
						}
						else
						{
							//other actors are green
							box.Color = new Color32(0, 128, 0, 255);
						}
					}

					if (GameVersion == GameVersion.AITD1)
					{
						UpdateWorldPosBox(box, roomPosition, isPlayer);
					}

					box.AlwaysOnTop = Camera.main.orthographic;
				}
				else
				{
					RemoveActor(box.Slot);
				}
			}
		}

		if (GameVersion == GameVersion.AITD1)
		{
			CurrentCamera = memory.ReadShort(entryPoint + 0x24056);
			CurrentCameraFloor = memory.ReadShort(entryPoint + 0x24058);
			CurrentCameraRoom = memory.ReadShort(entryPoint + 0x2405A);
		}

		if (ShowAITD1Vars)
		{
			allowInventory = memory.ReadShort(entryPoint + 0x19B6E) == 1;
			redrawFlag = memory.ReadShort(entryPoint + 0x19BC6);
			inHand = memory.ReadShort(entryPoint + 0x24054);

			//set by AITD when long running code is started (eg: loading ressource)
			saveTimerFlag = memory[entryPoint + 0x1B0FC] == 1;

			internalTimer1 = memory.ReadUnsignedInt(entryPoint + 0x19D12);
			internalTimer2 = memory.ReadUnsignedShort(entryPoint + 0x242E0);

			internalTimer1Frozen = memory.ReadUnsignedInt(entryPoint + 0x1B0F8);
			internalTimer2Frozen = memory.ReadUnsignedShort(entryPoint + 0x1B0F6);
		}
	}

	public uint Timer1
	{
		get
		{
			return saveTimerFlag ? internalTimer1Frozen : internalTimer1;
		}
	}

	public int Timer2
	{
		get
		{
			return saveTimerFlag ? internalTimer2Frozen : internalTimer2;
		}
	}

	public void UpdateArrowVisibility()
	{
		//arrow is only active if actors are active and player is active
		Arrow.gameObject.SetActive(Actors.activeSelf
			&& Player != null
			&& Player.gameObject.activeSelf
			&& Player.transform.localScale.magnitude > 0.01f);
	}

	void SwitchRoom(int floor, int room)
	{
		if (linkfloor != floor || linkroom != room)
		{
			linkfloor = floor;
			linkroom = room;

			GetComponent<RoomLoader>().RefreshRooms(linkfloor, linkroom);
		}
	}

	void RefreshCacheEntries(Dictionary<int, int> entries, int address)
	{
		entries.Clear();
		int cacheAddress = memory.ReadFarPointer(entryPoint + address);
		if (cacheAddress > 0 && cacheAddress < memory.Length)
		{
			int numEntries = Math.Min((int)memory.ReadUnsignedShort(cacheAddress + 16), 100);
			int baseAddress = memory.ReadFarPointer(cacheAddress + 18);

			for (int i = 0 ; i < numEntries ; i++)
			{
				int addr = cacheAddress + 22 + i * 10;
				int id = memory.ReadUnsignedShort(addr);
				int offset = memory.ReadUnsignedShort(addr + 2);
				entries[id] = baseAddress + offset;
			}
		}
	}

	void UpdateHotPointBox(Box box, Vector3Int roomPosition)
	{
		//hot point
		Box hotPoint = box.BoxHotPoint;

		if (box.ActionType == 2)
		{
			if (hotPoint == null)
			{
				hotPoint = Instantiate(BoxPrefab);
				hotPoint.name = "HotPoint";
				hotPoint.Color = new Color32(255, 0, 0, 255);
				Destroy(hotPoint.gameObject.GetComponent<BoxCollider>());
				box.BoxHotPoint = hotPoint;
			}

			Vector3 finalPos = (Vector3)(box.HotPosition + box.LocalPosition + box.Mod + roomPosition) / 1000.0f;
			finalPos = new Vector3(finalPos.x, -finalPos.y, finalPos.z);
			hotPoint.transform.position = finalPos;

			hotPoint.transform.localScale = Vector3.one * (box.HotBoxSize / 500.0f);
			hotPoint.AlwaysOnTop = Camera.main.orthographic;
		}
		else if (hotPoint != null)
		{
			Destroy(hotPoint.gameObject);
			box.BoxHotPoint = null;
		}
	}

	void UpdateWorldPosBox(Box box, Vector3Int roomPosition, bool isPlayer)
	{
		Vector3Int currentRoomPos;
		if (GetComponent<RoomLoader>().TryGetRoomPosition(CurrentCameraFloor, CurrentCameraRoom, out currentRoomPos))
		{
			Box worldPos = box.BoxWorldPos;
			Vector3Int boundingPos = box.WorldPosition + box.Mod + currentRoomPos - roomPosition;

			//worldpos unsync
			if (isPlayer &&
				  (boundingPos.x != box.BoundingPos.x ||
				   boundingPos.z != box.BoundingPos.z))
			{
				if (worldPos == null)
				{
					worldPos = Instantiate(BoxPrefab);
					worldPos.name = "WorldPos";
					worldPos.Color = new Color32(255, 0, 0, 128);
					Destroy(worldPos.gameObject.GetComponent<BoxCollider>());
					box.BoxWorldPos = worldPos;
				}

				Vector3 finalPos = (Vector3)(box.WorldPosition + box.Mod + currentRoomPos) / 1000.0f;
				float height = -(box.BoundingUpper.y + box.BoundingUpper.y) / 2000.0f;
				finalPos = new Vector3(finalPos.x, height + 0.001f, finalPos.z);
				worldPos.transform.position = finalPos;
				worldPos.transform.localScale = box.transform.localScale;
				worldPos.AlwaysOnTop = Camera.main.orthographic;
			}
			else if (worldPos != null)
			{
				Destroy(worldPos.gameObject);
				box.BoxWorldPos = null;
			}
		}
	}

	public void UpdateRightText()
	{
		RightText.Clear();
		if (Player != null)
		{
			float angle = Player.Angles.y * 360.0f / 1024.0f;
			float sideAngle = (angle + 45.0f) % 90.0f - 45.0f;

			RightText.Append("Position", Player.LocalPosition + Player.Mod);
			RightText.Append("Angle", "{0:N1} {1:N1}", angle, sideAngle);
		}

		if (ShowAITD1Vars || ShowAdditionalInfo)
		{
			if(Player != null) RightText.AppendLine();

			if (ShowAITD1Vars)
			{
				int calculatedFps = previousFrames.Sum(x => x.Key);
				TimeSpan totalDelayTS = TimeSpan.FromSeconds(totalDelay.Elapsed);
				uint timer1Delay = internalTimer1 - internalTimer1Frozen;
				int timer2Delay = internalTimer2 - internalTimer2Frozen;

				RightText.Append("Timer 1", !saveTimerFlag ? "{0}.{1:D2}" : "{0}.{1:D2} {2:D2}.{3:D2}", TimeSpan.FromSeconds(Timer1 / 60), Timer1 % 60, timer1Delay / 60 % 60, timer1Delay % 60);
				RightText.Append("Timer 2", !saveTimerFlag ? "{0}.{1:D2}" : "{0}.{1:D2} {2:D2}.{3:D2}", TimeSpan.FromSeconds(Timer2 / 60), Timer2 % 60, timer2Delay / 60 % 60, timer2Delay % 60);
				RightText.Append("FPS/Frame/Time", "{0}; {1}; {2} ms", calculatedFps, frameCounter, Mathf.RoundToInt(frameTimeElapsed * 1000));
				RightText.Append("Total delay/Delay", "{0:D2}:{1:D2}.{2:D3}; {3} ms", totalDelayTS.Minutes, totalDelayTS.Seconds, totalDelayTS.Milliseconds, Mathf.FloorToInt(lastDelay * 1000));
			}

			Vector3Int mousePosition = GetComponent<RoomLoader>().GetMousePosition(linkroom, linkfloor);
			RightText.Append("Cursor position", "{0} {1}", Mathf.Clamp(mousePosition.x, -32768, 32767), Mathf.Clamp(mousePosition.z, -32768, 32767));
			if(Player != null) RightText.Append("Last offset/dist", "{0}; {1}", Player.LastOffset, Mathf.RoundToInt(Player.LastDistance));

			if (ShowAITD1Vars)
			{
				RightText.Append("Allow inventory", "{0} ({1})", allowInventory ? "Yes" : "No", redrawFlag);
				RightText.Append("In hand", inHand);
			}
		}

		RightText.UpdateText();
	}

	void Update()
	{
		if (Input.GetKeyDown(KeyCode.Q))
		{
			totalDelay.Reset();
		}
		if (Input.GetKeyDown(KeyCode.W))
		{
			foreach (Box box in Boxes)
			{
				if (box != null)
				{
					box.LastDistance = 0.0f;
				}
			}
		}
		if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && GameVersion == GameVersion.AITD1 && ProcessMemory != null)
		{
			if (Input.GetKeyDown(KeyCode.Alpha1))
			{
				//internal timer 1
				byte[] buffer = new byte[4];
				buffer.Write(Timer1 - 60 * 5, 0);  //back 5 frames
				ProcessMemory.Write(buffer, entryPoint + 0x19D12, buffer.Length);
			}
			if (Input.GetKeyDown(KeyCode.Alpha2))
			{
				//internal timer 2
				byte[] buffer = new byte[2];
				buffer.Write((ushort)(Timer2 - 60 * 5), 0);  //back 5 frames
				ProcessMemory.Write(buffer, entryPoint + 0x242E0, buffer.Length);
			}
		}
	}

	public void RefreshCacheEntries()
	{
		if (ShowAITD1Vars)
		{
			RefreshCacheEntries(animIdToMemoryAddress, 0x218D3);
			RefreshCacheEntries(bodyIdToMemoryAddress, 0x218D7);
		}
	}

	public void CalculateFPS()
	{
		if (ProcessMemory == null)
		{
			return;
		}

		if (ShowAITD1Vars)
		{
			//fps
			int fps = memory.ReadShort(entryPoint + 0x19D18);

			//frames counter (reset to zero every second by AITD)
			int frames = memory.ReadShort(entryPoint + 0x2117C);

			//frame time
			if (frames != oldFrames)
			{
				oldFrames = frames;
				if(frames != 0)
				{
					frameTimeElapsed = frameTime.Elapsed;
					frameTime.Restart();
				}
			}

			//check how much frames elapsed since last time
			int diff;
			if (frames >= oldFramesCount)
			{
				diff = frames - oldFramesCount; //eg: 20 - 15
			}
			else
			{
				diff = fps - oldFramesCount + frames; //special case: eg: 60 - 58 + 3
			}
			oldFramesCount = frames;
			frameCounter += diff;

			float time = Time.time;
			if (diff > 0)
			{
				previousFrames.Enqueue(new KeyValuePair<int, float>(diff, time));
			}

			//remove any frame info older than one second
			while (previousFrames.Count > 0 &&
				previousFrames.Peek().Value < (time - 1.0f))
			{
				previousFrames.Dequeue();
			}
		}
	}

	public void CheckDelay()
	{
		if(ProcessMemory == null)
		{
			totalDelay.Stop();
			delayCounter.Stop();
			return;
		}

		if(ShowAITD1Vars)
		{
			if(delayCounter.Elapsed >= 0.1f) //100ms
			{
				lastDelay = delayCounter.Elapsed;
			}

			//check for large delays
			if (!saveTimerFlag)
			{
				delayCounter.Reset();
				totalDelay.Stop();
			}
			else
			{
				delayCounter.Start();
				totalDelay.Start();
			}
		}
	}

	void FixBoundingWrap(ref int a, ref int b)
	{
		if(a > b)
		{
			if(a < -b)
			{
				b += 65536;
			}
			else
			{
				a -= 65536;
			}
		}
	}

	#region SearchDOSBox

	int SearchDOSBoxProcess()
	{
		int? processId = Process.GetProcesses()
				.Where(x => GetProcessName(x).StartsWith("DOSBOX", StringComparison.InvariantCultureIgnoreCase))
				.Select(x => (int?)x.Id)
				.FirstOrDefault();

		if(processId.HasValue)
		{
			return processId.Value;
		}

		return -1;
	}

	string GetProcessName(Process process)
	{
		try
		{
			//could fail because not enough permissions (eg : admin process)
			return process.ProcessName;
		}
		catch
		{
			return string.Empty;
		}
	}

	bool TryGetMemoryReader(out ProcessMemory reader)
	{
		int processId = SearchDOSBoxProcess();
		if (processId != -1)
		{
			reader = new ProcessMemory(processId);
			reader.BaseAddress = reader.SearchFor16MRegion();
			if (reader.BaseAddress != -1)
			{
				return true;
			}

			reader.Close();
		}

		reader = null;
		return false;
	}

	bool TryGetExeEntryPoint(out int entryPoint)
	{
		int psp = memory.ReadUnsignedShort(0x0B30) * 16;
		if (psp > 0)
		{
			int exeSize = memory.ReadUnsignedShort(psp - 16 + 3) * 16;
			if (exeSize > 100 * 1024 && exeSize < 250 * 1024) //is AITD exe loaded yet?
			{
				entryPoint = psp + 0x100;
				return true;
			}
		}

		entryPoint = -1;
		return false;
	}

	bool FindActorsAddressAITD(GameVersion gameVersion)
	{
		ProcessMemory.Read(memory, 0, memory.Length);

		if (!TryGetExeEntryPoint(out entryPoint))
		{
			return false;
		}

		switch (gameVersion)
		{
			case GameVersion.AITD1:
				if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("CD Not Found")) == -1)
				{
					if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("USA.PAK")) != -1)
					{
						gameVersion = GameVersion.AITD1_DEMO;
					}
					else
					{
						gameVersion = GameVersion.AITD1_FLOPPY;
					}
				}
				break;

			case GameVersion.AITD2:
				if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("Not a CD-ROM drive")) == -1)
				{
					if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("BATL.PAK")) == -1)
					{
						gameVersion = GameVersion.AITD2_DEMO;
					}
					else
					{
						gameVersion = GameVersion.AITD2_FLOPPY;
					}
				}
				break;

			case GameVersion.AITD3:
				if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("AN3.PAK")) == -1)
				{
					gameVersion = GameVersion.AITD3_DEMO;
				}
				break;
		}

		GameVersion = gameVersion;
		gameConfig = gameConfigs[gameVersion];
		return true;
	}

	bool FindActorsAddressTimeGate(GameVersion gameVersion)
	{
		//scan range: 0x110000 (extended memory) - 0x300000 (3MB)
		byte[] pattern = Encoding.ASCII.GetBytes("HARD_DEC");
		int dataSegment = ProcessMemory.SearchForBytePattern(0x110000, 0x1F0000, buffer => Utils.IndexOf(buffer, pattern, 28, 16));

		if (dataSegment != -1)
		{
			ProcessMemory.Read(memory, dataSegment, memory.Length);
			if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("Time Gate not found")) == -1)
			{
				gameVersion = GameVersion.TIMEGATE_DEMO;
			}

			GameVersion = gameVersion;
			gameConfig = gameConfigs[gameVersion];
			ProcessMemory.Read(memory, dataSegment + gameConfig.ActorsPointer, 4);
			var result = memory.ReadUnsignedInt(0); //read pointer value
			if (result != 0)
			{
				ProcessMemory.BaseAddress += result;
				entryPoint = 0;
				return true;
			}
		}

		return false;
	}

	#endregion

	#region Room loader

	public bool LinkToDosBOX(int floor, int room, GameVersion gameVersion)
	{
		if (!TryGetMemoryReader(out ProcessMemory))
		{
			return false;
		}

		if (!FindActorsAddress(gameVersion))
		{
			ProcessMemory.Close();
			ProcessMemory = null;
			return false;
		}

		//force reload
		linkfloor = floor;
		linkroom = room;

		Player = null;
		lastValidPlayerIndex = -1;

		return true;
	}

	public bool FindActorsAddress(GameVersion gameVersion)
	{
		if (gameVersion == GameVersion.TIMEGATE)
		{
			return FindActorsAddressTimeGate(gameVersion);
		}

		return FindActorsAddressAITD(gameVersion);
	}

	public void ResetCamera(int floor, int room)
	{
		lastPlayerPosition = Vector3.zero;
		linkfloor = floor;
		linkroom = room;
	}

	public int GetActorMemoryAddress(int index)
	{
		return gameConfig.ActorsAddress + entryPoint + index * gameConfig.ActorStructSize;
	}

	public int GetActorSize()
	{
		return gameConfig.ActorStructSize;
	}

	public int GetObjectMemoryAddress(int index)
	{
		int objectAddress = memory.ReadFarPointer(entryPoint + 0x2400E);
		return objectAddress + index * 52;
	}

	public Box RefreshBoxUsingID(Box box, int boxId)
	{
		//make sure ID still match
		if(box != null && box.ID != boxId)
		{
			box = null;
		}

		if (box == null && boxId != -1)
		{
			//if actor is no more available (eg : after room switch) search for it
			foreach (Box b in Boxes)
			{
				if (b != null && b.ID == boxId)
				{
					box = b;
					break;
				}
			}
		}

		return box;
	}

	#endregion
}


text:
class AppConfigsController < ApplicationController
  authorize_resource class: false
  skip_before_action :seen_app_configs, only: [:edit]

  def edit
    @app_config = AppConfig.first || AppConfig.new
    @app_config.update_attribute(:viewed, true)
  end

  def update
    @app_config = AppConfig.first

    reset_tos = params[:app_config][:reset_tos_for_users]

    # check for require phone change and update users accordingly
    User.no_phone.update_all(missing_phone: true) if
      !@app_config.require_phone && params[:app_config][:require_phone] == '1'

    if @app_config.update_attributes(app_config_params)
      if reset_tos == '1'
        User.update_all(['terms_of_service_accepted = ?', false])
      end

      # TODO: Does this work? Checkbox shouldn't have value of 'on'??
      if params[:restore_favicon] == 'on'
        @app_config.favicon = nil
        @app_config.save
      end

      flash[:notice] = 'Application settings updated successfully.'
      redirect_to catalog_path
    else
      # flash[:error] = "Error saving application settings."
      render action: 'edit'
    end
  end

  private

  def app_config_params
    params.require(:app_config)
          .permit(:site_title, :admin_email, :department_name,
                  :contact_link_location, :home_link_text, :home_link_location,
                  :upcoming_checkin_email_body, :upcoming_checkin_email_active,
                  :upcoming_checkout_email_body,
                  :upcoming_checkout_email_active,
                  :overdue_checkin_email_body, :overdue_checkin_email_active,
                  :reservation_confirmation_email_active, :request_text,
                  :enable_new_users, :res_exp_time, :blackout_exp_time,
                  :send_notifications_for_deleted_missed_reservations,
                  :deleted_missed_reservation_email_body, :enable_guests,
                  :default_per_cat_page, :terms_of_service, :favicon,
                  :checkout_persons_can_edit, :enable_renewals,
                  :override_on_create, :override_at_checkout, :require_phone,
                  :notify_admin_on_create, :disable_user_emails,
                  :autodeactivate_on_archive)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package io.cattle.platform.process.common.handler;

import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessHandler;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.object.util.ObjectUtils;

public abstract class AbstractGenericObjectProcessLogic implements ProcessHandler {

    public abstract String getKind();

    @Override
    public final HandlerResult handle(ProcessState state, ProcessInstance process) {
        if (getKind().equals(ObjectUtils.getKind(state.getResource()))) {
            return handleKind(state, process);
        }

        return null;
    }

    protected abstract HandlerResult handleKind(ProcessState state, ProcessInstance process);

}


text:
package org.zaproxy.zap.extension.accessControl;

import java.awt.Dimension;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.db.RecordContext;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.ExtensionHookView;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.extension.report.ReportGenerator;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.view.View;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.zaproxy.zap.extension.accessControl.AccessControlScannerThread.AccessControlResultEntry;
import org.zaproxy.zap.extension.accessControl.AccessControlScannerThread.AccessControlScanStartOptions;
import org.zaproxy.zap.extension.accessControl.view.AccessControlScanOptionsDialog;
import org.zaproxy.zap.extension.accessControl.view.AccessControlStatusPanel;
import org.zaproxy.zap.extension.accessControl.view.ContextAccessControlPanel;
import org.zaproxy.zap.extension.authentication.ExtensionAuthentication;
import org.zaproxy.zap.extension.authorization.ExtensionAuthorization;
import org.zaproxy.zap.extension.users.ExtensionUserManagement;
import org.zaproxy.zap.model.Context;
import org.zaproxy.zap.model.ContextDataFactory;
import org.zaproxy.zap.scan.BaseScannerThreadManager;
import org.zaproxy.zap.users.User;
import org.zaproxy.zap.view.AbstractContextPropertiesPanel;
import org.zaproxy.zap.view.ContextPanelFactory;

/**
 * An extension that adds a set of tools that allows users to test Access Control issues in web
 * applications.
 */
public class ExtensionAccessControl extends ExtensionAdaptor implements SessionChangedListener,
		ContextPanelFactory, ContextDataFactory {

	private static Logger log = Logger.getLogger(ExtensionAccessControl.class);

	public static final String CONTEXT_CONFIG_ACCESS_RULES = Context.CONTEXT_CONFIG + ".accessControl.rules";
	public static final String CONTEXT_CONFIG_ACCESS_RULES_RULE = CONTEXT_CONFIG_ACCESS_RULES + ".rule";

	/** The NAME of the access control testing extension. */
	public static final String NAME = "ExtensionAccessControl";

	/** The list of extensions this depends on. */
	private static final List<Class<?>> EXTENSION_DEPENDENCIES;
	static {
		// Prepare a list of Extensions on which this extension depends
		List<Class<?>> dependencies = new ArrayList<>(1);
		dependencies.add(ExtensionUserManagement.class);
		dependencies.add(ExtensionAuthentication.class);
		dependencies.add(ExtensionAuthorization.class);
		EXTENSION_DEPENDENCIES = Collections.unmodifiableList(dependencies);
	}

	/** The status panel used by the extension. */
	private AccessControlStatusPanel statusPanel;

	/** The map of context panels shown in the Session Properties Dialog. */
	private Map<Integer, ContextAccessControlPanel> contextPanelsMap;

	/** The scan dialog used to specify the scan options. */
	private AccessControlScanOptionsDialog customScanDialog;

	/** The mapping of Access Rules Managers to Contexts. */
	private Map<Integer, ContextAccessRulesManager> contextManagers;

	/** The scanner threads manager. */
	private AccessControlScannerThreadManager threadManager;

	public ExtensionAccessControl() {
		super(NAME);
		this.setOrder(601);
		this.threadManager = new AccessControlScannerThreadManager();
		this.contextPanelsMap = new HashMap<>();
		this.contextManagers = new HashMap<>();
	}

	@Override
	public void hook(ExtensionHook extensionHook) {
		super.hook(extensionHook);
		// Register this where needed
		Model.getSingleton().addContextDataFactory(this);
		extensionHook.addSessionListener(this);

		if (getView() != null) {
			ExtensionHookView viewHook = extensionHook.getHookView();
			viewHook.addStatusPanel(getStatusPanel());
			getView().addContextPanelFactory(this);
		}
	}

	@Override
	public boolean canUnload() {
		return true;
	}

	@Override
	public String getAuthor() {
		return Constant.ZAP_TEAM;
	}

	@Override
	public String getDescription() {
		return Constant.messages.getString("accessControl.desc");
	}

	@Override
	public URL getURL() {
		try {
			return new URL(Constant.ZAP_EXTENSIONS_PAGE);
		} catch (MalformedURLException e) {
			return null;
		}
	}

	@Override
	public List<Class<?>> getDependencies() {
		return EXTENSION_DEPENDENCIES;
	}

	private AccessControlStatusPanel getStatusPanel() {
		if (statusPanel == null) {
			statusPanel = new AccessControlStatusPanel(this, threadManager);
		}
		return statusPanel;
	}

	@Override
	public AbstractContextPropertiesPanel getContextPanel(Context context) {
		ContextAccessControlPanel panel = this.contextPanelsMap.get(context.getIndex());
		if (panel == null) {
			panel = new ContextAccessControlPanel(this, context.getIndex());
			this.contextPanelsMap.put(context.getIndex(), panel);
		}
		return panel;
	}

	/**
	 * Shows the options dialog containing configuration needed for starting a scan.
	 *
	 * @param context the context
	 */
	public void showScanOptionsDialog(Context context) {
		if (customScanDialog == null) {
			customScanDialog = new AccessControlScanOptionsDialog(this, View.getSingleton().getMainFrame(),
					new Dimension(700, 500));
		}
		if (customScanDialog.isVisible()) {
			return;
		}
		customScanDialog.init(context);
		customScanDialog.setVisible(true);
	}

	/**
	 * Starts an access control testing scan.
	 *
	 * @param startOptions the start options
	 */
	public void startScan(AccessControlScanStartOptions startOptions) {
		int contextId = startOptions.targetContext.getIndex();
		AccessControlScannerThread scannerThread = threadManager.getScannerThread(contextId);
		if (scannerThread.isRunning()) {
			log.warn("Access control scan already running for context: " + contextId);
			throw new IllegalStateException("A scan is already running for context: " + contextId);
		}

		scannerThread = threadManager.recreateScannerThreadIfHasRun(contextId);
		if (getView() != null) {
			scannerThread.addScanListener(getStatusPanel());
		}
		scannerThread.setStartOptions(startOptions);
		scannerThread.start();
	}

	/**
	 * The implementation for a {@link BaseScannerThreadManager} that initializes an
	 * {@link AccessControlScannerThread}.
	 */
	private class AccessControlScannerThreadManager extends
			BaseScannerThreadManager<AccessControlScannerThread> {

		@Override
		public AccessControlScannerThread createNewScannerThread(int contextId) {
			return new AccessControlScannerThread(contextId, ExtensionAccessControl.this);
		}
	}

	@Override
	public void sessionChanged(Session session) {
		if (getView() != null) {
			getStatusPanel().contextsChanged();
			getStatusPanel().reset();
		}
		// If the session has changed, make sure we reload any ContextTrees for the existing context
		// managers
		// NOTE: if https://github.com/zaproxy/zaproxy/issues/1316 is fixed, this could
		// move to the "loadContextData()" method
		if (session != null) {
			for (Context c : session.getContexts()) {
				ContextAccessRulesManager m = contextManagers.get(c.getIndex());
				if (m != null) {
					m.reloadContextSiteTree(session);
				}
			}
		}
	}

	@Override
	public void sessionAboutToChange(Session session) {
	}

	@Override
	public void sessionScopeChanged(Session session) {
	}

	@Override
	public void sessionModeChanged(Mode mode) {
	}

	private Document generateLastScanXMLReport(int contextId) throws ParserConfigurationException {
		// Prepare the document and the root element
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.newDocument();

		Element rootElement = doc.createElement("report");
		doc.appendChild(rootElement);

		// Localization
		Element localizationElement = doc.createElement("localization");
		rootElement.appendChild(localizationElement);
		ReportGenerator.addChildTextNode(doc, localizationElement, "title",
				Constant.messages.getString("accessControl.report.title"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "url",
				Constant.messages.getString("accessControl.report.table.header.url"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "method",
				Constant.messages.getString("accessControl.report.table.header.method"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "authorization",
				Constant.messages.getString("accessControl.report.table.header.authorization"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "access-control",
				Constant.messages.getString("accessControl.report.table.header.accessControl"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "show-all",
				Constant.messages.getString("accessControl.report.button.all"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "show-valid",
				Constant.messages.getString("accessControl.report.button.valid"));
		ReportGenerator.addChildTextNode(doc, localizationElement, "show-illegal",
				Constant.messages.getString("accessControl.report.button.illegal"));
		final String UNAUTHENICATED_USER_NAME = Constant.messages
				.getString("accessControl.scanOptions.unauthenticatedUser");
		final String AUTHORIZED_STRING = Constant.messages
				.getString("accessControl.report.table.field.authorized");
		final String UNAUTHORIZED_STRING = Constant.messages
				.getString("accessControl.report.table.field.unauthorized");

		AccessControlScannerThread scanThread = threadManager.getScannerThread(contextId);
		List<AccessControlResultEntry> scanResults = scanThread.getLastScanResults();

		// If there are no scan results (i.e. hasn't run yet, return the document as is at this
		// point
		if (scanResults == null) {
			return doc;
		}

		// Create a sorted list of users based on id (null/unauthenticated user first)
		List<User> users = new ArrayList<>(scanThread.getStartOptions().targetUsers);
		Collections.sort(users, new Comparator<User>() {
			@Override
			public int compare(User o1, User o2) {
				if (o1 == o2) {
					return 0;
				}
				if (o1 == null) {
					return -1;
				}
				if (o2 == null) {
					return 1;
				}
				return o1.getId() - o2.getId();
			}
		});
		// ... and add the list of users in the report
		Element usersElement = doc.createElement("users");
		rootElement.appendChild(usersElement);
		for (User user : users) {
			Element userElement = doc.createElement("user");
			usersElement.appendChild(userElement);
			userElement.setAttribute("name", user == null ? UNAUTHENICATED_USER_NAME : user.getName());
			userElement.setAttribute("id", Integer.toString(user == null ? -1 : user.getId()));
		}

		// Prepare a comparator that keeps scan results in order based on the user id
		Comparator<AccessControlResultEntry> resultsComparator = new Comparator<AccessControlScannerThread.AccessControlResultEntry>() {
			@Override
			public int compare(AccessControlResultEntry o1, AccessControlResultEntry o2) {
				if (o1.getUser() == o2.getUser()) {
					return 0;
				}
				if (o1.getUser() == null) {
					return -1;
				}
				if (o2.getUser() == null) {
					return 1;
				}
				return o1.getUser().getId() - o2.getUser().getId();
			}
		};
		Map<String, TreeSet<AccessControlResultEntry>> uriResults = new HashMap<>(scanResults.size());
		TreeSet<AccessControlResultEntry> uriResultsSet;
		for (AccessControlResultEntry result : scanResults) {
			uriResultsSet = uriResults.get(result.getUri());
			if (uriResultsSet == null) {
				uriResultsSet = new TreeSet<>(resultsComparator);
				uriResults.put(result.getUri(), uriResultsSet);
			}
			uriResultsSet.add(result);
		}

		// Actually add the results nodes
		Element resultsElement = doc.createElement("results");
		rootElement.appendChild(resultsElement);
		for (TreeSet<AccessControlResultEntry> uriResultSet : uriResults.values()) {
			// For each result node...
			Element uriElement = doc.createElement("result");
			resultsElement.appendChild(uriElement);
			// ... add the URI and the HTTP method ...
			AccessControlResultEntry firstEntry = uriResultSet.first();
			uriElement.setAttribute("uri", firstEntry.getUri());
			uriElement.setAttribute("method", firstEntry.getMethod());
			// ... and for every result entry, add the necessary data
			for (AccessControlResultEntry result : uriResultSet) {
				Element userResultElement = doc.createElement("userResult");
				uriElement.appendChild(userResultElement);
				if (result.getUser() == null) {
					userResultElement.setAttribute("name", UNAUTHENICATED_USER_NAME);
				} else {
					userResultElement.setAttribute("name", result.getUser().getName());
				}
				userResultElement.setAttribute("authorization",
						result.isRequestAuthorized() ? AUTHORIZED_STRING : UNAUTHORIZED_STRING);
				userResultElement.setAttribute("access-control", result.getResult().name());
				userResultElement.setAttribute("access-control-localized", result.getResult().toString());
			}
		}

		return doc;
	}

	/**
	 * Generate an access control report for the provided context id and save it in the output file.
	 *
	 * @param contextId the context id
	 * @param outputFile the output file
	 * @return the file
	 */
	public File generateAccessControlReport(int contextId, File outputFile)
			throws ParserConfigurationException {
		log.debug("Generating report for context " + contextId + " to: " + outputFile);

		// The path for the XSL file
		File xslFile = new File(Constant.getZapHome(), "xml" + File.separator + "reportAccessControl.html.xsl");

		// Generate the report
		return ReportGenerator.XMLToHtml(generateLastScanXMLReport(contextId), xslFile.getAbsolutePath(),
				outputFile);

	}

	/**
	 * Gets the access rules manager for a Context.
	 *
	 * @param contextId the context id
	 * @return the user access rules manager
	 */
	public ContextAccessRulesManager getContextAccessRulesManager(int contextId) {
		ContextAccessRulesManager manager = contextManagers.get(contextId);
		if (manager == null) {
			manager = new ContextAccessRulesManager(Model.getSingleton().getSession().getContext(contextId));
			contextManagers.put(contextId, manager);
		}
		return manager;
	}

	/**
	 * Gets the access rules manager for a Context.
	 *
	 * @param context the context
	 * @return the user access rules manager
	 */
	public ContextAccessRulesManager getContextAccessRulesManager(Context context) {
		ContextAccessRulesManager manager = contextManagers.get(context.getIndex());
		if (manager == null) {
			manager = new ContextAccessRulesManager(context);
			contextManagers.put(context.getIndex(), manager);
		}
		return manager;
	}

	@Override
	public void discardContexts() {
		this.contextPanelsMap.clear();
		this.contextManagers.clear();
		this.threadManager.stopAllScannerThreads();
		this.threadManager.clearThreads();
	}

	@Override
	public void discardContext(Context ctx) {
		this.contextPanelsMap.remove(ctx.getIndex());
		this.contextManagers.remove(ctx.getIndex());
	}

	@Override
	public void loadContextData(Session session, Context context) {
		// Read the serialized rules for this context
		List<String> serializedRules = null;
		try {
			serializedRules = session.getContextDataStrings(context.getIndex(),
					RecordContext.TYPE_ACCESS_CONTROL_RULE);
		} catch (Exception e) {
			log.error("Unable to load access control rules for context: " + context.getIndex(), e);
			return;
		}

		// Load the rules for this context
		if (serializedRules != null) {
			ContextAccessRulesManager contextManager = getContextAccessRulesManager(context);
			for (String serializedRule : serializedRules) {
				contextManager.importSerializedRule(serializedRule);
			}
		}
	}

	@Override
	public void persistContextData(Session session, Context context) {
		try {
			ContextAccessRulesManager contextManager = contextManagers.get(context.getIndex());
			if (contextManager != null) {
				List<String> serializedRules = contextManager.exportSerializedRules();
				// Save only if we have anything to save
				if (!serializedRules.isEmpty()) {
					session.setContextData(context.getIndex(), RecordContext.TYPE_ACCESS_CONTROL_RULE,
							serializedRules);
					return;
				}
			}

			// If we don't have any rules, force delete any previous values
			session.clearContextDataForType(context.getIndex(), RecordContext.TYPE_ACCESS_CONTROL_RULE);
		} catch (Exception e) {
			log.error("Unable to persist access rules for context: " + context.getIndex(), e);
		}
	}

	@Override
	public void exportContextData(Context ctx, Configuration config) {
		ContextAccessRulesManager contextManager = contextManagers.get(ctx.getIndex());
		if (contextManager != null) {
			List<String> serializedRules = contextManager.exportSerializedRules();
			config.setProperty(CONTEXT_CONFIG_ACCESS_RULES_RULE, serializedRules);
		}
	}

	@Override
	public void importContextData(Context ctx, Configuration config) throws ConfigurationException {
		List<Object> serializedRules = config.getList(CONTEXT_CONFIG_ACCESS_RULES_RULE);
		if (serializedRules != null) {
			ContextAccessRulesManager contextManager = getContextAccessRulesManager(ctx);
			// Make sure we reload the context tree
			contextManager.reloadContextSiteTree(Model.getSingleton().getSession());
			for (Object serializedRule : serializedRules) {
				contextManager.importSerializedRule(serializedRule.toString());
			}
		}
	}

}


text:
from eve.tests import TestBase
import simplejson as json
from eve.utils import api_prefix

class TestRenders(TestBase):

    def test_default_render(self):
        r = self.test_client.get('/')
        self.assertEqual(r.content_type, 'application/json')

    def test_json_render(self):
        r = self.test_client.get('/', headers=[('Accept', 'application/json')])
        self.assertEqual(r.content_type, 'application/json')

    def test_xml_render(self):
        r = self.test_client.get('/', headers=[('Accept', 'application/xml')])
        self.assertTrue('application/xml' in r.content_type)

    def test_xml_url_escaping(self):
        r = self.test_client.get('%s?max_results=1' % self.known_resource_url,
                                 headers=[('Accept', 'application/xml')])
        self.assertTrue(b'&' in r.get_data())

    def test_unknown_render(self):
        r = self.test_client.get('/', headers=[('Accept', 'application/html')])
        self.assertEqual(r.content_type, 'application/json')

    def test_CORS(self):
        r = self.test_client.get('/')
        self.assertFalse('Access-Control-Allow-Origin' in r.headers)
        self.assertFalse('Access-Control-Allow-Methods' in r.headers)
        self.assertFalse('Access-Control-Allow-Max-Age' in r.headers)

        self.app.config['X_DOMAINS'] = '*'
        r = self.test_client.get('/', headers=[('Origin',
                                                'http://example.com')])
        self.assertEqual(r.headers['Access-Control-Allow-Origin'], '*')

        self.app.config['X_DOMAINS'] = ['http://example.com',
                                        'http://1on1.com']
        r = self.test_client.get('/', headers=[('Origin',
                                                'http://example.com')])
        self.assertEqual(r.headers['Access-Control-Allow-Origin'],
                         'http://example.com, http://1on1.com')

        self.assertTrue('Access-Control-Allow-Origin' in r.headers)
        self.assertTrue('Access-Control-Allow-Max-Age' in r.headers)

        r = self.test_client.get('/', headers=[('Origin',
                                                'http://not_an_example.com')])
        self.assertEqual(r.headers['Access-Control-Allow-Origin'],
                         'http://example.com, http://1on1.com')

    def test_CORS_OPTIONS(self, url='/', methods=[]):
        r = self.test_client.open(url, method='OPTIONS')
        self.assertFalse('Access-Control-Allow-Origin' in r.headers)
        self.assertFalse('Access-Control-Allow-Methods' in r.headers)
        self.assertFalse('Access-Control-Allow-Max-Age' in r.headers)
        self.assert200(r.status_code)

        self.app.config['X_DOMAINS'] = '*'
        r = self.test_client.open(url, method='OPTIONS',
                                  headers=[('Origin', 'http://example.com')])
        self.assert200(r.status_code)
        self.assertEqual(r.headers['Access-Control-Allow-Origin'], '*')
        for m in methods:
            self.assertTrue(m in r.headers['Access-Control-Allow-Methods'])

        self.app.config['X_DOMAINS'] = ['http://example.com',
                                        'http://1on1.com']
        r = self.test_client.open(url, method='OPTIONS',
                                  headers=[('Origin', 'http://example.com')])
        self.assert200(r.status_code)
        self.assertEqual(r.headers['Access-Control-Allow-Origin'],
                         'http://example.com, http://1on1.com')

        for m in methods:
            self.assertTrue(m in r.headers['Access-Control-Allow-Methods'])

        self.assertTrue('Access-Control-Allow-Origin' in r.headers)
        self.assertTrue('Access-Control-Allow-Max-Age' in r.headers)

        r = self.test_client.get(url, headers=[('Origin',
                                                'http://not_an_example.com')])
        self.assert200(r.status_code)
        self.assertEqual(r.headers['Access-Control-Allow-Origin'],
                         'http://example.com, http://1on1.com')
        for m in methods:
            self.assertTrue(m in r.headers['Access-Control-Allow-Methods'])

    def test_CORS_OPTIONS_resources(self):
        prefix = api_prefix(self.app.config['URL_PREFIX'],
                            self.app.config['API_VERSION'])

        for resource, settings in self.app.config['DOMAIN'].items():

            # resource endpoint
            url = '%s/%s/' % (prefix, settings['url'])
            methods = settings['resource_methods'] + ['OPTIONS']
            self.test_CORS_OPTIONS(url, methods)

    def test_CORS_OPTIONS_item(self):
        prefix = api_prefix(self.app.config['URL_PREFIX'],
                            self.app.config['API_VERSION'])

        url = '%s%s' % (prefix, self.item_id_url)
        methods = (self.domain[self.known_resource]['resource_methods'] +
                   ['OPTIONS'])
        self.test_CORS_OPTIONS(url, methods)
        url = '%s%s/%s' % (prefix, self.known_resource_url, self.item_ref)
        methods = ['GET', 'OPTIONS']
        self.test_CORS_OPTIONS(url, methods)

class TestEventHooks(TestBase):
    #TODO not sure this is the right place for this class really.

    def setUp(self):
        super(TestEventHooks, self).setUp()
        self.passed = False
        self.callback_value = None
        self.documents = None

    def test_on_GET(self):
        def general_hook(resource, request, payload):
            self.callback_value = resource
        self.app.on_GET += general_hook
        # homepage
        self.test_client.get('/')
        self.assertEqual(self.callback_value, None)
        # resource endpoint
        self.test_client.get(self.known_resource_url)
        self.assertEqual(self.callback_value, self.known_resource)
        # document endpoint
        self.test_client.get(self.item_id_url)
        self.assertEqual(self.callback_value, self.known_resource)

    def test_GET_resource(self):
        def resource_hook(request, payload):
            self.passed = True
        self.app.on_GET_contacts += resource_hook
        # resource endpoint
        self.test_client.get(self.known_resource_url)
        self.assertTrue(self.passed)
        # document endpoint
        self.passed = False
        self.test_client.get(self.item_id_url)
        self.assertTrue(self.passed)

    def test_on_POST(self):
        def general_hook(resource, request, payload):
            self.callback_value = resource
        self.app.on_POST += general_hook
        self.post()
        self.assertEqual(self.callback_value, self.known_resource)

    def test_on_POST_resource(self):
        def resource_hook(request, payload):
            self.passed = True
        self.app.on_POST_contacts += resource_hook
        self.post()
        self.assertTrue(self.passed)

    def test_on_PATCH(self):
        def general_hook(resource, request, payload):
            self.callback_value = resource
        self.app.on_PATCH += general_hook
        self.patch()
        self.assertEqual(self.callback_value, self.known_resource)

    def test_on_PATCH_resource(self):
        def resource_hook(request, payload):
            self.passed = True
        self.app.on_PATCH_contacts += resource_hook
        self.patch()
        self.assertTrue(self.passed)

    def test_on_PUT(self):
        def general_hook(resource, request, payload):
            self.callback_value = resource
        self.app.on_PUT += general_hook
        self.put()
        self.assertEqual(self.callback_value, self.known_resource)

    def test_on_PUT_resource(self):
        def resource_hook(request, payload):
            self.passed = True
        self.app.on_PUT_contacts += resource_hook
        self.put()
        self.assertTrue(self.passed)

    def test_on_DELETE(self):
        def general_hook(resource, request, payload):
            self.callback_value = resource
        self.app.on_DELETE += general_hook
        self.delete()
        self.assertEqual(self.callback_value, self.known_resource)

    def test_on_DELETE_resource(self):
        def resource_hook(request, payload):
            self.passed = True
        self.app.on_DELETE_contacts += resource_hook
        self.delete()
        self.assertTrue(self.passed)

    def test_on_insert_POST(self):
        def general_hook(resource, documents):
            self.assertEqual(resource, self.known_resource)
            self.assertEqual(len(documents), 1)
            self.passed = True
        self.app.on_insert += general_hook
        self.post()
        self.assertTrue(self.passed)

    def test_on_insert_PUT(self):
        def general_hook(resource, documents):
            self.assertEqual(resource, self.known_resource)
            self.assertEqual(len(documents), 1)
            self.passed = True
        self.app.on_insert += general_hook
        self.put()
        self.assertTrue(self.passed)

    def test_on_insert_resource_POST(self):
        def resource_hook(documents):
            self.assertEqual(len(documents), 1)
            self.passed = True
        self.app.on_insert_contacts += resource_hook
        self.post()
        self.assertTrue(self.passed)

    def test_on_insert_resource_PUT(self):
        def resource_hook(documents):
            self.assertEqual(len(documents), 1)
            self.passed = True
        self.app.on_insert_contacts += resource_hook
        self.put()
        self.assertTrue(self.passed)

    def test_on_fetch(self):
        def general_hook(resource, documents):
            self.assertEqual(resource, self.known_resource)
            self.assertEqual(len(documents), 25)
            self.passed = True
        self.app.on_fetch_resource += general_hook
        self.test_client.get(self.known_resource_url)
        self.assertTrue(self.passed)

    def test_on_fetch_resource(self):
        def resource_hook(documents):
            self.assertEqual(len(documents), 25)
            self.passed = True
        self.app.on_fetch_resource_contacts += resource_hook
        self.test_client.get(self.known_resource_url)
        self.assertTrue(self.passed)

    def test_on_fetch_item(self):
        def item_hook(resource, _id, document):
            self.assertEqual(str(_id), self.item_id)
            self.passed = True
        self.app.on_fetch_item += item_hook
        self.test_client.get(self.item_id_url)
        self.assertTrue(self.passed)

    def post(self, extra=None):
        headers = [('Content-Type', 'application/json')]
        data = json.dumps({"ref": "0123456789012345678901234"})
        if extra:
            headers.extend(extra)
        self.test_client.post(self.known_resource_url, data=data,
                              headers=headers)

    def patch(self):
        headers = [('Content-Type', 'application/json'),
                   ('If-Match', self.item_etag)]
        data = json.dumps({"ref": "i'm unique"})
        self.test_client.patch(self.item_id_url, data=data, headers=headers)

    def delete(self):
        self.test_client.delete(self.item_id_url, headers=[('If-Match',
                                                            self.item_etag)])

    def put(self):
        headers = [('Content-Type', 'application/json'),
                   ('If-Match', self.item_etag)]
        data = json.dumps({"ref": "0123456789012345678901234"})
        self.test_client.put(self.item_id_url, data=data, headers=headers)


text:
#include "RedisWatcher.h"

// states for processes
#define PROC_RUNNING    1
#define PROC_UNKNOWN    2
#define PROC_FAILED     3

// failure state for process
typedef struct _ProcHistory
{
    unsigned long StartTime;
    unsigned long StopTime;
    unsigned long FastFailCount;
} ProcHistory;

// restart policy from configuration
typedef struct _RestartPolicy
{
    unsigned long FastFailRetries;
    unsigned long FastFailMs;     // if process fails within this time, it failed during start
} RestartPolicy;

// Process state and configuration
typedef struct _ProcInstance
{
    wchar_t * WorkingDir;
    wchar_t * CmdParam;
    BOOL    SaveOutput;
    DWORD   RunMode;
    wchar_t * CmdLine;
    int     ProcessId;
    HANDLE  ProcessHandle;
    HANDLE  ProcessWaitHandle;
    int     State;
    ProcHistory History;
} ProcInstance;

// Set of processes
typedef struct _ProcList
{
    int     NumInstances;
    ProcInstance * Instances;
} ProcList;

// Configuration and processes
typedef struct _WatcherConfig
{
    wchar_t * ExecutableName;
    wchar_t * ExecutablePath;
    RestartPolicy Policy;
    ProcList ConfiguredInstances;
} WatcherConfig;

// method declarations

// High level start and stop
VOID SvcInstall();
void SvcStart();
BOOL WatcherStart(wchar_t * path);
void WatcherStop();

// initialize after loading or reloading configuration
void initialize(WatcherConfig * watchConfig);
void updateConfig(WatcherConfig * watchConfig);
void cleanup();

// configuration methods
WatcherConfig * parseConfig(wchar_t * configPath);
void freeConfig(WatcherConfig * config);
void startMonitorConfigFile(wchar_t * configPath);
void stopMonitorConfigFile();

// utility methods
void Lock();
void Unlock();
BOOL CopyString(wchar_t * value, wchar_t ** dest);
BOOL CombineFilePath(wchar_t * path, wchar_t * filename, wchar_t ** fullpath);
BOOL MakeAbsolute(wchar_t * filename, wchar_t ** fullpath);
BOOL GetCurrentDir(wchar_t ** fullpath);
BOOL GetModulePath(wchar_t ** fullpath);
wchar_t * Trim(wchar_t * buf);


text:
package io.dropwizard.jetty;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jetty9.InstrumentedConnectionFactory;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.util.DataSize;
import io.dropwizard.util.DataSizeUnit;
import io.dropwizard.util.Duration;
import io.dropwizard.validation.MinDataSize;
import io.dropwizard.validation.MinDuration;
import io.dropwizard.validation.PortRange;
import org.eclipse.jetty.http.CookieCompliance;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.io.ArrayByteBufferPool;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.ProxyConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ArrayUtil;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.util.thread.ThreadPool;

import javax.annotation.Nullable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.valueextraction.Unwrapping;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.codahale.metrics.MetricRegistry.name;

/**
 * Builds HTTP connectors.
 *
 *

 * Configuration Parameters:
 *

 *

 *         Name
 *         Default
 *         Description
 *

 *

 *         {@code port}
 *         8080
 *         The TCP/IP port on which to listen for incoming connections.
 *

 *

 *         {@code bindHost}
 *         (none)
 *         The hostname to bind to.
 *

 *

 *         {@code inheritChannel}
 *         false
 *
 *             Whether this connector uses a channel inherited from the JVM.
 *             Use it with Server::Starter,
 *             to launch an instance of Jetty on demand.
 *
 *

 *

 *         {@code headerCacheSize}
 *         512 bytes
 *         The size of the header field cache.
 *

 *

 *         {@code outputBufferSize}
 *         32KiB
 *
 *             The size of the buffer into which response content is aggregated before being sent to
 *             the client.  A larger buffer can improve performance by allowing a content producer
 *             to run without blocking, however larger buffers consume more memory and may induce
 *             some latency before a client starts processing the content.
 *
 *

 *

 *         {@code maxRequestHeaderSize}
 *         8KiB
 *
 *             The maximum allowed size in bytes for the HTTP request line and HTTP request headers.
 *             Larger headers will allow for more and/or larger cookies plus larger form content
 *             encoded in a URL. However, larger headers consume more memory and can make a server
 *             more vulnerable to denial of service attacks.
 *
 *

 *

 *         {@code maxResponseHeaderSize}
 *         8KiB
 *
 *             The maximum size of a response header. Larger headers will allow for more and/or
 *             larger cookies and longer HTTP headers (eg for redirection).  However, larger headers
 *             will also consume more memory.
 *
 *

 *

 *         {@code inputBufferSize}
 *         8KiB
 *         The size of the per-connection input buffer.
 *

 *

 *         {@code idleTimeout}
 *         30 seconds
 *
 *             The maximum idle time for a connection, which roughly translates to the
 *             {@link java.net.Socket#setSoTimeout(int)} call, although with NIO implementations
 *             other mechanisms may be used to implement the timeout.
 *

 *             The max idle time is applied:
 *

 *
When waiting for a new message to be received on a connection

 *
When waiting for a new message to be sent on a connection

 *

 *

 *             This value is interpreted as the maximum time between some progress being made on the
 *             connection. So if a single byte is read or written, then the timeout is reset.
 *
 *

 *

 *         {@code minBufferPoolSize}
 *         64 bytes
 *         The minimum size of the buffer pool.
 *

 *

 *         {@code bufferPoolIncrement}
 *         1KiB
 *         The increment by which the buffer pool should be increased.
 *

 *

 *         {@code maxBufferPoolSize}
 *         64KiB
 *         The maximum size of the buffer pool.
 *

 *

 *         {@code acceptorThreads}
 *         (Jetty's default)
 *         The number of worker threads dedicated to accepting connections.
 *         By default is max(1, min(4, #CPUs/8)).
 *

 *

 *         {@code selectorThreads}
 *         (Jetty's default)
 *         The number of worker threads dedicated to sending and receiving data.
 *         By default is max(1, min(4, #CPUs/2)).
 *

 *

 *         {@code acceptQueueSize}
 *         (OS default)
 *         The size of the TCP/IP accept queue for the listening socket.
 *

 *

 *         {@code reuseAddress}
 *         true
 *         Whether or not {@code SO_REUSEADDR} is enabled on the listening socket.
 *

 *

 *         {@code useServerHeader}
 *         false
 *         Whether or not to add the {@code Server} header to each response.
 *

 *

 *         {@code useDateHeader}
 *         true
 *         Whether or not to add the {@code Date} header to each response.
 *

 *

 *         {@code minResponseDataPerSecond}
 *         0 bytes
 *
 *             The minimum response data rate in bytes per second; or <=0 for no limit
 *
 *

 *

 *         {@code minRequestDataPerSecond}
 *         0 bytes
 *
 *             The minimum request data rate in bytes per second; or <=0 for no limit
 *
 *

 *

 *         {@code useForwardedHeaders}
 *         false
 *
 *             Whether or not to look at {@code X-Forwarded-*} headers added by proxies. See
 *             {@link ForwardedRequestCustomizer} for details.
 *
 *

 *

 *         {@code useProxyProtocol}
 *         false
 *
 *             Enable jetty proxy protocol header support.
 *
 *

 *

 *         {@code httpCompliance}
 *         RFC7230
 *
 *             This sets the http compliance level used by Jetty when parsing http, this can be useful when using a
 *             non-RFC7230 compliant front end, such as nginx, which can produce multi-line headers when forwarding
 *             client certificates using proxy_set_header X-SSL-CERT $ssl_client_cert;
 *
 *             Possible values are set forth in the org.eclipse.jetty.http.HttpCompliance enum:
 *

 *
RFC7230: Disallow header folding.

 *
RFC2616: Allow header folding.

 *

 *
 *

 *

 *         {@code requestCookieCompliance}
 *         RFC6265
 *
 *             This sets the cookie compliance level used by Jetty when parsing request {@code Cookie} headers,
 *             this can be useful when needing to support Version=1 cookies defined in RFC2109 (and continued in
 *             RFC2965) which allows for special/reserved characters (control, separator, et al) to be enclosed within
 *             double quotes when used in a cookie value;
 *
 *             Possible values are set forth in the org.eclipse.jetty.http.CookieCompliance enum:
 *

 *
RFC6265: Special characters in cookie values must be encoded.

 *
RFC2965: Allows for special characters enclosed within double quotes.

 *

 *
 *

 *

 *         {@code responseCookieCompliance}
 *         RFC6265
 *
 *             This sets the cookie compliance level used by Jetty when generating response {@code Set-Cookie} headers,
 *             this can be useful when needing to support Version=1 cookies defined in RFC2109 (and continued in
 *             RFC2965) which allows for special/reserved characters (control, separator, et al) to be enclosed within
 *             double quotes when used in a cookie value;
 *
 *             Possible values are set forth in the org.eclipse.jetty.http.CookieCompliance enum:
 *

 *
RFC6265: Special characters in cookie values must be encoded.

 *
RFC2965: Allows for special characters enclosed within double quotes.

 *

 *
 *

 *

 */
@JsonTypeName("http")
public class HttpConnectorFactory implements ConnectorFactory {
    public static ConnectorFactory application() {
        final HttpConnectorFactory factory = new HttpConnectorFactory();
        factory.port = 8080;
        return factory;
    }

    public static ConnectorFactory admin() {
        final HttpConnectorFactory factory = new HttpConnectorFactory();
        factory.port = 8081;
        return factory;
    }

    @PortRange
    private int port = 8080;

    @Nullable
    private String bindHost;

    private boolean inheritChannel = false;

    @NotNull
    @MinDataSize(128)
    private DataSize headerCacheSize = DataSize.bytes(512);

    @NotNull
    @MinDataSize(value = 8, unit = DataSizeUnit.KIBIBYTES)
    private DataSize outputBufferSize = DataSize.kibibytes(32);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.KIBIBYTES)
    private DataSize maxRequestHeaderSize = DataSize.kibibytes(8);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.KIBIBYTES)
    private DataSize maxResponseHeaderSize = DataSize.kibibytes(8);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.KIBIBYTES)
    private DataSize inputBufferSize = DataSize.kibibytes(8);

    @NotNull
    @MinDuration(value = 1, unit = TimeUnit.MILLISECONDS)
    private Duration idleTimeout = Duration.seconds(30);

    @NotNull
    @MinDataSize(0)
    private DataSize minResponseDataPerSecond = DataSize.bytes(0);

    @NotNull
    @MinDataSize(0)
    private DataSize minRequestDataPerSecond = DataSize.bytes(0);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.BYTES)
    private DataSize minBufferPoolSize = DataSize.bytes(64);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.BYTES)
    private DataSize bufferPoolIncrement = DataSize.bytes(1024);

    @NotNull
    @MinDataSize(value = 1, unit = DataSizeUnit.BYTES)
    private DataSize maxBufferPoolSize = DataSize.kibibytes(64);

    @Min(value = 1, payload = Unwrapping.Unwrap.class)
    private Optional<Integer> acceptorThreads = Optional.empty();

    @Min(value = 1, payload = Unwrapping.Unwrap.class)
    private Optional<Integer> selectorThreads = Optional.empty();

    @Min(0)
    @Nullable
    private Integer acceptQueueSize;

    private boolean reuseAddress = true;

    private boolean useServerHeader = false;
    private boolean useDateHeader = true;
    private boolean useForwardedHeaders = false;
    private boolean useProxyProtocol = false;
    private HttpCompliance httpCompliance = HttpCompliance.RFC7230;
    private CookieCompliance requestCookieCompliance = CookieCompliance.RFC6265;
    private CookieCompliance responseCookieCompliance = CookieCompliance.RFC6265;

    @JsonProperty
    public int getPort() {
        return port;
    }

    @JsonProperty
    public void setPort(int port) {
        this.port = port;
    }

    @JsonProperty
    @Nullable
    public String getBindHost() {
        return bindHost;
    }

    @JsonProperty
    public void setBindHost(String bindHost) {
        this.bindHost = bindHost;
    }

    @JsonProperty
    public boolean isInheritChannel() {
        return inheritChannel;
    }

    @JsonProperty
    public void setInheritChannel(boolean inheritChannel) {
        this.inheritChannel = inheritChannel;
    }

    @JsonProperty
    public DataSize getHeaderCacheSize() {
        return headerCacheSize;
    }

    @JsonProperty
    public void setHeaderCacheSize(DataSize headerCacheSize) {
        this.headerCacheSize = headerCacheSize;
    }

    @JsonProperty
    public DataSize getOutputBufferSize() {
        return outputBufferSize;
    }

    @JsonProperty
    public void setOutputBufferSize(DataSize outputBufferSize) {
        this.outputBufferSize = outputBufferSize;
    }

    @JsonProperty
    public DataSize getMaxRequestHeaderSize() {
        return maxRequestHeaderSize;
    }

    @JsonProperty
    public void setMaxRequestHeaderSize(DataSize maxRequestHeaderSize) {
        this.maxRequestHeaderSize = maxRequestHeaderSize;
    }

    @JsonProperty
    public DataSize getMaxResponseHeaderSize() {
        return maxResponseHeaderSize;
    }

    @JsonProperty
    public void setMaxResponseHeaderSize(DataSize maxResponseHeaderSize) {
        this.maxResponseHeaderSize = maxResponseHeaderSize;
    }

    @JsonProperty
    public DataSize getInputBufferSize() {
        return inputBufferSize;
    }

    @JsonProperty
    public void setInputBufferSize(DataSize inputBufferSize) {
        this.inputBufferSize = inputBufferSize;
    }

    @JsonProperty
    public Duration getIdleTimeout() {
        return idleTimeout;
    }

    @JsonProperty
    public void setIdleTimeout(Duration idleTimeout) {
        this.idleTimeout = idleTimeout;
    }

    @JsonProperty
    public DataSize getMinBufferPoolSize() {
        return minBufferPoolSize;
    }

    @JsonProperty
    public void setMinBufferPoolSize(DataSize minBufferPoolSize) {
        this.minBufferPoolSize = minBufferPoolSize;
    }

    @JsonProperty
    public DataSize getBufferPoolIncrement() {
        return bufferPoolIncrement;
    }

    @JsonProperty
    public void setBufferPoolIncrement(DataSize bufferPoolIncrement) {
        this.bufferPoolIncrement = bufferPoolIncrement;
    }

    @JsonProperty
    public DataSize getMaxBufferPoolSize() {
        return maxBufferPoolSize;
    }

    @JsonProperty
    public void setMaxBufferPoolSize(DataSize maxBufferPoolSize) {
        this.maxBufferPoolSize = maxBufferPoolSize;
    }

    @JsonProperty
    public DataSize getMinResponseDataPerSecond() {
        return minResponseDataPerSecond;
    }

    @JsonProperty
    public void setMinResponseDataPerSecond(DataSize minResponseDataPerSecond) {
        this.minResponseDataPerSecond = minResponseDataPerSecond;
    }

    @JsonProperty
    public DataSize getMinRequestDataPerSecond() {
        return minRequestDataPerSecond;
    }

    @JsonProperty
    public void setMinRequestDataPerSecond(DataSize minRequestDataPerSecond) {
        this.minRequestDataPerSecond = minRequestDataPerSecond;
    }

    @JsonProperty
    public Optional<Integer> getAcceptorThreads() {
        return acceptorThreads;
    }

    @JsonProperty
    public void setAcceptorThreads(Optional<Integer> acceptorThreads) {
        this.acceptorThreads = acceptorThreads;
    }

    @JsonProperty
    public Optional<Integer> getSelectorThreads() {
        return selectorThreads;
    }

    @JsonProperty
    public void setSelectorThreads(Optional<Integer> selectorThreads) {
        this.selectorThreads = selectorThreads;
    }

    @JsonProperty
    @Nullable
    public Integer getAcceptQueueSize() {
        return acceptQueueSize;
    }

    @JsonProperty
    public void setAcceptQueueSize(Integer acceptQueueSize) {
        this.acceptQueueSize = acceptQueueSize;
    }

    @JsonProperty
    public boolean isReuseAddress() {
        return reuseAddress;
    }

    @JsonProperty
    public void setReuseAddress(boolean reuseAddress) {
        this.reuseAddress = reuseAddress;
    }

    @JsonProperty
    public boolean isUseServerHeader() {
        return useServerHeader;
    }

    @JsonProperty
    public void setUseServerHeader(boolean useServerHeader) {
        this.useServerHeader = useServerHeader;
    }

    @JsonProperty
    public boolean isUseDateHeader() {
        return useDateHeader;
    }

    @JsonProperty
    public void setUseDateHeader(boolean useDateHeader) {
        this.useDateHeader = useDateHeader;
    }

    @JsonProperty
    public boolean isUseForwardedHeaders() {
        return useForwardedHeaders;
    }

    @JsonProperty
    public void setUseForwardedHeaders(boolean useForwardedHeaders) {
        this.useForwardedHeaders = useForwardedHeaders;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public boolean isUseProxyProtocol() {
        return useProxyProtocol;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public void setUseProxyProtocol(boolean useProxyProtocol) {
        this.useProxyProtocol = useProxyProtocol;
    }

    @JsonProperty
    public HttpCompliance getHttpCompliance() {
        return httpCompliance;
    }

    @JsonProperty
    public void setHttpCompliance(HttpCompliance httpCompliance) {
        this.httpCompliance = httpCompliance;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public CookieCompliance getRequestCookieCompliance() {
        return requestCookieCompliance;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public void setRequestCookieCompliance(CookieCompliance requestCookieCompliance) {
        this.requestCookieCompliance = requestCookieCompliance;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public CookieCompliance getResponseCookieCompliance() {
        return responseCookieCompliance;
    }

    /**
     * @since 2.0
     */
    @JsonProperty
    public void setResponseCookieCompliance(CookieCompliance responseCookieCompliance) {
        this.responseCookieCompliance = responseCookieCompliance;
    }

    @Override
    public Connector build(Server server,
                           MetricRegistry metrics,
                           String name,
                           @Nullable ThreadPool threadPool) {
        final HttpConfiguration httpConfig = buildHttpConfiguration();

        final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig);

        final Scheduler scheduler = new ScheduledExecutorScheduler();

        final ByteBufferPool bufferPool = buildBufferPool();

        return buildConnector(server, scheduler, bufferPool, name, threadPool,
                              new InstrumentedConnectionFactory(httpConnectionFactory,
                                                                metrics.timer(httpConnections())));
    }

    /**
     * Get name of the timer that tracks incoming HTTP connections
     */
    protected String httpConnections() {
        return name(HttpConnectionFactory.class,  bindHost, Integer.toString(port), "connections");
    }

    protected ServerConnector buildConnector(Server server,
                                             Scheduler scheduler,
                                             ByteBufferPool bufferPool,
                                             String name,
                                             @Nullable ThreadPool threadPool,
                                             ConnectionFactory... factories) {
        if (useProxyProtocol) {
            factories = ArrayUtil.prependToArray(new ProxyConnectionFactory(), factories, ConnectorFactory.class);
        }

        final ServerConnector connector = new ServerConnector(server,
                                                              threadPool,
                                                              scheduler,
                                                              bufferPool,
                                                              acceptorThreads.orElse(-1),
                                                              selectorThreads.orElse(-1),
                                                              factories);
        connector.setPort(port);
        connector.setHost(bindHost);
        connector.setInheritChannel(inheritChannel);
        if (acceptQueueSize != null) {
            connector.setAcceptQueueSize(acceptQueueSize);
        } else {
            // if we do not set the acceptQueueSize, when jetty
            // creates the ServerSocket, it uses the default backlog of 50, and
            // not the value from the OS.  Therefore we set to the value
            // obtained from NetUtil, which will attempt to read the value from the OS.
            // somaxconn setting
            connector.setAcceptQueueSize(NetUtil.getTcpBacklog());
        }

        connector.setReuseAddress(reuseAddress);
        connector.setIdleTimeout(idleTimeout.toMilliseconds());
        connector.setName(name);

        return connector;
    }

    protected HttpConnectionFactory buildHttpConnectionFactory(HttpConfiguration httpConfig) {
        final HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfig, httpCompliance);
        httpConnectionFactory.setInputBufferSize((int) inputBufferSize.toBytes());
        return httpConnectionFactory;
    }

    protected HttpConfiguration buildHttpConfiguration() {
        final HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setHeaderCacheSize((int) headerCacheSize.toBytes());
        httpConfig.setOutputBufferSize((int) outputBufferSize.toBytes());
        httpConfig.setRequestHeaderSize((int) maxRequestHeaderSize.toBytes());
        httpConfig.setResponseHeaderSize((int) maxResponseHeaderSize.toBytes());
        httpConfig.setSendDateHeader(useDateHeader);
        httpConfig.setSendServerVersion(useServerHeader);
        httpConfig.setMinResponseDataRate(minResponseDataPerSecond.toBytes());
        httpConfig.setMinRequestDataRate(minRequestDataPerSecond.toBytes());
        httpConfig.setRequestCookieCompliance(requestCookieCompliance);
        httpConfig.setResponseCookieCompliance(responseCookieCompliance);

        if (useForwardedHeaders) {
            httpConfig.addCustomizer(new ForwardedRequestCustomizer());
        }

        return httpConfig;
    }

    protected ByteBufferPool buildBufferPool() {
        return buildBufferPool((int) minBufferPoolSize.toBytes(),
                               (int) bufferPoolIncrement.toBytes(),
                               (int) maxBufferPoolSize.toBytes());
    }

    // This method only exists so that mockito can spy on the constructor parameters.
    ByteBufferPool buildBufferPool(int minCapacity, int factor, int maxCapacity) {
        return new ArrayByteBufferPool(minCapacity, factor, maxCapacity);
    }
}


text:
namespace cobalt {
namespace cssom {

MediaList::MediaList() : css_parser_(NULL) {}

MediaList::MediaList(CSSParser* css_parser) : css_parser_(css_parser) {}

std::string MediaList::media_text() const {
  std::string media;
  size_t mediaitem = 0;
  while (true) {
    media += media_queries_[mediaitem]->media_query();
    if (++mediaitem < media_queries_.size())
      media += ", ";
    else
      break;
  }
  return media;
}

void MediaList::set_media_text(const std::string& css_text) {
  DCHECK(css_parser_);
  scoped_refptr<MediaList> media_list =
      css_parser_->ParseMediaList(css_text, GetInlineSourceLocation());

  media_queries_.swap(media_list->media_queries_);
}

// Returns the number of MediaQuery objects represented by the collection.
unsigned int MediaList::length() const {
  CHECK_LE(media_queries_.size(), std::numeric_limits<unsigned int>::max());
  return static_cast<unsigned int>(media_queries_.size());
}

std::string MediaList::Item(unsigned int index) const {
  return index < media_queries_.size() ? media_queries_[index]->media_query()
                                       : "";
}

// Inserts a new media query string into the current style sheet. This Web API
// takes a string as input and parses it into a MediaQuery.
void MediaList::AppendMedium(const std::string& medium) {
  DCHECK(css_parser_);
  scoped_refptr<MediaQuery> media_query =
      css_parser_->ParseMediaQuery(medium, GetInlineSourceLocation());

  // TODO: Don't add the query if the same one already exists in the
  // collection. See https://www.w3.org/TR/cssom/#medialist for details.
  media_queries_.push_back(media_query);
}

void MediaList::Append(const scoped_refptr<MediaQuery>& media_query) {
  media_queries_.push_back(media_query);
}

bool MediaList::EvaluateConditionValue(const ViewportSize& viewport_size) {
  if (media_queries_.empty()) {
    // A CSSMediaRule with no expressions always evaluates to true.
    return true;
  }

  for (MediaQueries::iterator it = media_queries_.begin();
       it != media_queries_.end(); ++it) {
    if ((*it)->EvaluateConditionValue(viewport_size)) {
      return true;
    }
  }
  return false;
}

void MediaList::TraceMembers(script::Tracer* tracer) {
  tracer->TraceItems(media_queries_);
}

MediaList::~MediaList() {}

}  // namespace cssom
}  // namespace cobalt


text:
from pollirio.reactors import expose
from pollirio import conf, choose_dest

import random
import cPickle
import string

markov_data = 'data/markov.pkl'
try:
    markov_chains = cPickle.load(open(markov_data))
except IOError:
    markov_chains = {}
    markov_chains['all'] = {}
    markov_chains['fanculo'] = {}

def update_chains(lines, alternative=False):
    has_prev = False
    for line in lines:
        for cur_word in line.split():
            if cur_word != '':
                cur_word = cur_word.lower()
                if has_prev == False:
                    prev_word = cur_word
                    has_prev = True
                else:
                    if prev_word == cur_word:
                        # avoid infinite loops
                        continue
                    chain = 'all'
                    if alternative:
                        chain = 'fanculo'
                    if prev_word in markov_chains[chain]:
                        if cur_word in markov_chains[chain][prev_word]:
                            markov_chains[chain][prev_word][cur_word] += 1
                        else:
                            markov_chains[chain][prev_word][cur_word] = 1
                    else:
                        markov_chains[chain][prev_word] = {cur_word: 1}
                    #~ markov_chains[chain].setdefault(prev_word, []).append(cur_word)

                    prev_word = cur_word

def make_sentence(words=None, alternative=False):
    while True:
        if not words:
            keys = markov_chains['all'].keys()
            additional_keys = []
            if alternative:
                additional_keys = [x for x in markov_chains['fanculo'].keys() if x not in keys]
            word = random.choice(keys + additional_keys)
        else:
            word = random.choice(words)
        if word[-1] not in ('.','?'):
            break
    generated_sentence = word.capitalize()
    while word[-1] not in ('.','?'):
        try:
            threshold = int(round(sum(markov_chains['all'][word].values()) / (len(markov_chains['all'][word].values()) * 0.2)))
            subchain = [x[0] for x in markov_chains['all'][word].items() if x[1] >= threshold]
            try:
                subchain.remove(word)
            except ValueError:
                pass
            additional_subchain = []
            if alternative:
                try:
                    additional_subchain = [x[0] for x in markov_chains['fanculo'][word].items() if x[0] not in subchain and x[1] >= threshold]
                    try:
                        additional_subchain.remove(word)
                    except ValueError:
                        pass
                except KeyError:
                    pass
            newword = random.choice(subchain + additional_subchain)
            generated_sentence += ' '+newword
            word = newword #TODO fix possible crash if this is not a key (last word parsed)
        except (KeyError, IndexError):
            generated_sentence += '.'
            word = '.'
    return generated_sentence

@expose('.*')
def learn(bot, ievent):
    if ievent.msg.startswith(conf.nickname) or (ievent.channel == '#fanculo' and conf.nickname in ievent.msg):
        punct = string.punctuation.replace('_', '')
        punct = punct.replace('|', '')
        punct = punct.replace('-', '')
        msg = ievent.msg.translate(string.maketrans('', ''), punct)
        words = msg.replace(conf.nickname, '').split()

        if ievent.channel == '#fanculo':
            # learn from here too, unless a bot is speaking
            if ievent.nick not in ['godzilla', 'parrot', 'RedBot']:
                update_chains([ievent.msg.replace(conf.nickname, '')], True)
            talk(bot, ievent, words, True)
        else:
            talk(bot, ievent, words)
        return

    if ievent.channel.startswith('#'):
        if ievent.channel == '#fanculo':
            update_chains([ievent.msg], True)
        else:
            update_chains([ievent.msg])
        #print markov_chains
        cPickle.dump(markov_chains, open(markov_data, 'w'))

# commented because triggered from learn()
#@expose('^%s' % conf.nickname)
def talk(bot, ievent, words=None, alternative=False):
    #source = 'data/pg28867.txt'
    #mc = create_chains(open(source))
    bot.msg(choose_dest(ievent), '%s: %s' % (ievent.nick, make_sentence(words, alternative)))


text:
promise_test(async t => {
  const result = await fetch(`resources/content-length.py?length=${encodeURIComponent("Content-Length: 50")}`);
  await promise_rejects_js(t, TypeError, result.text());
}, "Content-Length header value of network response exceeds response body");


text:
#include "../Internal.h"
#include <Lumino/Reflection/ReflectionObject.h>
#include <Lumino/Reflection/ReflectionArrayObject.h>
#include <Lumino/Reflection/Variant.h>

LN_NAMESPACE_BEGIN
namespace tr
{

//==============================================================================
// Variant
//==============================================================================

const Variant Variant::Null;

//------------------------------------------------------------------------------
Variant::Variant()
	: m_type(VariantType::Null)
	, m_object(nullptr)
	, m_structSize(0)
{
}

//------------------------------------------------------------------------------
void Variant::SetNullPtr(std::nullptr_t value)
{
	Release();
}
std::nullptr_t Variant::GetNullPtr() const
{
	LN_CHECK_STATE(m_type == VariantType::Null);
	return nullptr;
}
void Variant::SetBool(bool value)
{
	Release();
	m_type = VariantType::Bool;
	m_bool = value;
}
bool Variant::GetBool() const
{
	LN_CHECK_STATE(m_type == VariantType::Bool);
	return m_bool;
}
void Variant::SetArithmetic(int32_t value)
{
	Release();
	m_type = VariantType::Int32;
	m_int32 = value;
}
void Variant::SetArithmetic(uint32_t value)
{
	Release();
	m_type = VariantType::UInt32;
	m_uint32 = value;
}
//void Variant::GetArithmetic(int32_t* value) const
//{
//	LN_CHECK_STATE_RETURNV(m_type == VariantType::Int32);
//	*value = m_int32;
//}
void Variant::SetArithmetic(float value)
{
	Release();
	m_type = VariantType::Float;
	m_float = value;
}
//void Variant::GetArithmetic(float* value) const
//{
//	LN_CHECK_STATE_RETURNV(m_type == VariantType::Float);
//	*value = m_float;
//}
void Variant::SetArithmetic(double value)
{
	Release();
	m_type = VariantType::Double;
	m_double = value;
}
void Variant::SetString(const TCHAR* value)
{
	Release();
	m_type = VariantType::String;
	m_string = LN_NEW ln::detail::GenericStringCore<TCHAR>();
	m_string->assign(value);
}
void Variant::SetString(const String& value)
{
	Release();
	m_type = VariantType::String;
	LN_REFOBJ_SET(m_string, value.m_string);
}
String Variant::GetString() const
{
	LN_CHECK_STATE(m_type == VariantType::String);
	String str;
	str.Attach(m_string);
	return str;
}
void Variant::SetEnumValue(EnumValueType value)
{
	Release();
	m_type = VariantType::Enum;
	m_enum = value;
}
EnumValueType Variant::GetEnumValue() const
{
	LN_CHECK_STATE(m_type == VariantType::Enum);
	return m_enum;
}
void Variant::SetStruct(const void* value, size_t size, const std::type_info& typeInfo)
{
	LN_CHECK_ARG(size <= sizeof(m_struct));
	m_type = VariantType::Struct;
	memcpy(m_struct, value, size);
	m_structSize = size;
	m_typeInfo = &typeInfo;
}
const void* Variant::GetStruct() const
{
	LN_CHECK_STATE(m_type == VariantType::Struct);
	return (const void*)m_struct;
}
void Variant::SetReflectionObject(ReflectionObject* obj)
{
	Release();
	m_type = VariantType::Object;
	LN_REFOBJ_SET(m_object, obj);
}
ReflectionObject* Variant::GetReflectionObject() const
{
	if (m_type == VariantType::Null) return nullptr;
	LN_CHECK_STATE(m_type == VariantType::Object || m_type == VariantType::ArrayObject);	// List も Object の一部。
	return m_object;
}
void Variant::SetReflectionArrayObject(ReflectionArrayObject* obj)
{
	Release();
	m_type = VariantType::ArrayObject;
	LN_REFOBJ_SET(m_arrayObject, obj);
}
ReflectionArrayObject* Variant::GetReflectionArrayObject() const
{
	if (m_type == VariantType::Null) return nullptr;
	LN_CHECK_STATE(m_type == VariantType::ArrayObject);
	return m_arrayObject;
}

//------------------------------------------------------------------------------
bool Variant::Equals(const Variant& obj) const
{
	if (m_type != obj.m_type) return false;
	switch (m_type)
	{
	case VariantType::Null:
		return true;
	case VariantType::Bool:
		return m_bool == obj.m_bool;
	case VariantType::Int32:
		return m_int32 == obj.m_int32;
	case VariantType::UInt32:
		return m_uint32 == obj.m_uint32;
	case VariantType::Float:
		return m_float == obj.m_float;
	case VariantType::Double:
		return m_double == obj.m_double;
	case VariantType::String:
		return m_string == obj.m_string;
	case VariantType::Enum:
		return m_enum == obj.m_enum;
	case VariantType::Struct:
		if (m_structSize != obj.m_structSize) return false;
		return memcmp(m_struct, obj.m_struct, m_structSize) != 0;
	case VariantType::Object:
		return m_object == obj.m_object;
	case VariantType::ArrayObject:
		return m_arrayObject == obj.m_arrayObject;
	default:
		LN_ASSERT(0);
		break;
	}
	return false;
}

//------------------------------------------------------------------------------
void Variant::Copy(const Variant& obj)
{
	Release();
	m_type = obj.m_type;
	switch (m_type)
	{
	case VariantType::Null:
		break;
	case VariantType::Bool:
		m_bool = obj.m_bool;
		break;
	case VariantType::Int32:
		m_int32 = obj.m_int32;
		break;
	case VariantType::UInt32:
		m_uint32 = obj.m_uint32;
		break;
	case VariantType::Float:
		m_float = obj.m_float;
		break;
	case VariantType::Double:
		m_double = obj.m_double;
		break;
	case VariantType::String:
		LN_REFOBJ_SET(m_string, obj.m_string);
		break;
	case VariantType::Enum:
		m_enum = obj.m_enum;
		break;
	case VariantType::Struct:
		m_structSize = obj.m_structSize;
		memcpy(m_struct, obj.m_struct, m_structSize);
		break;
	case VariantType::Object:
		LN_REFOBJ_SET(m_object, obj.m_object);
		break;
	case VariantType::ArrayObject:
		LN_REFOBJ_SET(m_arrayObject, obj.m_arrayObject);
		break;
	default:
		LN_ASSERT(0);
		break;
	}
}

//------------------------------------------------------------------------------
void Variant::Release()
{
	if (m_type == VariantType::String) {
		LN_SAFE_RELEASE(m_string);
	}
	else if (m_type == VariantType::Object) {
		LN_SAFE_RELEASE(m_object);
	}
	else if (m_type == VariantType::ArrayObject) {
		LN_SAFE_RELEASE(m_arrayObject);
	}
	m_type = VariantType::Null;
	m_structSize = 0;
}

} // namespace tr
LN_NAMESPACE_END


text:
from apps.thirdparty.smart_selects.widgets import ChainedSelect
from django.forms.models import ModelChoiceField
from django.forms import ChoiceField
from django.db.models import get_model

class ChainedModelChoiceField(ModelChoiceField):
    def __init__(self, app_name, model_name, chain_field, model_field, show_all, auto_choose, manager=None, initial=None, *args, **kwargs):
        defaults = {
            'widget': ChainedSelect(app_name, model_name, chain_field, model_field, show_all, auto_choose, manager),
        }
        defaults.update(kwargs)
        if not 'queryset' in kwargs:
            queryset = get_model(app_name, model_name).objects.all()
            super(ChainedModelChoiceField, self).__init__(queryset=queryset, initial=initial, *args, **defaults)
        else:
            super(ChainedModelChoiceField, self).__init__(initial=initial, *args, **defaults)

    def _get_choices(self):
        self.widget.queryset = self.queryset
        choices = super(ChainedModelChoiceField, self)._get_choices()
        return choices
    choices = property(_get_choices, ChoiceField._set_choices)

class GroupedModelSelect(ModelChoiceField):
    def __init__(self, queryset, order_field, *args, **kwargs):
        self.order_field = order_field
        super(GroupedModelSelect, self).__init__(queryset, *args, **kwargs)

    def _get_choices(self):
        # If self._choices is set, then somebody must have manually set
        # the property self.choices. In this case, just return self._choices.
        if hasattr(self, '_choices'):
            return self._choices
        # Otherwise, execute the QuerySet in self.queryset to determine the
        # choices dynamically. Return a fresh QuerySetIterator that has not been
        # consumed. Note that we're instantiating a new QuerySetIterator *each*
        # time _get_choices() is called (and, thus, each time self.choices is
        # accessed) so that we can ensure the QuerySet has not been consumed. This
        # construct might look complicated but it allows for lazy evaluation of
        # the queryset.
        final = [("", self.empty_label or "---------"), ]
        group = None
        for item in self.queryset:
            if not group or group[0] != unicode(getattr(item, self.order_field)):
                if group:
                    final.append(group)
                group = [unicode(getattr(item, self.order_field)), []]
            group[1].append(self.make_choice(item))
        return final

    def make_choice(self, obj):
        return (obj.pk, "   " + self.label_from_instance(obj))

    choices = property(_get_choices, ChoiceField._set_choices)