text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;
using System.Diagnostics;
using Remote;
using MahApps.Metro.Controls;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
namespace RemoteGUI
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : MetroWindow
	{
		Dictionary<string, BindingEntry> bindings = new Dictionary<string, BindingEntry>();

		public static string[] screenCaptureMethods = new string[] { "GDI", "BitBlt", "DirectX" };
		public static string[] frameBufferings = new string[] { "Disabled", "Enabled" };
		public static string[] desktopCompositions = new string[] { "Enabled", "Disabled" };
		public static string[] pixelFormats = new string[] { "32bppARGB", "24bppRGB", "16bppRGB565" };
		public static string[] framesPerSeconds = new string[] { "5", "10", "15", "20", "25", "30", "Max" };
		public static string[] compressions = new string[] { "Lossless", "Lossy" };
		public static string[] losslessCodec = new string[] { "LZ4" };
		public static string[] lossyCodec = new string[] { "ffmpeg" };
		public static string[] LZ4BlockSizes = new string[] { "32kb", "64kb", "128kb", "256kb", "512kb", "Max" };
		public static string[] autoStartServer = new string[] { "Disabled", "Enabled" };

		public List<string> serverConnectedComputerNames;
		public List<SOCKET.Client> serverConnectedComputers;
		public bool serverEmpty = true;

		SOCKET.Server server;
		//List<SOCKET.Client> client;

		RemoteDesktopHost host;

		List<StackPanel> connectedComputersItems = new List<StackPanel>();
		//Dictionary<StackPanel, ClientData> connectedComputersBinding = new Dictionary<StackPanel, ClientData>();
		Clients clients = new Clients();
		public static RemoteGuiLoader.MainWindow loader = new RemoteGuiLoader.MainWindow();
		Command lastCommand;

		ConsoleWriter cw = new ConsoleWriter(1000);
		string tempText;

		public DispatcherTimer dt;
		public int fps = 1;
		public long oldTick;
		public long newTick;
		public string sajt;
		BitmapImage bmi;
		Stopwatch sw;
		int kecske;
		int x = 1920;
		int y = 1080;
		System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format16bppRgb565;
		//[System.Runtime.InteropServices.DllImport("gdi32.dll")]
		//public static extern bool DeleteObject(IntPtr hObject);
		public MainWindow()
		{

			InitializeComponent();
			Loaded += MainWindow_Loaded;
			Closing += MainWindow_Closing;

			FlyoutsControlAll.Visibility = System.Windows.Visibility.Visible;
			ConnectedInfo.Visibility = System.Windows.Visibility.Hidden;

			ScreenCaptureMethodComboBox.ItemsSource = screenCaptureMethods;
			BufferingComboBox.ItemsSource = Remote.Language.Find(() => BufferingComboBox.ItemsSource, this, frameBufferings);//frameBufferings;
			CompositionComboBox.ItemsSource = Remote.Language.Find(() => CompositionComboBox.ItemsSource, this, desktopCompositions);//desktopCompositions;
			FormatComboBox.ItemsSource = pixelFormats;
			FPSComboBox.ItemsSource = framesPerSeconds;
			CompressionComboBox.ItemsSource = Remote.Language.Find(() => CompressionComboBox.ItemsSource, this, compressions);//compressions;
			CodecComboBox.ItemsSource = losslessCodec;
			LZ4BlockSizeComboBox.ItemsSource = LZ4BlockSizes;
			AutoStartServerComboBox.ItemsSource = Remote.Language.Find(() => AutoStartServerComboBox.ItemsSource, this, autoStartServer); ;

			Bind(ScreenCaptureMethodComboBox.Name, () => Settings.s.remoteDesktopSettings.screenCaptureMethod, true);
			Bind(BufferingComboBox.Name, () => Settings.s.remoteDesktopSettings.frameBuffering, true);
			Bind(CompositionComboBox.Name, () => Settings.s.remoteDesktopSettings.desktopComposition, true);
			Bind(FormatComboBox.Name, () => Settings.s.remoteDesktopSettings.pixelFormat, true);
			Bind(FPSComboBox.Name, () => Settings.s.remoteDesktopSettings.framesPerSecond, true);
			Bind(CompressionComboBox.Name, () => Settings.s.remoteDesktopSettings.compression, true);
			Bind(LZ4BlockSizeComboBox.Name, () => Settings.s.remoteDesktopSettings.LZ4BlockSize, true);
			Bind(AutoStartServerComboBox.Name, () => Settings.s.startServer, false);

			ScreenCaptureMethodComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.screenCaptureMethod;
			BufferingComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.frameBuffering;
			CompositionComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.desktopComposition;
			FormatComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.pixelFormat;
			FPSComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.framesPerSecond;
			CompressionComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.compression;
			if(CompressionComboBox.SelectedIndex == 0)
			{
				//Bind(CodecComboBox.Name, () => Settings.s.remoteDesktopSettings.losslessCodec);
				// Notes: No need to bind here, as this will be changed in custom method and not in generic one!
				CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.losslessCodec;
			}
			else
			{
				//Bind(CodecComboBox.Name, () => Settings.s.remoteDesktopSettings.lossyCodec);
				// Notes: No need to bind here, as this will be changed in custom method and not in generic one!
				CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.lossyCodec;
			}
			LZ4BlockSizeComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.LZ4BlockSize;

			Address.ItemsSource = Settings.s.addresses;

			if (Settings.s.startServer == 1)
			{
				server = new SOCKET.Server(Settings.s.remoteDesktopPort);
				server.Listen();
				server.StartReceiveAsync(OnConnectionAccept);
				ServerStartButton.Content = Remote.Language.Find(on => ServerStartButton.Content, this, "");
				//ServerStartButton.Content = "Stop Server";
			}
			else
			{
				server = new SOCKET.Server(Settings.s.remoteDesktopPort);
				server.Close();
				ServerStartButton.Content = Remote.Language.Find(off => ServerStartButton.Content, this, "");
				//ServerStartButton.Content = "Start Server";
			}

			UserNameTextBox.Text = Settings.s.name;
			PortTextBox.Text = Settings.s.remoteDesktopPort.ToString();

			//lServer.Content = Remote.Language.Find(() => lServer.Content, this, "Server");
			//cw.WriteLine(lServer.Name);

			//Screen.EnableComposition(false);
			sw = new Stopwatch();
			sw.Start();
			dt = new DispatcherTimer(DispatcherPriority.Send);
			dt.Tick += dt_Tick;
			dt.Interval = new TimeSpan(0, 0, 0, 0, /*1000 / fps*/ 40);
			oldTick = Environment.TickCount;
			dt.Start();
			/*Thread thread = new Thread(dt_Tick1);
			thread.Priority = ThreadPriority.Highest;
			thread.Start();*/

			/*Thread thread1 = new Thread(dt_Tick1);
			thread1.Priority = ThreadPriority.Highest;
			thread1.Start();*/

			/*Thread thread2 = new Thread(dt_Tick1);
			thread2.Priority = ThreadPriority.Highest;
			thread2.Start();*/

		}

		void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			foreach (var item in clients)
			{
				item.client.Close();
			}
			loader.Close();
		}

		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{

			// Load non english language
			foreach (var item in FindVisualChildren<Label>(this))
			{
				// If it's empty, just ignore
				if (item.Content != null)
				{
					if (item.Name != "")
					{
						item.Content = Remote.Language.Find(item.Name + ".Content", this) ?? item.Content; // Find text for the given element
						//cw.WriteLine(Remote.Language.Find(item.Name + ".Content", this));
					}
				}
				//else cw.WriteLine("error <-----------");
			}
			foreach (var item in FindVisualChildren<Button>(this))
			{
				if (item.Content != null)
				{
					// Not really important to exclude nav and PART_XXX, as we just reassign the contents.
					// This is because they dont have language files.
					// Note: ServerStartButton uses conditions, so this call would throw an exception.
					if (item.Name != "" && item.Name != "nav" && !item.Name.Contains("PART") && item.Name != "ServerStartButton")
					{
						item.Content = Remote.Language.Find(item.Name + ".Content", this) ?? item.Content;
						//cw.WriteLine(item.Name);
					}
				}
			}
			bSettings.Content = Remote.Language.Find(bSettings.Name + ".Content", this) ?? bSettings.Content;
		}

		private bool OnConnectionAccept(System.Net.Sockets.SocketAsyncEventArgs arg)
		{
			Dispatcher.Invoke(new Action(() =>
			{
				ClientData cd = new ClientData();
				cd.client = new SOCKET.Client();
				cd.client.socket = arg.AcceptSocket;

				StackPanel sp = new StackPanel();
				Label l = new Label();
				l.Content = "No name yet";
				cd.lName = l;
				sp.Children.Add(l);
				clients[sp] = cd;
				cd.sp = sp;

				cd.client.StartReceiveAsync(OnReceiveAsync);
			}), DispatcherPriority.Render);

			return true;
		}
		private bool OnReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs arg)
		{
			// Get the client object from arg
			SOCKET.Client client = (SOCKET.Client)arg.UserToken;

			// Notes: First 4 bytes are the size of the message.
			// Notes: It's impossible to send only 4 bytes, as that would mean we only send the message size, which doesn't make sense , so this must be always bigger than 4 bytes
			if (arg.BytesTransferred > 4 && client.pmIn.NewRead() == arg.BytesTransferred)
			{
				lastCommand = client.pmIn.ReadCommand();
				switch (lastCommand)
				{
						// Connection attempt
					case Command.CONNECT:
						#region CONNECT
						{
							cw.WriteLine(Remote.Language.Find("IncomingConnection", this, "Incoming connection attempt from: {0}"), client.ClientAddress);
							Command c = client.pmIn.ReadCommand();
							if (c == Command.USER_NAME)
							{
								Dispatcher.Invoke(new Action(() =>
								{
									foreach (var cd in clients)
									{
										if (cd.client == client)
										{
											cd.name = client.pmIn.ReadString();
											cd.lName.Content = cd.name;

											connectedComputersItems.Add(cd.sp);
											ConnectedComputers.ItemsSource = connectedComputersItems;
											break;
										}
									}
								}),
								DispatcherPriority.Render);
								client.pmOut.New();
								client.pmOut.Write(Command.CONNECT_SUCCESS);
								client.pmOut.Write(Command.USER_NAME);
								client.pmOut.Write(Settings.s.name);
								client.pmOut.End();
								if (client.SendSafe())
								{
									cw.WriteLine(Remote.Language.Find("ClientConnectSuccess", this, "Client from {0} successfully connected!"), client.ClientAddress);
									return true;
								}
								else
								{
									cw.WriteLine(client.lastSendException.Message);
									client.Close();
									client = null;
								}
							}
						}
						break;
						#endregion
					// Success!
					case Command.CONNECT_SUCCESS:
						#region CONNECT_SUCCES
						{
							cw.WriteLine(Remote.Language.Find("ClientConnected", this, "Succesfully connected to {0}"), client.ClientAddress);
							Command c = client.pmIn.ReadCommand();
							if (c == Command.USER_NAME)
							{
								Dispatcher.Invoke(new Action(() =>
								{
									ClientData cd = new ClientData();
									cd.client = client;
									Label l = new Label();
									cd.name = client.pmIn.ReadString();
									cd.lName = l;
									l.Content = cd.name;

									StackPanel sp = new StackPanel();
									sp.Children.Add(l);
									//connectedComputersBinding.Add(sp, cd);
									clients[sp] = cd;
									connectedComputersItems.Add(sp);
									ConnectedComputers.ItemsSource = connectedComputersItems;
								}),
								DispatcherPriority.Render);
							}
							return true;
						}
						#endregion
					case Command.REMOTE_DESKTOP_REQUEST:
						#region REMOTE_DESKTOP_REQUEST
						{
							ClientData cd = clients[(SOCKET.Client)arg.UserToken];
							cd.remoteDesktopRequest = true;
							Dispatcher.Invoke(new Action(() =>
							{
								ConnectedComputers_SelectionChanged(null, null);
							}), DispatcherPriority.Render);
							cw.WriteLine(Remote.Language.Find("RemoteDesktopRequestIncoming", this, "A Remote Desktop request was received from {0} / {1}"), cd.name, cd.client.ClientAddress);
							return true;
						}
						#endregion
					case Command.REMOTE_DESKTOP_CAPTURE_INFO_REQUEST:
						#region REMOTE_DESKTOP_CAPTURE_INFO_REQUEST
						{
							Dispatcher.Invoke(new Action(() =>
								{
									this.WindowState = System.Windows.WindowState.Minimized;
									loader.Show();
								}), DispatcherPriority.Render);
							loader.ChangeText("Sending streaming settings...");

							ClientData cd = clients[(SOCKET.Client)arg.UserToken];

							cd.client.pmOut.New();
							cd.client.pmOut.Write(Command.REMOTE_DESKTOP_CAPTURE_INFO);

							ProtoBuf.Serializer.SerializeWithLengthPrefix(cd.client.pmOut.Stream, Settings.s.remoteDesktopSettings, ProtoBuf.PrefixStyle.Base128);

							cd.client.pmOut.End();

							if (cd.client.SendSafe())
							{
								return true;
							}
							else
							{

							}

						}
						break;
						#endregion
					case Command.REMOTE_DESKTOP_CAPTURE_INFO:
						#region REMOTE_DESKTOP_CAPTURE_INFO
						{
							loader.ChangeText("Creating host...");

							ClientData cd = clients[(SOCKET.Client)arg.UserToken];

							Settings.RemoteDesktopSettings s = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Settings.RemoteDesktopSettings>(cd.client.pmIn.Stream, ProtoBuf.PrefixStyle.Base128);
							host = new RemoteDesktopHost(s);

							cd.client.pmOut.New();
							cd.client.pmOut.Write(Command.REMOTE_DESKTOP_HOST_READY);

							cd.client.pmOut.Write(SystemParameters.PrimaryScreenWidth);
							cd.client.pmOut.Write(SystemParameters.PrimaryScreenHeight);

							cd.client.pmOut.End();

							if (cd.client.SendSafe())
							{
								return true;
							}
							else
							{

							}
						}
						break;
						#endregion
					case Command.REMOTE_DESKTOP_HOST_READY:
						#region REMOTE_DESKTOP_HOST_READY
						{
							loader.ChangeText("Creating streaming connection...");
							bool whatToReturn = false;
							RemoteDesktop rd;
							Dispatcher.Invoke(new Action(() =>
							{
								rd = new RemoteDesktop();
								rd.x = (int)client.pmIn.ReadDouble();
								rd.y = (int)client.pmIn.ReadDouble();

								System.Net.IPAddress address = client.ClientAddress;

								rd.clientStream = new SOCKET.Client();
								rd.clientStream.socket = new System.Net.Sockets.Socket(new System.Net.IPEndPoint(address, Settings.s.remoteDesktopPort).AddressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
								try
								{
									rd.clientStream.socket.Connect(address, Settings.s.remoteDesktopPort);
									rd.clientStream.StartReceiveAsync(rd.OnReceiveAsyncStream);

									rd.clientStream.socket.SendTimeout = 5000;
									rd.clientStream.socket.ReceiveTimeout = 5000;

									rd.clientStream.pmOut.Write(Command.REMOTE_DESKTOP_CONNECT_STREAM);

									rd.clientStream.pmOut.End();

									if (rd.clientStream.SendSafe())
									{
										//cw.WriteLine(Remote.Language.Find("ClientConnecting", this, "Connecting to {0}"), Address.Text);
										whatToReturn = true;
									}
									else
									{
										cw.WriteLine(rd.clientStream.lastSendException.Message);
										rd.clientStream.Close();
										rd.clientStream = null;
										whatToReturn = false;
									}

									//cw.WriteLine(Remote.Language.Find("ClientConnected", this, "Succesfully conencted to {0}"), Address.Text);

								}
								catch (System.Net.Sockets.SocketException ee)
								{
									cw.WriteLine(ee.Message);
									rd.clientStream.Close();
									rd.clientStream = null;
								}
							}), DispatcherPriority.Render);
							if (whatToReturn) return true;
							else return false;
						}
						#endregion
					case Command.REMOTE_DESKTOP_CONNECT_STREAM:
						#region REMOTE_DESKTOP_CONNECT_STREAM
						{
							loader.ChangeText("Streaming connection created...");
							ClientData cd = clients[(SOCKET.Client)arg.UserToken];
							Dispatcher.Invoke(new Action(() =>
							{
								cd.sp.Children.Remove(cd.lName);
								clients.Remove(cd);
								host.clientStream = cd.client;
								host.clientStream.onReceiveAsync = host.OnReceiveAsync;
							}), DispatcherPriority.Render);

							host.clientStream.pmOut.New();
							host.clientStream.pmOut.Write(Command.REMOTE_DESKTOP_CONNECT_STREAM_SUCCESS);
							host.clientStream.pmOut.End();

							if (host.clientStream.SendSafe())
							{
								return true;
							}
							else
							{

							}
							// send success
						}
						break;
						#endregion
					case Command.REMOTE_DESKTOP_CONNECT_INPUT:
						#region REMOTE_DESKTOP_CONNECT_INPUT
						{
							loader.ChangeText("Input stream created...");
							ClientData cd = clients[(SOCKET.Client)arg.UserToken];
							Dispatcher.Invoke(new Action(() =>
							{
								cd.sp.Children.Remove(cd.lName);
								clients.Remove(cd);
								host.clientInput = cd.client;
								host.clientInput.onReceiveAsync = host.OnReceiveAsyncInput;
							}), DispatcherPriority.Render);

							host.clientInput.pmOut.New();
							host.clientInput.pmOut.Write(Command.REMOTE_DESKTOP_CONNECT_INPUT_SUCCESS);
							host.clientInput.pmOut.End();

							if (host.clientInput.SendSafe())
							{
								return true;
							}
							else
							{

							}
							// send success
						}
						break;
						#endregion
					default:
						break;
				}
			}
			//Client disconnected, clean up.
			else if (arg.BytesTransferred == 0)
			{
				switch (lastCommand)
				{
						// Error? EMPTY_COMMAND = 0
					case Command.EMPTY_COMMAND:
						break;
						// Restore MainWindow upon client fail
					case Command.REMOTE_DESKTOP_CAPTURE_INFO_REQUEST:
						{
							Dispatcher.Invoke(new Action(() =>
							{
								loader.Close();
								loader = new RemoteGuiLoader.MainWindow();
								WindowState = System.Windows.WindowState.Normal;
							}), DispatcherPriority.Render);
							cw.WriteLine(Remote.Language.Find("RemoteDekstopCaptureInfoRequestClientDisconnected", this, "The client disconnected during Remote Desktop initialization"));
						}
						break;
					default:
						break;
				}

				foreach (var item in connectedComputersItems)
				{

				}
				//cw.WriteLine("End");
			}
			return false;
		}
		/*protected override void OnPreviewKeyDown(KeyEventArgs e)
		{
				bool[] b = new bool[4];
				b[0] = Keyboard.Modifiers == ModifierKeys.Control;
				b[1] = Keyboard.Modifiers == ModifierKeys.Alt;
				b[2] = e.SystemKey == Key.Delete;
				b[3] = e.SystemKey == Key.Escape;
				sajt = string.Format("Control: {0}, Alt: {1}, Delete: {2}, Escape: {3}, Modifier: {4}, SystemKey: {5}, Key: {6}", b[0], b[1], b[2], b[3], Keyboard.Modifiers, e.SystemKey, e.Key);
				e.Handled = true;
				return;
			if (Keyboard.Modifiers == ModifierKeys.Alt && e.SystemKey == Key.F4 ||
			   Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Escape ||
				Keyboard.Modifiers == ModifierKeys.Control && Keyboard.Modifiers == ModifierKeys.Alt && e.Key == Key.Delete)
			{
				e.Handled = true;
			}
			else
			{
				base.OnPreviewKeyDown(e);
			}
		}*/
		void dt_Tick(object sender, EventArgs e)
		{
			//FPS.Content = sajt;
			//cw.WriteLine(Environment.TickCount.ToString());

			/*cw.WriteLine(Environment.TickCount.ToString());
			ConsoleQuickText.Text = cw.GetLastLine();
			ConsoleText.Text = cw.Update();
			ConsoleText.ScrollToEnd();*/
			//dt_Tick11();

			if (ConsoleFlyout.IsOpen)
			{
				tempText = cw.Update();
				if (tempText != null)
				{
					ConsoleText.Text = tempText;
					ConsoleText.CaretIndex = tempText.Length;
					ConsoleText.ScrollToEnd();
				}
			}
			else
			{
				ConsoleQuickText.Text = cw.GetLastLine();
			}
		}
		async void dt_Tick1()
		{
			int kecske = 0;
			int csiga = 0;
			int boci = 0;
			int count = 0;
			//int totalDiff = 0;
			Thread.Sleep(100);
			Bitmap bmpScreenCapture = new Bitmap(/*(int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight,*/x, y, format);
			BitmapImage bmi;
			byte[][] arr = new byte[2][];// = await task;
			byte[] diff = new byte[0];

			Screen.Capture(x, y, ref bmpScreenCapture, format);//1
			Task<byte[]> task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture));//1

			Screen.Capture(x, y, ref bmpScreenCapture, format);//0
			arr[1] = await task;
			//Screen.arr11 = new int[arr[1].Length / 4];
			//Task<BitmapImage> task = Screen.CompressImageAsync(bmpScreenCapture);
			task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture));//0

			Screen.Capture(x, y, ref bmpScreenCapture, format);//1
			//bmi = await task;

			//Screen.CompressImageAsync(bmpScreenCapture);
			arr[0] = await task;
			//Screen.arr22 = new int[arr[0].Length / 4];
			//Screen.arr = new int[Screen.arr11.Length];
			//Screen.arr0 = new byte[Screen.arr.Length * 4];
			Screen.InitReturnDifference(arr[1].Length);
			Task<byte[]> taskDiff = Task.Run(() => Screen.ReturnDifference(arr[1], arr[0], ref count));
			//task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture));
			//arr[0] = await task;
			//arr[2] = await taskDiff;
			//taskDiff = Task.Run(() => Screen.ReturnDifference(arr[1], arr[0]));
			task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture)); //1
			//arr[2] = await taskDiff;

			while (true)
			{
				newTick = Environment.TickCount;
				kecske++;
				Screen.Capture(x, y, ref bmpScreenCapture, format);
				if (!task.IsCompleted) csiga++;
				//bmi = await task;
				//task = Screen.CompressImageAsync(bmpScreenCapture);

				arr[1] = await task;
				if (!taskDiff.IsCompleted) boci++;
				diff = await taskDiff;
				//totalDiff += diff.Length;
				sajt = kecske / sw.Elapsed.TotalSeconds + ", "/* + 1000 / (newTick - oldTick) */+ ", " + (newTick - oldTick) + ", " + fps + ", " + kecske + " - " + csiga + " - " + boci/* + ", Total uncompressed/compressed diff (MB): " + count * 4 / 1048576 + "/" + *//*totalDiff * 4 / 1048576*//* + ", compressed image size: " + arr.Length*/ + ", Delta size: " + diff.Length + ", Diff count: " + count;//TimeSpan.FromTicks(newTick - oldTick).TotalSeconds;
				oldTick = newTick;
				count = 0;
				taskDiff = Task.Run(() => Screen.ReturnDifference(arr[0], arr[1], ref count));
				task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture));

				newTick = Environment.TickCount;
				kecske++;
				Screen.Capture(x, y, ref bmpScreenCapture, format);
				if (!task.IsCompleted) csiga++;
				arr[0] = await task;
				if (!taskDiff.IsCompleted) boci++;
				diff = await taskDiff;
				//totalDiff += diff.Length;
				sajt = kecske / sw.Elapsed.TotalSeconds + ", "/* + 1000 / (newTick - oldTick) */+ ", " + (newTick - oldTick) + ", " + fps + ", " + kecske + " - " + csiga + " - " + boci/* + ", Total uncompressed/compressed diff (MB): " + count * 4 / 1048576 + "/" + *//*totalDiff * 4 / 1048576*//* + ", compressed image size: " + arr.Length*/ + ", Delta size: " + diff.Length + ", Diff count: " + count;
				oldTick = newTick;
				count = 0;
				taskDiff = Task.Run(() => Screen.ReturnDifference(arr[1], arr[0], ref count));
				task = Task.Run(() => Screen.CompressImageLZ4(bmpScreenCapture));

			}
		}
		void dt_Tick11()
		{
			//Thread.Sleep(100);
			//IntPtr ptr;
			//while (true)
			//{
			sw.Restart();
			jololo:
				oldTick = Environment.TickCount;
				using (Bitmap
				bmpScreenCapture = new Bitmap(/*(int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight,*/1280, 720, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
				{
					using (Graphics g = Graphics.FromImage(bmpScreenCapture))
					{
						g.CopyFromScreen(0,
										 0,
										 0, 0,
										 bmpScreenCapture.Size,
										// new System.Drawing.Size(1280, 720),
										 CopyPixelOperation.SourceCopy);
					}
					//Compress(bmpScreenCapture);
					//using (FileStream ms = new FileStream(@"H:\" + DateTime.Now.Ticks + ".png", FileMode.Create))
					/*using (MemoryStream ms = new MemoryStream())
					{
						bmpScreenCapture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
						BitmapImage bmi = new BitmapImage();
						bmi.BeginInit();
						bmi.CacheOption = BitmapCacheOption.OnLoad;
						ms.Position = 0;
						bmi.StreamSource = ms;
						bmi.EndInit();
						Image_Test.Source = bmi;
					}*/
					//ptr = bmpScreenCapture.GetHbitmap();
					//Image_Test.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
						//ptr,
						//IntPtr.Zero,
						//Int32Rect.Empty,
						//BitmapSizeOptions.FromEmptyOptions());
					//bmpScreenCapture.Save(@"H:\" + DateTime.Now.Ticks + ".png", ImageFormat.Png);
					//DeleteObject(ptr);
				}
				newTick = Environment.TickCount;
				sajt = kecske / sw.Elapsed.TotalSeconds + ", " + ", " + (newTick - oldTick) + ", " + kecske;//TimeSpan.FromTicks(newTick - oldTick).TotalSeconds;
				kecske++;
				goto jololo;
			//}
		}
		/*public async void Compress(Bitmap picture)
		{

		}*/
		private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			/*fps = (int)e.NewValue;
			if(dt != null)
			dt.Interval = new TimeSpan(0, 0, 0, 0, 1000 / fps);*/
		}
		public string Path
		{
			get
			{
				return Environment.CurrentDirectory;
			}
		}
		// Todo: Blocking call if failed to connect for about 10-15 sec
		private void Connect_Click(object sender, RoutedEventArgs e)
		{
			/*if (client != null)
			{
				cw.WriteLine(Remote.Language.Find("ClientNotNull", this, "A connection is already made!"));
				return;
			}*/

			System.Net.IPAddress address;
			if (System.Net.IPAddress.TryParse(Address.Text, out address))
			{
				SOCKET.Client client = new SOCKET.Client();
				client.socket = new System.Net.Sockets.Socket(new System.Net.IPEndPoint(address, Settings.s.remoteDesktopPort).AddressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
				try
				{
					client.socket.Connect(address, Settings.s.remoteDesktopPort);
					client.StartReceiveAsync(OnReceiveAsync);

					client.socket.SendTimeout = 5000;
					client.socket.ReceiveTimeout = 5000;

					client.pmOut.Write(Command.CONNECT);
					client.pmOut.Write(Command.USER_NAME);
					client.pmOut.Write(Settings.s.name);
					client.pmOut.End();

					if (client.SendSafe())
					{
						cw.WriteLine(Remote.Language.Find("ClientConnecting", this, "Connecting to {0}"), Address.Text);
						return;
					}
					else
					{
						cw.WriteLine(client.lastSendException.Message);
						client.Close();
						client = null;
					}

					//cw.WriteLine(Remote.Language.Find("ClientConnected", this, "Succesfully conencted to {0}"), Address.Text);

				}
				catch (System.Net.Sockets.SocketException ee)
				{
					cw.WriteLine(ee.Message);
					client.Close();
					client = null;
				}
			}
		}
		private void RemoveAddress_Click(object sender, RoutedEventArgs e)
		{
			if (Settings.s.addresses.Contains(Address.Text))
			{
				Settings.s.addresses.Remove(Address.Text);
			}
			Address.ItemsSource = null; //Without this the dropdown isn't updated, although autocompletion works, strange, maybe a bug in current Metro nuget
			Address.ItemsSource = Settings.s.addresses;
		}
		private void SaveAddress_Click(object sender, RoutedEventArgs e)
		{
			if (Settings.s.addresses.Contains(Address.Text))
			{

			}
			else
			{
				Settings.s.addresses.Add(Address.Text);
			}
			Address.ItemsSource = null; //Without this the dropdown isn't updated, although autocompletion works, strange, maybe a bug in current Metro nuget
			Address.ItemsSource = Settings.s.addresses;
		}
		private void ConsoleInputText_PreviewKeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				e.Handled = true; //Not so important, as TextBox doesn't makes new lines.
				//Todo: merge console project
			}
			else if (e.Key == Key.Escape)
			{
				//Keyboard.ClearFocus();
				e.Handled = true;
				ConsoleFlyout.IsOpen = false;
			}
		}

		private void StatusBar_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			ConsoleFlyout.IsOpen = true;
		}

		private void CodecComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (compressions[CompressionComboBox.SelectedIndex] == "Lossless")
			{
				if (CodecComboBox.SelectedIndex < 0)
				{
					CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.losslessCodec;
				}
				else
				{
					Settings.s.remoteDesktopSettings.losslessCodec = CodecComboBox.SelectedIndex;
				}

				if (losslessCodec[Settings.s.remoteDesktopSettings.losslessCodec] == "LZ4")
				{
					CodecInfo.SelectedIndex = 0;
				}
			}
			else
			{
				if (CodecComboBox.SelectedIndex < 0)
				{
					CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.lossyCodec;
				}
				else
				{
					Settings.s.remoteDesktopSettings.lossyCodec = CodecComboBox.SelectedIndex;
				}

				if (lossyCodec[Settings.s.remoteDesktopSettings.lossyCodec] == "ffmpeg")
				{
					CodecInfo.SelectedIndex = 1;
				}
			}
		}

		private void CompressionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (CompressionComboBox.SelectedIndex == 0)
			{
				CodecComboBox.ItemsSource = losslessCodec;
				// No longer needed
				//CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.losslessCodec;
			}
			else
			{
				CodecComboBox.ItemsSource = lossyCodec;
				// No longer needed
				//CodecComboBox.SelectedIndex = Settings.s.remoteDesktopSettings.lossyCodec;
			}
			//CodecComboBox_SelectionChanged(null, null); //useless here, changes made to the ItemsSource will trigger SelectionChanged method
		}

		private void ServerDisconnectButton_Click(object sender, RoutedEventArgs e)
		{

		}

		private void ServerStartButton_Click(object sender, RoutedEventArgs e)
		{
			if (server.socket != null)
			{
				server.Close();
				ServerStartButton.Content = Remote.Language.Find(off => ServerStartButton.Content, this, "Start Server");
				//ServerStartButton.Content = "Start Server";
			}
			else
			{
				server = new SOCKET.Server(Settings.s.remoteDesktopPort);
				if (server.Listen())
				{
					server.StartReceiveAsync(OnConnectionAccept);
					ServerStartButton.Content = Remote.Language.Find(on => ServerStartButton.Content, this, "Stop Server");
					//ServerStartButton.Content = "Stop Server";

				}
			}

			//cw.WriteLine(Remote.Language.Find(() => ServerStartButton.Content, this, ""));
		}
		//Based on: http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type
		public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
		{
			if (depObj != null)
			{
				for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
				{
					DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
					if (child != null && child is T)
					{
						yield return (T)child;
					}

					foreach (T childOfChild in FindVisualChildren<T>(child))
					{
						yield return childOfChild;
					}
				}
			}
		}

		private void ConnectedComputers_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			// Only show panel if we have something selected
			if (ConnectedComputers.SelectedIndex >= 0)
			{
				StackPanel sp = connectedComputersItems[ConnectedComputers.SelectedIndex];
				//ClientData cd = connectedComputersBinding[sp];
				ClientData cd = clients[sp];

				if (ConnectedInfo.Visibility != System.Windows.Visibility.Visible)
				{
					ConnectedInfo.Visibility = System.Windows.Visibility.Visible;
				}

				AddressConnected.Content = cd.client.ClientAddress;

				if (cd.remoteDesktopRequest)
				{
					lRemoteDesktopRequest.Visibility = System.Windows.Visibility.Visible;
					RemoteDesktopRequestAcceptButton.Visibility = System.Windows.Visibility.Visible;
				}
				else
				{
					lRemoteDesktopRequest.Visibility = System.Windows.Visibility.Hidden;
					RemoteDesktopRequestAcceptButton.Visibility = System.Windows.Visibility.Hidden;
				}
			}
		}

		private void bSettings_Click(object sender, RoutedEventArgs e)
		{
			if (bSettings.IsChecked == true)
			{
				SettingsFlyout.IsOpen = true;
			}
			else
			{
				SettingsFlyout.IsOpen = false;
			}
		}

		private void GenericComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			ComboBox cb = sender as ComboBox;
			// Should never be false
			if (cb != null)
			{
				//bindings[cb.Name].SetValue(bindings[cb.Name].)
				BindingEntry be = bindings[cb.Name];
				if (be.parent != null)
				{
					be.fi.SetValue(be.parent.GetValue(Settings.s), cb.SelectedIndex);
				}
				else
				{
					be.fi.SetValue(Settings.s, cb.SelectedIndex);
				}
			}
		}

		private void UserNameTextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			Settings.s.name = UserNameTextBox.Text;
		}

		private void PortTextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			int temp;
			if (!Int32.TryParse(PortTextBox.Text, out temp))
			{
				// What should we do? Nothing right now :(
				return;
			}
			else
			{
				Settings.s.remoteDesktopPort = temp;
			}
		}
		private void Bind<T>(string name, Expression<Func<T>> memberExpression, bool parent)
		{
			var memberExp = memberExpression.Body as MemberExpression;
			MemberInfo memberInfo = memberExp.Member;
			switch (memberInfo.MemberType)
			{
				case MemberTypes.All:
					break;
				case MemberTypes.Constructor:
					break;
				case MemberTypes.Custom:
					break;
				case MemberTypes.Event:
					break;
				case MemberTypes.Field:
					// Save it
					if (parent)
					{
						memberExp = memberExp.Expression as MemberExpression;
						bindings[name] = new BindingEntry() { fi = memberInfo as FieldInfo, parent = memberExp.Member as FieldInfo };
					}
					else
					{
						bindings[name] = new BindingEntry() { fi = memberInfo as FieldInfo, parent = null };
					}
					break;
				case MemberTypes.Method:
					break;
				case MemberTypes.NestedType:
					break;
				case MemberTypes.Property:
					break;
				case MemberTypes.TypeInfo:
					break;
				default:
					break;
			}
		}
		private class BindingEntry
		{
			public FieldInfo fi;
			public FieldInfo parent;
		}
		public class ClientData
		{
			public string name;
			public SOCKET.Client client;

			public Label lName;
			public StackPanel sp;

			public bool remoteDesktopRequest;
		}

		private void RemoteDesktopRequestAcceptButton_Click(object sender, RoutedEventArgs e)
		{
			WindowState = System.Windows.WindowState.Minimized;
			loader.Show();
			// Do we need it?
			loader.Activate();

			loader.ChangeText("Wating for Data...");
			StackPanel sp = connectedComputersItems[ConnectedComputers.SelectedIndex];
			ClientData cd = clients[sp];

			cd.client.pmOut.New();
			cd.client.pmOut.Write(Command.REMOTE_DESKTOP_CAPTURE_INFO_REQUEST);
			cd.client.pmOut.End();

			if (cd.client.SendSafe())
			{
				// We need the set lastCommand to this, else if the connection fails midway there is no way knowing what to do
				lastCommand = Command.REMOTE_DESKTOP_CAPTURE_INFO_REQUEST;
			}
			else
			{

			}
		}
		private void RemoteDesktopConnectButton_Click(object sender, RoutedEventArgs e)
		{
			StackPanel sp = connectedComputersItems[ConnectedComputers.SelectedIndex];
			//ClientData cd = connectedComputersBinding[sp];
			ClientData cd = clients[sp];

			cd.client.pmOut.New();
			cd.client.pmOut.Write(Command.REMOTE_DESKTOP_REQUEST);
			cd.client.pmOut.End();

			if (cd.client.SendSafe())
			{
				cw.WriteLine(Remote.Language.Find("RemoteDesktopRequest", this, "Remote Desktop Request was sent to {0} at {1}"), cd.name, cd.client.ClientAddress);
				return;
			}
			else
			{
				// Should we do this here?
				/*cw.WriteLine(client.lastSendException.Message);
				client.Close();
				client = null;*/
			}
		}
		public class Clients : IEnumerable<ClientData>
		{
			private Dictionary<StackPanel, ClientData> spDic = new Dictionary<StackPanel,ClientData>();
			private Dictionary<SOCKET.Client, ClientData> scDic = new Dictionary<SOCKET.Client, ClientData>();
			public ClientData this[StackPanel sp]
			{
				get
				{
					return spDic[sp];
				}
				set
				{
					spDic[sp] = value;
					scDic[value.client] = value;
				}
			}
			public ClientData this[SOCKET.Client sc]
			{
				get
				{
					return scDic[sc];
				}
				/*set
				{
					scDic[sc] = value;
				}*/
			}
			public void Remove(ClientData cd)
			{
				spDic.Remove(cd.sp);
				scDic.Remove(cd.client);
			}
			public IEnumerator<ClientData> GetEnumerator()
			{
				foreach (ClientData item in spDic.Values)
				{
					yield return item;
				}
			}

			System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}
	}
}


text:
require "spec_helper"
require "./plugins/google.rb"

describe Google do
  describe "search" do
    it "should return a result" do
      Google.search("cows").should =~ /^.* : https?:\/\/.*$/
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CreateVotes < ActiveRecord::Migration
  def change
    create_table :votes do |t|
      t.jsonb :data, null: false, default: {}
    end
  end
end


text:
package com.filmon.maven.packaging;

import org.apache.maven.plugin.MojoExecutionException;

public enum AppEntryPointNameTruncation {
    LEFT ("-etl"),
    RIGHT ("-etr"),
    NONE ("-etn");

    private final String value;

    public static AppEntryPointNameTruncation parseAppEntryPointNameTruncation(String arg)
            throws MojoExecutionException {
        if (arg == null) {
            return NONE;
        } else if (arg.toLowerCase().equals("left")) {
            return LEFT;
        } else if (arg.toLowerCase().equals("right")) {
            return RIGHT;
        } else {
            throw new MojoExecutionException("Illegal application entry point truncation method. " +
                                             "Only values 'left', 'right' and 'none' are allowed.");
        }
    }

    private  AppEntryPointNameTruncation(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return getValue();
    }
}


text:
if [ "$JAVA_HOME" = "" ]
then
  echo "JAVA_HOME must be set and valid to run $0" ; exit 1
fi

VERSION=1.6.3-SNAPSHOT

$JAVA_HOME/bin/java -Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=45999 \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.ssl=false \
-Djava.rmi.server.hostname=localhost \
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1045 \
-javaagent:"$(dirname $0)/../../../../../agent/jvm/target/jolokia-jvm-${VERSION}.jar=port=8779" \
-classpath "$(dirname $0)/../../../../jmx-adapter/target/jolokia-jmx-adapter-${VERSION}-standalone.jar:$(dirname $0)/../../../target/jolokia-kubernetes-1.6.3-SNAPSHOT-standalone.jar:$HOME/.m2/repository/io/kubernetes/client-java/5.0.0/client-java-5.0.0.jar:$JAVA_HOME/lib/jconsole.jar:$JAVA_HOME/classes" \
-Dapplication.home=$JAVA_HOME \
-Xms8m -Djconsole.showOutputViewer \
sun.tools.jconsole.JConsole


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customTitle"
        android:textColor="#80000000"
        android:text="@string/signalStrength" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customEntry"
        android:layout_marginTop="4dp"
        android:textColor="#000000"
        android:text="@string/excellent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customTitle"
        android:textColor="#80000000"
        android:layout_marginTop="18dp"
        android:text="@string/ssid" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customEntry"
        android:layout_marginTop="4dp"
        android:textColor="#000000"
        android:text="@string/ssidLit" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customTitle"
        android:textColor="#80000000"
        android:layout_marginTop="18dp"
        android:text="@string/security" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customEntry"
        android:layout_marginTop="4dp"
        android:textColor="#000000"
        android:text="@string/securityType" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customTitle"
        android:textColor="#80000000"
        android:layout_marginTop="18dp"
        android:text="@string/password" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customEntry"
        android:layout_marginTop="4dp"
        android:textColor="#000000"
        android:inputType="textPassword" />

    <CheckBox
        android:id="@+id/showPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/customEntry"
        android:textColor="#000000"
        android:text="@string/showPassword"
        android:layout_marginTop="18dp" />

</LinearLayout>


text:
package com.matianl.explore.java7concurrency.Chapter2.ch2_recipe1_problem.src.com.packtpub.java7.concurrency.chapter2.recipe1.task;

/**
 * This class simulates a company that pays a salary an
 * insert money into an account
 *
 */
public class Company implements Runnable {

	/**
	 * The account affected by the operations
	 */
	private Account account;

	/**
	 * Constructor of the class. Initializes the account
	 * @param account the account affected by the operations
	 */
	public Company(Account account) {
		this.account=account;
	}

	/**
	 * Core method of the Runnable
	 */
	public void run() {
		for (int i=0; i<100; i++){
			account.addAmount(1000);
		}
	}

}


text:
#include "tiledb.h"
#include <cstdio>

int main() {
  // Initialize context with the default configuration parameters
  TileDB_CTX* tiledb_ctx;
  tiledb_ctx_init(&tiledb_ctx, NULL);

  // Prepare cell buffers
  int buffer_a1[3];
  void* buffers[] = { buffer_a1 };
  size_t buffer_sizes[] = { sizeof(buffer_a1) };

  // Subarray and attributes
  int64_t subarray[] = { 3, 4, 2, 4 };
  const char* attributes[] = { "a1" };

  // Initialize array
  TileDB_ArrayIterator* tiledb_array_it;
  tiledb_array_iterator_init(
      tiledb_ctx,                                    // Context
      &tiledb_array_it,                              // Array iterator
      "my_workspace/sparse_arrays/my_array_B",       // Array name
      TILEDB_ARRAY_READ,                             // Mode
      subarray,                                      // Constrain in subarray
      attributes,                                    // Subset on attributes
      1,                                             // Number of attributes
      buffers,                                       // Buffers used internally
      buffer_sizes);                                 // Buffer sizes

  // Iterate over all values in subarray
  printf(" a1\n----\n");
  const int* a1_v;
  size_t a1_size;
  while(!tiledb_array_iterator_end(tiledb_array_it)) {
    // Get value
    tiledb_array_iterator_get_value(
        tiledb_array_it,     // Array iterator
        0,                   // Attribute id
        (const void**) &a1_v,// Value
        &a1_size);           // Value size (useful in variable-sized attributes)

    // Print value (if not a deletion)
    if(*a1_v != TILEDB_EMPTY_INT32)
      printf("%3d\n", *a1_v);

    // Advance iterator
    tiledb_array_iterator_next(tiledb_array_it);
  }

  // Finalize array
  tiledb_array_iterator_finalize(tiledb_array_it);

  // Finalize context
  tiledb_ctx_finalize(tiledb_ctx);

  return 0;
}


text:
package org.springframework.security.core.context;

import java.util.function.Supplier;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import org.springframework.security.core.Authentication;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;

class InheritableThreadLocalSecurityContextHolderStrategyTests {

	InheritableThreadLocalSecurityContextHolderStrategy strategy = new InheritableThreadLocalSecurityContextHolderStrategy();

	@AfterEach
	void clearContext() {
		this.strategy.clearContext();
	}

	@Test
	void deferredNotInvoked() {
		Supplier<SecurityContext> deferredContext = mock(Supplier.class);
		this.strategy.setDeferredContext(deferredContext);
		verifyNoInteractions(deferredContext);
	}

	@Test
	void deferredContext() {
		Authentication authentication = mock(Authentication.class);
		Supplier<SecurityContext> deferredContext = () -> new SecurityContextImpl(authentication);
		this.strategy.setDeferredContext(deferredContext);
		assertThat(this.strategy.getDeferredContext().get()).isEqualTo(deferredContext.get());
		assertThat(this.strategy.getContext()).isEqualTo(deferredContext.get());
	}

	@Test
	void deferredContextValidates() {
		this.strategy.setDeferredContext(() -> null);
		Supplier<SecurityContext> deferredContext = this.strategy.getDeferredContext();
		assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> deferredContext.get());
	}

	@Test
	void context() {
		Authentication authentication = mock(Authentication.class);
		SecurityContext context = new SecurityContextImpl(authentication);
		this.strategy.setContext(context);
		assertThat(this.strategy.getContext()).isEqualTo(context);
		assertThat(this.strategy.getDeferredContext().get()).isEqualTo(context);
	}

	@Test
	void contextValidates() {
		assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.strategy.setContext(null));
	}

	@Test
	void getContextWhenEmptyThenReturnsSameInstance() {
		Authentication authentication = mock(Authentication.class);
		this.strategy.getContext().setAuthentication(authentication);
		assertThat(this.strategy.getContext().getAuthentication()).isEqualTo(authentication);
	}

}


text:
[![Build Status](https://travis-ci.org/maschall/cookbook.svg?branch=gitignore-bin)](https://travis-ci.org/maschall/cookbook)

# Cookbook

## About
Cookbook is a CLI for creating projects from a template.

The intention of this project is to get any project off the ground as fast as possible. It is not intended to be opinionated but to serve as another tool in the tool chest.

## Installation
Eventually this will be shipped with homebrew, but not until we get to Beta or V1

Until then you can:
git clone git@github.com:maschall/cookbook
bundle install --binstubs
rake homebrew

## License

Cookbook is Copyright (c) 2014 Mark Schall.  It is free software, and may be redistributed under the terms specified in the [LICENSE.txt](LICENSE.txt) file


text:
package com.planet_ink.coffee_mud.Libraries.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.Map.Entry;

public interface WorldMap extends CMLibrary
{
	public final static long ROOM_EXPIRATION_MILLIS=2500000;

	/************************************************************************/
	/**							 AREAS										*/
	/************************************************************************/
	public int numAreas();
	public void addArea(Area newOne);
	public void delArea(Area oneToDel);
	public Area getArea(String calledThis);
	public Area findAreaStartsWith(String calledThis);
	public Area findArea(String calledThis);
	public Area getDefaultParentArea();
	public Enumeration<Area> areas();
	public Enumeration<Area> mundaneAreas();
	public Enumeration<Area> spaceAreas();
	public Area getFirstArea();
	public Area getRandomArea();
	public void obliterateArea(Area theOne);
	public void renamedArea(Area theA);

	/************************************************************************/
	/**							 ROOMS										*/
	/************************************************************************/
	public int numRooms();
	public Enumeration<String> roomIDs();
	public String getExtendedRoomID(final Room R);
	public String getExtendedTwinRoomIDs(final Room R1,final Room R2);
	public Room getRoom(Room room);
	public Room getRoom(String calledThis);
	public Room getRoom(Enumeration<Room> roomSet, String calledThis);
	public Enumeration<Room> rooms();
	public Enumeration<Room> roomsFilled();
	public Room getRandomRoom();
	public void renameRooms(Area A, String oldName, List<Room> allMyDamnRooms);
	public void obliterateRoom(Room deadRoom);
	public Room findConnectingRoom(Room room);
	public int getRoomDir(Room from, Room to);
	public int getExitDir(Room from, Exit to);
	public Area getTargetArea(Room from, Exit to);
	public Room getTargetRoom(Room from, Exit to);

	/************************************************************************/
	/**								SEARCH TOOLS 							*/
	/************************************************************************/
	public List<Room> findWorldRoomsLiberally(MOB mob, String cmd, String srchWhatAERIPMVK, int timePct, long maxMillis);
	public Room findWorldRoomLiberally(MOB mob, String cmd, String srchWhatAERIPMVK, int timePct, long maxMillis);
	public List<Room> findAreaRoomsLiberally(MOB mob, Area A, String cmd, String srchWhatAERIPMVK, int timePct);
	public Room findAreaRoomLiberally(MOB mob, Area A, String cmd, String srchWhatAERIPMVK, int timePct);
	public List<Room> findRooms(Enumeration<Room> rooms, MOB mob, String srchStr, boolean displayOnly, int timePct);
	public Room findFirstRoom(Enumeration<Room> rooms, MOB mob, String srchStr, boolean displayOnly, int timePct);
	public MOB findFirstInhabitant(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public List<MOB> findInhabitants(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public List<Item> findRoomItems(Enumeration<Room> rooms, MOB mob, String srchStr, boolean anyItems, int timePct);
	public Item findFirstRoomItem(Enumeration<Room> rooms, MOB mob, String srchStr, boolean anyItems, int timePct);
	public List<Environmental> findShopStock(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public Environmental findFirstShopStock(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public List<Environmental> findShopStockers(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public Environmental findFirstShopStocker(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public List<Item> findInventory(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public Item findFirstInventory(Enumeration<Room> rooms, MOB mob, String srchStr, int timePct);
	public boolean isHere(CMObject E2, Area here);
	public boolean isHere(CMObject E2, Room here);

	/************************************************************************/
	/**							 ROOM-AREA-UTILITIES						*/
	/************************************************************************/
	public void resetArea(Area area);
	public void resetRoom(Room room);
	public void resetRoom(Room room, boolean rebuildGrids);
	public Room getStartRoom(Environmental E);
	public Area getStartArea(Environmental E);
	public Room roomLocation(Environmental E);
	public void emptyRoom(Room room, Room toRoom, boolean clearPlayers);
	public void emptyAreaAndDestroyRooms(Area A);
	public boolean hasASky(Room room);
	public boolean isClearableRoom(Room room);
	public String createNewExit(Room from, Room room, int direction);
	public Area areaLocation(CMObject E);
	public ThreadGroup getOwnedThreadGroup(CMObject E);
	public boolean explored(Room R);
	public CMFile.CMVFSDir getMapRoot(final CMFile.CMVFSDir root);

	/************************************************************************/
	/**						WORLD OBJECT INDEXES							*/
	/************************************************************************/
	public void registerWorldObjectLoaded(Area area, Room room, CMObject o);
	public void registerWorldObjectDestroyed(Area area, Room room, CMObject o);
	public Enumeration<LocatedPair> scriptHosts(Area area);
	public Deity getDeity(String calledThis);
	public Enumeration<Deity> deities();
	public PostOffice getPostOffice(String chain, String areaNameOrBranch);
	public Enumeration<PostOffice> postOffices();
	public Banker getBank(String chain, String areaNameOrBranch);
	public Enumeration<Banker> banks();
	public Iterator<String> bankChains(Area AreaOrNull);
	public Auctioneer getAuctionHouse(String chain, String areaNameOrBranch);
	public Enumeration<Auctioneer> auctionHouses();
	public BoardableShip getShip(String calledThis);
	public Enumeration<BoardableShip> ships();
	public Room getSafeRoomToMovePropertyTo(Room room, PrivateProperty I);

	/************************************************************************/
	/**							 SPACE METHODS 								*/
	/************************************************************************/
	public Enumeration<Area> areasPlusShips();
	public long getRelativeSpeed(SpaceObject O1, SpaceObject O2);
	public int numSpaceObjects();
	public boolean isObjectInSpace(SpaceObject O);
	public void delObjectInSpace(SpaceObject O);
	public void addObjectToSpace(SpaceObject O, long[] coords);
	public long getDistanceFrom(SpaceObject O1, SpaceObject O2);
	public long getDistanceFrom(final long[] coord1, final long[] coord2);
	public double[] getDirection(SpaceObject FROM, SpaceObject TO);
	public long[] getLocation(long[] oldLocation, double[] direction, long distance);
	public void moveSpaceObject(SpaceObject O);
	public void moveSpaceObject(SpaceObject O, long[] coords);
	public void moveSpaceObject(SpaceObject O, double[] newDirection, long newAccelleration);
	public SpaceObject getSpaceObject(CMObject o, boolean ignoreMobs);
	public Enumeration<SpaceObject> getSpaceObjects();
	public Enumeration<Entry<SpaceObject, List<WeakReference<TrackingVector<SpaceObject>>>>>  getSpaceObjectEntries();
	public List<SpaceObject> getSpaceObjectsWithin(SpaceObject ofObj, long minDistance, long maxDistance);
	public List<SpaceObject> getSpaceObjectsWithin(final long[] centerCoordinates, long minDistance, long maxDistance);
	public SpaceObject findSpaceObject(String s, boolean exactOnly);

	/************************************************************************/
	/**							 MESSAGES	 								*/
	/************************************************************************/
	public void addGlobalHandler(MsgListener E, int category);
	public void delGlobalHandler(MsgListener E, int category);
	public MOB deity();
	public MOB getFactoryMOBInAnyRoom();
	public MOB getFactoryMOB(Room R);
	public boolean sendGlobalMessage(MOB host, int category, CMMsg msg);

	/************************************************************************/
	/**							 HELPER CLASSES								*/
	/************************************************************************/
	public static class LocatedPair
	{
		private final WeakReference<Room> roomW;
		private final WeakReference<PhysicalAgent> objW;
		public Room room(){return roomW.get();}
		public PhysicalAgent obj(){return objW.get();}
		public LocatedPair(final Room room, final PhysicalAgent obj)
		{ this.roomW=new WeakReference<Room>(room); this.objW=new WeakReference<PhysicalAgent>(obj);}
	}

	public static Filterer<Area> planetsAreaFilter=new Filterer<Area>()
	{
		@Override
		public boolean passesFilter(Area obj)
		{
			return (obj instanceof SpaceObject) && (!(obj instanceof SpaceShip));
		}
	};

	public static Filterer<Area> spaceShipsAreaFilter=new Filterer<Area>()
	{
		@Override
		public boolean passesFilter(Area obj)
		{
			return (obj instanceof SpaceObject) && (obj instanceof SpaceShip);
		}
	};

	public static Filterer<Area> mundaneAreaFilter=new Filterer<Area>()
	{
		@Override
		public boolean passesFilter(Area obj)
		{
			return !(obj instanceof SpaceObject);
		}
	};

	public static class CrossExit
	{
		public int x;
		public int y;
		public int dir;
		public String destRoomID="";
		public boolean out=false;
		public static CrossExit make(int xx, int xy, int xdir, String xdestRoomID, boolean xout)
		{   final CrossExit EX=new CrossExit();
			EX.x=xx;EX.y=xy;EX.dir=xdir;EX.destRoomID=xdestRoomID;EX.out=xout;
			return EX;
		}
	}
}


text:
package parse

import (
	"encoding/binary"
	"errors"
	"os"
)

const pdbAuthStreamSignature int32 = 0x01312E94

type pdbHeader struct {
	Description          [0x20]byte // 0x00-0x20
	PageSize             int32      // 0x20-0x24
	Unknown1             int32      // 0x24-0x28 0x00000002
	NumberOfPages        int32      // 0x28-0x2C
	StreamDirectoryBytes int32      // 0x2C-0x30
	Unknown2             int32      // 0x30-0x34 0x00000000
	StreamDirectoryPage  int32      // 0x34-0x38
}

type pdbAuthStream struct {
	Signature     int32      // 0x00-0x04 pdbAuthStreamSignature
	Unknown       int32      // 0x04-0x08
	TimeDateStamp int32      // 0x08-0x0C
	Guid          [0x10]byte // 0x0C-0x1C
}

func ParsePdb(file *os.File) (*DebugId, error) {
	var pdb pdbHeader
	// Read PDB header
	if err := binary.Read(file, binary.LittleEndian, &pdb); err != nil {
		return nil, err
	}
	pageSize := int64(pdb.PageSize)
	// Seek to PDB stream directory list
	if _, err := file.Seek(int64(pdb.StreamDirectoryPage)*pageSize, 0); err != nil {
		return nil, err
	}
	// Read first stream directory offset
	var stream_dir_page int32
	if err := binary.Read(file, binary.LittleEndian, &stream_dir_page); err != nil {
		return nil, err
	}
	// Seek to first stream directory
	if _, err := file.Seek(int64(stream_dir_page)*pageSize, 0); err != nil {
		return nil, err
	}
	// Read stream count (first DWORD in stream directory)
	var stream_count int32
	if err := binary.Read(file, binary.LittleEndian, &stream_count); err != nil {
		return nil, err
	}
	if stream_count < 2 {
		return nil, errors.New("Unexpected PDB stream count (need at least 2 streams)")
	}
	// Skip all stream sizes
	var size int32
	if _, err := file.Seek(int64(stream_count)*int64(binary.Size(&size)), 1); err != nil {
		return nil, err
	}
	// Read stream offsets
	stream_offset := make([]int32, stream_count)
	if err := binary.Read(file, binary.LittleEndian, &stream_offset); err != nil {
		return nil, err
	}
	for _, offset := range stream_offset {
		// Seek to second stream with PDB debug information
		if _, err := file.Seek(int64(offset)*int64(pdb.PageSize), 0); err != nil {
			return nil, err
		}
		// Read PDB debug information
		var auth pdbAuthStream
		if err := binary.Read(file, binary.LittleEndian, &auth); err != nil {
			return nil, err
		}
		if auth.Signature == pdbAuthStreamSignature {
			return &DebugId{
				Guid{
					auth.Guid,
				},
				int(auth.TimeDateStamp),
			}, nil
		}
	}
	return nil, errors.New("Can't find PDB auth stream")
}


text:
namespace Wortell.XamarinForms
{
  public static class Initializer
  {
    public static void Init()
    {

    }
  }
}


text:
namespace toolbar_container {

// Used to move toolbar layout management to a container view.
BASE_DECLARE_FEATURE(kToolbarContainerEnabled);

}  // namespace toolbar_container

#endif  // IOS_CHROME_BROWSER_UI_TOOLBAR_CONTAINER_TOOLBAR_CONTAINER_FEATURES_H_


text:
package org.commonjava.emb.boot.log;

import org.apache.maven.repository.ArtifactTransferEvent;
import org.apache.maven.repository.ArtifactTransferListener;
import org.apache.maven.repository.ArtifactTransferResource;

import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

/**
 *
 */
public class BatchTransferListener
    implements ArtifactTransferListener
{
    protected PrintStream out;

    private boolean showChecksumEvents;

    public BatchTransferListener( final PrintStream out )
    {
        this.out = ( out != null ) ? out : System.out;
    }

    protected boolean showEvent( final ArtifactTransferEvent event )
    {
        if ( event.getResource() == null )
        {
            return true;
        }

        final String resource = event.getResource().getName();

        if ( resource == null || resource.trim().length() == 0 )
        {
            return true;
        }

        if ( resource.endsWith( ".sha1" ) || resource.endsWith( ".md5" ) )
        {
            return showChecksumEvents;
        }

        return true;
    }

    public void transferInitiated( final ArtifactTransferEvent transferEvent )
    {
        if ( !showEvent( transferEvent ) )
        {
            return;
        }

        doInitiated( transferEvent );
    }

    protected void doInitiated( final ArtifactTransferEvent transferEvent )
    {
        final String message =
            transferEvent.getRequestType() == ArtifactTransferEvent.REQUEST_PUT ? "Uploading" : "Downloading";

        out.println( message + ": " + transferEvent.getResource().getUrl() );
    }

    public void transferStarted( final ArtifactTransferEvent transferEvent )
    {
        if ( !showEvent( transferEvent ) )
        {
            return;
        }

        doStarted( transferEvent );
    }

    protected void doStarted( final ArtifactTransferEvent transferEvent )
    {
        // to be overriden by sub classes
    }

    public void transferProgress( final ArtifactTransferEvent transferEvent )
    {
        if ( !showEvent( transferEvent ) )
        {
            return;
        }

        doProgress( transferEvent );
    }

    protected void doProgress( final ArtifactTransferEvent transferEvent )
    {
        // to be overriden by sub classes
    }

    public void transferCompleted( final ArtifactTransferEvent transferEvent )
    {
        if ( !showEvent( transferEvent ) )
        {
            return;
        }

        doCompleted( transferEvent );
    }

    protected void doCompleted( final ArtifactTransferEvent transferEvent )
    {
        final ArtifactTransferResource artifact = transferEvent.getResource();
        final long contentLength = transferEvent.getTransferredBytes();
        if ( contentLength >= 0 )
        {
            final String type =
                ( transferEvent.getRequestType() == ArtifactTransferEvent.REQUEST_PUT ? "Uploaded" : "Downloaded" );
            final String len = contentLength >= 1024 ? toKB( contentLength ) + " KB" : contentLength + " B";

            String throughput = "";
            final long duration = System.currentTimeMillis() - artifact.getTransferStartTime();
            if ( duration > 0 )
            {
                final DecimalFormat format = new DecimalFormat( "0.0", new DecimalFormatSymbols( Locale.ENGLISH ) );
                final double kbPerSec = ( contentLength / 1024.0 ) / ( duration / 1000.0 );
                throughput = " at " + format.format( kbPerSec ) + " KB/sec";
            }

            out.println( type + ": " + artifact.getUrl() + " (" + len + throughput + ")" );
        }
    }

    protected long toKB( final long bytes )
    {
        return ( bytes + 1023 ) / 1024;
    }

    public boolean isShowChecksumEvents()
    {
        return showChecksumEvents;
    }

    public void setShowChecksumEvents( final boolean showChecksumEvents )
    {
        this.showChecksumEvents = showChecksumEvents;
    }

}


text:
class FlightsController < ApplicationController
  def index
  end

  def show
    @pilot = Pilot.find_by(id: params[:pilot_id])
    @flight = Flight.find_by(id: params[:id])
  end

  def new
    @pilot = Pilot.find_by(id: params[:pilot_id])
    if !can_edit?
      flash[:notice] = "You do not have permission to edit this page"
      redirect_to :back
    else
      @flight = @pilot.flights.new
      @flight_airplane = @flight.build_flight_airplane
      @airplane = @flight_airplane.build_airplane
    end
  end

  def create
    @pilot = Pilot.find_by(id: params[:pilot_id])
    if can_edit?
      @flight = @pilot.log_book.flights.create(flight_params)
      @flight.flight_airplane.flight = @flight
      @flight.update_duration(params[:flight][:hours], params[:flight][:minutes])
      if @flight.save!
        redirect_to pilot_path(@flight.pilot)
      else
        render :new
      end
    else
      flash[:notice] = "You do not have permission to edit this page"
      redirect_to :back
    end
  end

  def edit
    @pilot = Pilot.find_by(id: params[:pilot_id])
    @flight = Flight.find_by(id: params[:id])
    if !can_edit?
      flash[:notice] = "You do not have permission to edit this page"
      redirect_to :back
    end
  end

  def update
    @pilot = Pilot.find_by(id: params[:pilot_id])
    @flight = Flight.find_by(id: params[:id])
    if !can_edit?
      flash[:notice] = "You do not have permission to edit this page"
      redirect_to :back
    else
      @flight.update_attributes(flight_params)
      @flight.update_duration(params[:flight][:hours], params[:flight][:minutes])
      @flight.save
      redirect_to pilot_flight_path(@pilot, @flight)
    end
  end

  def destroy
    @pilot = Pilot.find_by(id: params[:pilot_id])
    @flight = Flight.find_by(id: params[:id])
    if can_edit?
      @flight.destroy
      redirect_to pilot_path(@pilot)
    else
      flash[:notice] = "You can not delete this flight"
      redirect_to :back
    end
  end

  private

  def flight_params
    params.require(:flight).permit(:date, :origin, :destination, :notes, :instructor, flight_airplane_attributes: [:tail_number, airplane_attributes: [:make, :model]])
  end
end


text:
'use strict'
var arrayify = require('array-back')
var t = require('typical')
var objectGet = require('object-get')
var testValue = require('test-value')

/**
Useful functions for working with objects
@module object-tools
@typicalname o
@example
var o = require('object-tools')
*/
exports.extend = extend
exports.clone = clone
exports.every = every
exports.each = each
exports.exists = testValue
exports.without = without
exports.extract = extract
exports.where = where
exports.select = select
exports.get = objectGet

/**
Merge a list of objects, left to right, into one - to a maximum depth of 10.

@param {...object} object - a sequence of object instances to be extended
@returns {object}
@static
@example
> o.extend({ one: 1, three: 3 }, { one: 'one', two: 2 }, { four: 4 })
{ one: 'one',
  three: 3,
  two: 2,
  four: 4 }
*/
function extend () {
  var depth = 0
  var args = arrayify(arguments)
  if (!args.length) return {}
  var last = args[args.length - 1]
  if (t.isPlainObject(last) && '__depth' in last) {
    depth = last.__depth
    args.pop()
  }
  return args.reduce(function (output, curr) {
    if (typeof curr !== 'object') return output
    for (var prop in curr) {
      var value = curr[prop]
      if (value === undefined) break
      if (t.isObject(value) && !Array.isArray(value) && depth < 10) {
        if (!output[prop]) output[prop] = {}
        output[prop] = extend(output[prop], value, { __depth: ++depth })
      } else {
        output[prop] = value
      }
    }
    return output
  }, {})
}

/**
Clones an object or array
@param {object|array} input - the input to clone
@returns {object|array}
@static
@example
> date = new Date()
Fri May 09 2014 13:54:34 GMT+0200 (CEST)
> o.clone(date)
{}  // a Date instance doesn't own any properties
> date.clive = 'hater'
'hater'
> o.clone(date)
{ clive: 'hater' }
> array = [1,2,3]
[ 1, 2, 3 ]
> newArray = o.clone(array)
[ 1, 2, 3 ]
> array === newArray
false
*/
function clone (input) {
  var output
  if (typeof input === 'object' && !Array.isArray(input) && input !== null) {
    output = {}
    for (var prop in input) {
      output[prop] = input[prop]
    }
    return output
  } else if (Array.isArray(input)) {
    output = []
    input.forEach(function (item) {
      output.push(clone(item))
    })
    return output
  } else {
    return input
  }
}

/**
Returns true if the supplied iterator function returns true for every property in the object
@param {object} - the object to inspect
@param {Function} - the iterator function to run against each key/value pair, the args are `(value, key)`.
@returns {boolean}
@static
@example
> function aboveTen(input){ return input > 10; }
> o.every({ eggs: 12, carrots: 30, peas: 100 }, aboveTen)
true
> o.every({ eggs: 6, carrots: 30, peas: 100 }, aboveTen)
false
*/
function every (object, iterator) {
  var result = true
  for (var prop in object) {
    result = result && iterator(object[prop], prop)
  }
  return result
}

/**
Runs the iterator function against every key/value pair in the input object
@param {object} - the object to iterate
@param {Function} - the iterator function to run against each key/value pair, the args are `(value, key)`.
@static
@example
> var total = 0
> function addToTotal(n){ total += n; }
> o.each({ eggs: 3, celery: 2, carrots: 1 }, addToTotal)
> total
6
*/
function each (object, callback) {
  for (var prop in object) {
    callback(object[prop], prop)
  }
}

/**
returns true if the key/value pairs in `query` also exist identically in `object`.
Also supports RegExp values in `query`. If the `query` property begins with `!` then test is negated.

@method exists
@param object {object} - the object to examine
@param query {object} - the key/value pairs to look for
@returns {boolean}
@static
@example
> o.exists({ a: 1, b: 2}, {a: 0})
false
> o.exists({ a: 1, b: 2}, {a: 1})
true
> o.exists({ a: 1, b: 2}, {'!a': 1})
false
> o.exists({ name: 'clive hater' }, { name: /clive/ })
true
> o.exists({ name: 'clive hater' }, { '!name': /ian/ })
true
> o.exists({ a: 1}, { a: function(n){ return n > 0; } })
true
> o.exists({ a: 1}, { a: function(n){ return n > 1; } })
false
*/

/**
Returns a clone of the object minus the specified properties. See also {@link module:object-tools.select}.
@param {object} - the input object
@param {string|string[]} - a single property, or array of properties to omit
@returns {object}
@static
@example
> o.without({ a: 1, b: 2, c: 3}, 'b')
{ a: 1, c: 3 }
> o.without({ a: 1, b: 2, c: 3}, ['b', 'a'])
{ c: 3 }
*/
function without (object, toRemove) {
  toRemove = arrayify(toRemove)
  var output = clone(object)
  toRemove.forEach(function (remove) {
    delete output[remove]
  })
  return output
}

/**
Returns a new object containing the key/value pairs which satisfy the query
@param {object} - The input object
@param {string[]|function(*, string)} - Either an array of property names, or a function. The function is called with `(value, key)` and must return `true` to be included in the output.
@returns {object}
@static
@example
> object = { a: 1, b: 0, c: 2 }
{ a: 1, b: 0, c: 2 }
> o.where(object, function(value, key){
      return value > 0
  })
{ a: 1, c: 2 }
> o.where(object, [ 'b' ])
{ b: 0 }
> object
{ a: 1, b: 0, c: 2 }
@since 1.2.0
*/
function where (object, query) {
  var output = {}
  var prop
  if (typeof query === 'function') {
    for (prop in object) {
      if (query(object[prop], prop) === true) output[prop] = object[prop]
    }
  } else if (Array.isArray(query)) {
    for (prop in object) {
      if (query.indexOf(prop) > -1) output[prop] = object[prop]
    }
  }
  return output
}

/**
identical to `o.where(object, query)` with one exception - the found properties are removed from the input `object`
@param {object} - The input object
@param {string[]|function(*, string)} - Either an array of property names, or a function. The function is called with `(value, key)` and must return `true` to be included in the output.
@returns {object}
@static
@example
> object = { a: 1, b: 0, c: 2 }
{ a: 1, b: 0, c: 2 }
> o.where(object, function(value, key){
      return value > 0
  })
{ a: 1, c: 2 }
> object
{ b: 0 }
@since 1.2.0
*/
function extract (object, query) {
  var output = where(object, query)
  for (var prop in output) {
    delete object[prop]
  }
  return output
}

/**
Returns a new object containing only the selected fields. See also {@link module:object-tools.without}.
@param {object} - the input object
@param {string|array} - a list of fields to return
@returns {object}
@static
*/
function select (object, fields) {
  return arrayify(fields).reduce(function (prev, curr) {
    prev[curr] = object[curr]
    return prev
  }, {})
}

/**
Returns the value at the given property.
@param object {object} - the input object
@param expression {string} - the property accessor expression
@returns {*}
@method get
@static
@memberof module:object-tools
@since 1.4.0
*/


text:
package org.elasticsearch.xpack.ml.aggs.categorization;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.search.aggregations.ParsedMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.xcontent.ObjectParser;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

class ParsedCategorization extends ParsedMultiBucketAggregation<ParsedCategorization.ParsedBucket> {

    @Override
    public String getType() {
        return CategorizeTextAggregationBuilder.NAME;
    }

    private static final ObjectParser<ParsedCategorization, Void> PARSER = new ObjectParser<>(
        ParsedCategorization.class.getSimpleName(),
        true,
        ParsedCategorization::new
    );
    static {
        declareMultiBucketAggregationFields(PARSER, ParsedBucket::fromXContent, ParsedBucket::fromXContent);
    }

    public static ParsedCategorization fromXContent(XContentParser parser, String name) throws IOException {
        ParsedCategorization aggregation = PARSER.parse(parser, null);
        aggregation.setName(name);
        return aggregation;
    }

    @Override
    public List<? extends Bucket> getBuckets() {
        return buckets;
    }

    public static class ParsedBucket extends ParsedMultiBucketAggregation.ParsedBucket implements MultiBucketsAggregation.Bucket {

        private InternalCategorizationAggregation.BucketKey key;

        protected void setKeyAsString(String keyAsString) {
            if (keyAsString == null) {
                key = null;
                return;
            }
            if (keyAsString.isEmpty()) {
                key = new InternalCategorizationAggregation.BucketKey(new BytesRef[0]);
                return;
            }
            String[] split = Strings.tokenizeToStringArray(keyAsString, " ");
            key = new InternalCategorizationAggregation.BucketKey(
                split == null
                    ? new BytesRef[] { new BytesRef(keyAsString) }
                    : Arrays.stream(split).map(BytesRef::new).toArray(BytesRef[]::new)
            );
        }

        @Override
        public Object getKey() {
            return key;
        }

        @Override
        public String getKeyAsString() {
            return key.asString();
        }

        @Override
        protected XContentBuilder keyToXContent(XContentBuilder builder) throws IOException {
            return builder.field(CommonFields.KEY.getPreferredName(), getKey());
        }

        static InternalCategorizationAggregation.BucketKey parsedKey(final XContentParser parser) throws IOException {
            if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
                String toSplit = parser.text();
                String[] split = Strings.tokenizeToStringArray(toSplit, " ");
                return new InternalCategorizationAggregation.BucketKey(
                    split == null
                        ? new BytesRef[] { new BytesRef(toSplit) }
                        : Arrays.stream(split).map(BytesRef::new).toArray(BytesRef[]::new)
                );
            } else {
                return new InternalCategorizationAggregation.BucketKey(
                    XContentParserUtils.parseList(parser, p -> new BytesRef(p.binaryValue())).toArray(BytesRef[]::new)
                );
            }
        }

        static ParsedBucket fromXContent(final XContentParser parser) throws IOException {
            return ParsedMultiBucketAggregation.ParsedBucket.parseXContent(
                parser,
                false,
                ParsedBucket::new,
                (p, bucket) -> bucket.key = parsedKey(p)
            );
        }

    }

}


text:
<?php

namespace Application\Model;

use Zend\Db\TableGateway\TableGateway;
use Application\Model\Affiliate;

class AffiliateTable
{
	protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}

	public function fetchAll($page=1, $take=25, &$count)
	{
		if($page < 1){
			$page = 1;
		} // if

		$select = new \Zend\Db\Sql\Select();
		$select->from($this->tableGateway->getTable());
		$select->order('lastname ASC');
		$select->offset(($page - 1) * $take);
		$select->limit($take);

		$results = $this->tableGateway->selectWith($select);

		$count = $this->getCount();

		$list = array();

		foreach($results as $result){
			$list[] = $result;
		} // foreach

		return $list;
	}

	public function getCount()
	{
		$stmt = $this->tableGateway->getAdapter()->createStatement("SELECT count(id) as count FROM affiliates");

		$results = $stmt->execute();

		$result = $results->current();

		if(!$result){
			return 0;
		} // if

		return $result['count'];
	}

	public function getAffiliate($id)
	{
		$id = (int)$id;
		$results = $this->tableGateway->select(array('id' => $id));
		$result = $results->current();

		if(!$result){
			return null;
		} // if

		return $result;
	}

	public function getAffiliateByFacebookId($fbid)
	{
		$fbid = (string)$fbid;
		$results = $this->tableGateway->select(array('facebookuserid' => $fbid));
		$result = $results->current();

		if(!$result){
			return null;
		} // if

		return $result;
	}

	public function save(Affiliate $affiliate)
	{
		$id = (int)$affiliate->id();
		$fid = (string)$affiliate->facebookUserId();

		$data = array(
			'facebookuserid' => $affiliate->facebookUserId(),
			'firstname' => $affiliate->firstName(),
			'lastname' => $affiliate->lastName(),
			'address1' => $affiliate->address1(),
			'address2' => $affiliate->address2(),
			'city' => $affiliate->city(),
			'state' => $affiliate->state(),
			'country' => $affiliate->country(),
			'postal' => $affiliate->postal(),
			'telephone' => $affiliate->telephone(),
			'emailaddress' => $affiliate->emailAddress(),
			'enabled' => $affiliate->enabled()	? 1 : 0
		);

		if($id > 0 && !empty($fid)){
			if($this->getAffiliate($id)){
				$this->tableGateway->update($data, array('id' => $id));
			} // if
			else{
				throw new \Exception("Could not locate Affiliate with id: $id");
			} // else
		} // if
		else{

			if(empty($fid)){
				throw new \Exception("An Affiliate must have a Facebook User ID.");
			} // if
			$this->tableGateway->insert($data);
			$affiliate->id((int)$this->tableGateway->lastInsertValue);
		} // else
	}
}


text:
import sling
from action import Action

# Outputs a list of transitions that represent a given document's frame graph.
class TransitionGenerator:
  # Bookkeeping for one frame.
  class FrameInfo:
    def __init__(self, handle):
      self.handle = handle
      self.type = None
      self.edges = []
      self.from_mention = False

      # Whether this frame has been evoked.
      self.output = False

  # Labeled edge between two frames. Each edge is used to issue a CONNECT,
  # EMBED, ELABORATE, or ASSIGN action.
  class Edge:
    def __init__(self, incoming=None, role=None, value=None):
      self.incoming = incoming
      self.role = role
      self.neighbor = value
      self.inverse = None
      self.used = False

  # Simple action that will be translated into an Action object later on.
  class SimpleAction:
    def __init__(self, t=None):
      self.action = Action(t)
      self.info = None
      self.other_info = None

  def __init__(self, commons):
    self.commons = commons
    self._id = commons["id"]
    self._isa = commons["isa"]

  # Returns whether 'handle' refers to another frame.
  def is_ref(self, handle):
    return type(handle) == sling.Frame

  # Creates a FrameInfo object for 'frame' and recursively for all frames
  # pointed to by it.
  def _init_info(self, frame, frame_info, initialized):
    if frame in initialized:
      return
    initialized[frame] = True

    info = frame_info.get(frame, None)
    if info is None:
      info = TransitionGenerator.FrameInfo(frame)
      frame_info[frame] = info

    pending = []
    for role, value in frame:
      if not self.is_ref(value) or role == self._id: continue
      if role == self._isa and value.islocal(): continue

      if role == self._isa and info.type is None:
        info.type = value
      else:
        edge = TransitionGenerator.Edge(incoming=False, role=role, value=value)
        info.edges.append(edge)
        if value == frame:
          edge.inverse = edge
          continue

        if value.islocal():
          nb_info = frame_info.get(value, None)
          if nb_info is None:
            nb_info = TransitionGenerator.FrameInfo(value)
            frame_info[value] = nb_info
          nb_edge = TransitionGenerator.Edge(
              incoming=True, role=role, value=frame)
          nb_info.edges.append(nb_edge)
          nb_edge.inverse = edge
          edge.inverse = nb_edge
          pending.append(value)

    # Initialize bookkeeping for all frames pointed to by this frame.
    for p in pending:
      self._init_info(p, frame_info, initialized)

  # Translates 'simple' action to an Action using indices from 'attention'.
  def _translate(self, attention, simple):
    action = Action(t=simple.action.type)
    if simple.action.length is not None:
      action.length = simple.action.length
    if simple.action.role is not None:
      action.role = simple.action.role

    if action.type == Action.EVOKE:
       action.label = simple.info.type
    elif action.type == Action.REFER:
      action.target = attention.index(simple.info.handle)
    elif action.type == Action.EMBED:
      action.label = simple.info.type
      action.target = attention.index(simple.other_info.handle)
    elif action.type == Action.ELABORATE:
      action.label = simple.info.type
      action.source = attention.index(simple.other_info.handle)
    elif action.type == Action.CONNECT:
      action.source = attention.index(simple.info.handle)
      action.target = attention.index(simple.other_info.handle)
    elif action.type == Action.ASSIGN:
      action.source = attention.index(simple.info.handle)
      action.label = simple.action.label

    return action

  # Updates frame indices in 'attention' as a result of the action 'simple'.
  def _update(self, attention, simple):
    t = simple.action.type
    if t in [Action.EVOKE, Action.EMBED, Action.ELABORATE]:
      # Insert a new frame at the center of attention.
      attention.insert(0, simple.info.handle)
    elif t in [Action.REFER, Action.ASSIGN, Action.CONNECT]:
      # Promote an existing frame to the center of attention.
      attention.remove(simple.info.handle)
      attention.insert(0, simple.info.handle)

  # Builds and returns a simple action of type 'type'.
  def _simple_action(self, type=None):
    return TransitionGenerator.SimpleAction(type)

  # Stores mentions starting or ending or both at a given token.
  class TokenToMentions:
    def __init__(self):
      self.starting = []
      self.ending = []
      self.singletons = []

    # Record 'mention' at starting at this token.
    def start(self, mention):
      if len(self.starting) > 0:
        # Check that the mention respects nesting.
        assert self.starting[-1].end >= mention.end
      self.starting.append(mention)

    # Record 'mention' as ending at this token.
    def end(self, mention):
      if len(self.ending) > 0:
        # Check that the mention respects nesting.
        assert self.ending[0].begin <= mention.begin
      self.ending.insert(0, mention)  # most-nested is at the front

    # Record 'mention' as starting and ending at this token.
    def singleton(self, mention):
      self.singletons.append(mention)

    # Returns if there are no mentions starting/ending at this token.
    def empty(self):
      return len(self.starting) + len(self.ending) + len(self.singletons) == 0

    # Returns a string representation of the object.
    def __repr__(self):
      return "Starting:" + str(self.starting) + ", Ending:" + \
        str(self.ending) + ", Singletons:" + str(self.singletons)

  # Generates transition sequence for 'document' which should be an instance of
  # AnnotatedDocument.
  def generate(self, document):
    frame_info = {}    # frame -> whether it is evoked from a span
    initialized = {}   # frame -> whether the frame's book-keeping is done

    # Initialize book-keeping for all evoked frames.
    for m in document.mentions:
      for evoked in m.evokes():
        self._init_info(evoked, frame_info, initialized)
        frame_info[evoked].from_mention = True

    # Initialize book-keeping for all thematic frames.
    for theme in document.themes:
      self._init_info(theme, frame_info, initialized)

    # Record start/end boundaries of all mentions.
    token_to_mentions = []
    for _ in range(len(document.tokens)):
      token_to_mentions.append(TransitionGenerator.TokenToMentions())

    for m in document.mentions:
      if m.length == 1:
        token_to_mentions[m.begin].singleton(m)
      else:
        token_to_mentions[m.begin].start(m)
        token_to_mentions[m.end - 1].end(m)

    # Single token mentions are handled via EVOKE(length=1), and others
    # are handled via MARK at the beginning token and EVOKE(length=None)
    # at the end token.

    simple_actions = []
    marked = {}   # frames for which we have output a MARK
    evoked = {}   # frames for which we have output an EVOKE
    for index in range(len(document.tokens)):
      t2m = token_to_mentions[index]

      # First evoke/refer the singleton mentions.
      for singleton in t2m.singletons:
        for frame in singleton.evokes():
          # If the frame is already evoked, refer to it.
          if frame in marked:
            assert frame in evoked, "Referring to marked but not evoked frame"
          if frame in evoked:
            refer = self._simple_action(Action.REFER)
            refer.info = frame_info[frame]
            refer.action.length = singleton.length  # should be 1
            simple_actions.append(refer)
            continue

          # Otherwise evoke a new frame.
          evoke = self._simple_action(Action.EVOKE)
          evoke.action.length = singleton.length  # should be 1
          evoke.info = frame_info[frame]
          evoke.action.label = evoke.info.type
          simple_actions.append(evoke)
          marked[frame] = True
          evoked[frame] = True

      # Output EVOKE for any frames whose spans end here.
      for mention in t2m.ending:
        assert mention.length > 1, mention.length  # singletons already handled
        for frame in mention.evokes():
          assert frame in marked   # frame should be already MARKed
          if frame in evoked:
            # Already handled via REFER at mention.begin.
            continue

          evoke = self._simple_action(Action.EVOKE)
          evoke.info = frame_info[frame]
          evoke.action.label = evoke.info.type
          simple_actions.append(evoke)
          evoked[frame] = True

      # Output MARK for any frames whose spans begin here.
      for mention in t2m.starting:
        assert mention.length > 1, mention.length  # singletons already handled
        for frame in mention.evokes():
          # Check if this is a fresh frame or a refer.
          if frame in marked:
            assert frame in evoked, "Referring to marked but not evoked frame"
          if frame in evoked:
            refer = self._simple_action(Action.REFER)
            refer.info = frame_info[frame]
            refer.action.length = mention.length
            simple_actions.append(refer)
            continue

          mark = self._simple_action(Action.MARK)
          mark.info = frame_info[frame]
          simple_actions.append(mark)
          marked[frame] = True

      # Move to the next token.
      simple_actions.append(self._simple_action(Action.SHIFT))
    simple_actions.append(self._simple_action(Action.STOP))

    # Recursively output more actions (e.g. CONNECT, EMBED, ELABORATE, ASSIGN)
    # from the current set of EVOKE/REFER actions. Then translate each
    # action using final attention indices. This is done in reverse order
    # for convenience.
    simple_actions.reverse()
    actions = []
    attention = []
    while len(simple_actions) > 0:
      simple_action = simple_actions.pop()
      actions.append(self._translate(attention, simple_action))
      self._update(attention, simple_action)
      t = simple_action.action.type
      if t == Action.EVOKE or t == Action.EMBED or t == Action.ELABORATE:
        simple_action.info.output = True

        # CONNECT actions triggered by the newly output frame.
        for e in simple_action.info.edges:
          if e.used: continue

          nb = frame_info.get(e.neighbor, None)
          if nb is not None and nb.output:
            connect = self._simple_action(Action.CONNECT)
            connect.action.role = e.role
            connect.info = nb if e.incoming else simple_action.info
            connect.other_info = simple_action.info if e.incoming else nb
            simple_actions.append(connect)
            e.used = True
            e.inverse.used = True

        # EMBED actions triggered by the newly output frame.
        for e in simple_action.info.edges:
          if e.used or not e.incoming: continue

          nb = frame_info.get(e.neighbor, None)
          if nb is not None and not nb.output and not nb.from_mention:
            embed = self._simple_action(Action.EMBED)
            embed.action.role = e.role
            embed.info = nb
            embed.other_info = simple_action.info
            simple_actions.append(embed)
            e.used = True
            e.inverse.used = True

        # ELABORATE actions triggered by the newly output frame.
        for e in simple_action.info.edges:
          if e.used or e.incoming: continue

          nb = frame_info.get(e.neighbor, None)
          if nb is not None and not nb.output and not nb.from_mention:
            elaborate = self._simple_action(Action.ELABORATE)
            elaborate.action.role = e.role
            elaborate.info = nb
            elaborate.other_info = simple_action.info
            simple_actions.append(elaborate)
            e.used = True
            e.inverse.used = True

        # ASSIGN actions triggered by the newly output frame.
        for e in simple_action.info.edges:
          if not e.used and not e.neighbor.islocal() and not e.incoming:
            assign = self._simple_action(Action.ASSIGN)
            assign.info = simple_action.info
            assign.action.role = e.role
            assign.action.label = e.neighbor
            simple_actions.append(assign)
            e.used = True

    return actions


text:
@interface RTTableViewController : UITableViewController

@end


text:
class SimulationCostStructure(object):

    def __init__(self):
        self.expandTechnology  = 0
        self.reagent           = 0
        self.labor             = 0
        self.facility          = 0
        self.equipmentUsage    = 0
        self.qualityControl    = 0
        self.totalCost         = 0
        self.costPerDose       = 0


text:
namespace media {

FFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine()
    : codec_context_(NULL),
      state_(kCreated) {
}

FFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() {
}

void FFmpegVideoDecodeEngine::Initialize(AVStream* stream, Task* done_cb) {
  AutoTaskRunner done_runner(done_cb);

  // Always try to use two threads for video decoding.  There is little reason
  // not to since current day CPUs tend to be multi-core and we measured
  // performance benefits on older machines such as P4s with hyperthreading.
  //
  // Handling decoding on separate threads also frees up the pipeline thread to
  // continue processing. Although it'd be nice to have the option of a single
  // decoding thread, FFmpeg treats having one thread the same as having zero
  // threads (i.e., avcodec_decode_video() will execute on the calling thread).
  // Yet another reason for having two threads :)
  //
  // TODO(scherkus): some video codecs might not like avcodec_thread_init()
  // being called on them... should attempt to find out which ones those are!
  static const int kDecodeThreads = 2;

  CHECK(state_ == kCreated);

  codec_context_ = stream->codec;
  codec_context_->flags2 |= CODEC_FLAG2_FAST;  // Enable faster H264 decode.
  // Enable motion vector search (potentially slow), strong deblocking filter
  // for damaged macroblocks, and set our error detection sensitivity.
  codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
  codec_context_->error_recognition = FF_ER_CAREFUL;

  // Serialize calls to avcodec_open().
  AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
  {
    AutoLock auto_lock(FFmpegLock::get()->lock());
    if (codec &&
        avcodec_thread_init(codec_context_, kDecodeThreads) >= 0 &&
        avcodec_open(codec_context_, codec) >= 0) {
      state_ = kNormal;
    } else {
      state_ = kError;
    }
  }
}

// Decodes one frame of video with the given buffer.
void FFmpegVideoDecodeEngine::DecodeFrame(const Buffer& buffer,
                                          AVFrame* yuv_frame,
                                          bool* got_frame,
                                          Task* done_cb) {
  AutoTaskRunner done_runner(done_cb);

  // Create a packet for input data.
  // Due to FFmpeg API changes we no longer have const read-only pointers.
  AVPacket packet;
  av_init_packet(&packet);
  packet.data = const_cast<uint8*>(buffer.GetData());
  packet.size = buffer.GetDataSize();

  // We don't allocate AVFrame on the stack since different versions of FFmpeg
  // may change the size of AVFrame, causing stack corruption.  The solution is
  // to let FFmpeg allocate the structure via avcodec_alloc_frame().
  int frame_decoded = 0;
  int result =
      avcodec_decode_video2(codec_context_, yuv_frame, &frame_decoded, &packet);

  // Log the problem if we can't decode a video frame and exit early.
  if (result < 0) {
    LOG(INFO) << "Error decoding a video frame with timestamp: "
              << buffer.GetTimestamp().InMicroseconds() << " us"
              << " , duration: "
              << buffer.GetDuration().InMicroseconds() << " us"
              << " , packet size: "
              << buffer.GetDataSize() << " bytes";
    *got_frame = false;
  } else {
    // If frame_decoded == 0, then no frame was produced.
    *got_frame = frame_decoded != 0;
  }
}

void FFmpegVideoDecodeEngine::Flush(Task* done_cb) {
  AutoTaskRunner done_runner(done_cb);

  avcodec_flush_buffers(codec_context_);
}

VideoSurface::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const {
  // J (Motion JPEG) versions of YUV are full range 0..255.
  // Regular (MPEG) YUV is 16..240.
  // For now we will ignore the distinction and treat them the same.
  switch (codec_context_->pix_fmt) {
    case PIX_FMT_YUV420P:
    case PIX_FMT_YUVJ420P:
      return VideoSurface::YV12;
      break;
    case PIX_FMT_YUV422P:
    case PIX_FMT_YUVJ422P:
      return VideoSurface::YV16;
      break;
    default:
      // TODO(scherkus): More formats here?
      return VideoSurface::INVALID;
  }
}

}  // namespace media


text:
  <meta charset="UTF-8">
  <title>Try it yourself</title>
  <link rel="stylesheet" type="text/css" href="app.bundle.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">