text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
#if !SILVERLIGHT
using Microsoft.Win32;
#endif
using Rawr;
using System.Threading;

namespace Rawr.UI
{
	public partial class MainPage : UserControl
	{
		public static ItemTooltip Tooltip { get; private set; }
		public static MainPage Instance { get; private set; }

		private bool _unsavedChanges = false;

		private Status status;
		public Status Status
		{
			set { status = value; }
			get
			{
				if (status == null) status = new Status();
				return status;
			}
		}

		private ItemBrowser itemSearch = null;
		public ItemBrowser ItemSearch
		{
			get
			{
				if (itemSearch == null) itemSearch = new ItemBrowser();
				return itemSearch;
			}
		}

		private Character character;
		public Character Character
		{
			get { return character; }
			set
			{
				if (value != null)
				{
					if (character != null)
					{
						character.CalculationsInvalidated -= new EventHandler(character_CalculationsInvalidated);
						character.AvailableItemsChanged -= new EventHandler(character_AvailableItemsChanged);
						character.ClassChanged -= new EventHandler(character_ClassChanged);
					}

					character = value;
					if (_batchCharacter != null && _batchCharacter.Character != character)
					{
						// we're loading a character that is not a batch character
						_batchCharacter = null;
					}
					character.IsLoading = true;

					DataContext = character;
					Calculations.LoadModel(Calculations.Models[character.CurrentModel]);
					Calculations.ClearCache();
					Calculations.CalculationOptionsPanel.Character = character;
					HeadButton.Character = character;
					NeckButton.Character = character;
					ShoulderButton.Character = character;
					BackButton.Character = character;
					ChestButton.Character = character;
					ShirtButton.Character = character;
					TabardButton.Character = character;
					WristButton.Character = character;
					HandButton.Character = character;
					BeltButton.Character = character;
					LegButton.Character = character;
					FeetButton.Character = character;
					Ring1Button.Character = character;
					Ring2Button.Character = character;
					Trinket1Button.Character = character;
					Trinket2Button.Character = character;
					MainHandButton.Character = character;
					OffHandButton.Character = character;
					RangedButton.Character = character;
					TalentPicker.Character = character;

					BuffControl.Character = character;

					BossPicker.Character = character;

					character.CalculationsInvalidated += new EventHandler(character_CalculationsInvalidated);
					character.ClassChanged += new EventHandler(character_ClassChanged);
					character.AvailableItemsChanged += new EventHandler(character_AvailableItemsChanged);

					character_ClassChanged(this, EventArgs.Empty);

					if (character.LoadItemFilterEnabledOverride())
					{
						ItemCache.OnItemsChanged();
					}

					Character.IsLoading = false;
					character_CalculationsInvalidated(this, EventArgs.Empty);

					// it's important that ComparisonGraph hooks CalculationsInvalidated event after we do because
					// the reference calculation must happen first
					// it also triggers update graph when we change character so make sure we've already done
					// the reference calculation
					ComparisonGraph.Character = character;
				}
			}
		}

		void character_AvailableItemsChanged(object sender, EventArgs e)
		{
			_unsavedChanges = true;
		}

		#region Batch Tools
		private Character _storedCharacter;
		private BatchCharacter _batchCharacter;
		public void BatchCharacterSaved(BatchCharacter character)
		{
			if (_batchCharacter == character)
			{
				//_unsavedChanges = false;
				//SetTitle();
			}
		}

		public void LoadBatchCharacter(BatchCharacter character)
		{
			if (character.Character != null)
			{
				if (_batchCharacter == null)
				{
					_storedCharacter = this.character;
					//_storedCharacterPath = _characterPath;
					//_storedUnsavedChanged = _unsavedChanges;
				}
				_batchCharacter = character;
				//_characterPath = character.AbsulutePath;
				EnsureItemsLoaded(character.Character.GetAllEquippedAndAvailableGearIds());
				//LoadCharacterIntoForm(character.Character, character.UnsavedChanges);
				Character = character.Character;
			}
		}

		public void UnloadBatchCharacter()
		{
			if (_batchCharacter != null)
			{
				_batchCharacter = null;
				//_characterPath = _storedCharacterPath;
				//LoadCharacterIntoForm(_storedCharacter, _storedUnsavedChanged);
				Character = _storedCharacter;
				_storedCharacter = null;
			}
		}
		#endregion

		private class AsyncCalculationResult
		{
			public CharacterCalculationsBase Calculations;
			public Dictionary<string, string> DisplayCalculationValues;
		}

		CharacterCalculationsBase referenceCalculation;
		SendOrPostCallback asyncCalculationCompleted;
		AsyncOperation asyncCalculation;

		private void AsyncCalculationStart(CharacterCalculationsBase calculations, AsyncOperation asyncCalculation)
		{
			Dictionary<string, string> result = calculations.GetAsynchronousCharacterDisplayCalculationValues();
			asyncCalculation.PostOperationCompleted(asyncCalculationCompleted, new AsyncCalculationResult() { Calculations = calculations, DisplayCalculationValues = result });
		}

		private void AsyncCalculationCompleted(object arg)
		{
			AsyncCalculationResult result = (AsyncCalculationResult)arg;
			if (result.DisplayCalculationValues != null && result.Calculations == referenceCalculation)
			{
				CalculationDisplay.SetCalculations(result.DisplayCalculationValues);
				// refresh chart
				ComparisonGraph.UpdateGraph();
				asyncCalculation = null;
			}
		}

		public void character_CalculationsInvalidated(object sender, EventArgs e)
		{
#if DEBUG
			DateTime start = DateTime.Now;
#endif
			this.Cursor = Cursors.Wait;
			if (asyncCalculation != null)
			{
				CharacterCalculationsBase oldCalcs = referenceCalculation;
				referenceCalculation = null;
				oldCalcs.CancelAsynchronousCharacterDisplayCalculation();
				asyncCalculation = null;
			}
			//_unsavedChanges = true;
			referenceCalculation = Calculations.GetCharacterCalculations(character, null, true, true, true);
			CalculationDisplay.SetCalculations(referenceCalculation.GetCharacterDisplayCalculationValues());
			UpdateDisplayCalculationValues(referenceCalculation.GetCharacterDisplayCalculationValues(), referenceCalculation);
			if (Character.PrimaryProfession == Profession.Blacksmithing || Character.SecondaryProfession == Profession.Blacksmithing)
			{
				//HandBSCheck.IsChecked = true;
				//WristBSCheck.IsChecked = true;
				HandBSCheck.IsEnabled = true;
				WristBSCheck.IsEnabled = true;
			}
			else
			{
				HandBSCheck.IsChecked = false;
				WristBSCheck.IsChecked = false;
				HandBSCheck.IsEnabled = false;
				WristBSCheck.IsEnabled = false;
			}
			if (referenceCalculation.RequiresAsynchronousDisplayCalculation)
			{
				asyncCalculation = AsyncOperationManager.CreateOperation(null);
				ThreadPool.QueueUserWorkItem(delegate
				{
					AsyncCalculationStart(referenceCalculation, asyncCalculation);
				});
			}
			this.Cursor = Cursors.Arrow;
#if DEBUG
			System.Diagnostics.Debug.WriteLine(string.Format("Finished MainPage CalculationsInvalidated: {0}ms", DateTime.Now.Subtract(start).TotalMilliseconds));
#endif
		}

		public void ProfChanged(object sender, SelectionChangedEventArgs e) {
			character_CalculationsInvalidated(null, null);
		}

		public void UpdateDisplayCalculationValues(Dictionary<string, string> displayCalculationValues, CharacterCalculationsBase _calculatedStats)
		{
			//calculationDisplay1.SetCalculations(displayCalculationValues);
			string status;
			if (!displayCalculationValues.TryGetValue("Status", out status))
			{
				int i = 0;
				status = "Overall: " + Math.Round(_calculatedStats.OverallPoints);
				foreach (KeyValuePair<string, Color> kvp in Calculations.SubPointNameColors)
				{
					status += ", " + kvp.Key + ": " + Math.Round(_calculatedStats.SubPoints[i]);
					i++;
				}
				//status = "Rawr version " + typeof(Calculations).Assembly.GetName().Version.ToString();
			}
			StatusText.Text = status;
		}

		public MainPage()
		{
			Instance = this;
			InitializeComponent();
			if (App.Current.IsRunningOutOfBrowser) OfflineInstallButton.Visibility = Visibility.Collapsed;

			// Assign the Version number to the status bar
			Assembly asm = Assembly.GetExecutingAssembly();
			string version = "Debug";
			if (asm.FullName != null) {
				string[] parts = asm.FullName.Split(',');
				version = parts[1];
				if (version.Contains("Version=")) { version = version.Replace("Version=",""); }
				if (version.Contains(" ")) { version = version.Replace(" ", ""); }
			}
			VersionText.Text = string.Format("Rawr b{0}", version);

			asyncCalculationCompleted = new SendOrPostCallback(AsyncCalculationCompleted);

			Tooltip = ItemTooltip;

			HeadButton.Slot = CharacterSlot.Head;
			NeckButton.Slot = CharacterSlot.Neck;
			ShoulderButton.Slot = CharacterSlot.Shoulders;
			BackButton.Slot = CharacterSlot.Back;
			ChestButton.Slot = CharacterSlot.Chest;
			ShirtButton.Slot = CharacterSlot.Shirt;
			TabardButton.Slot = CharacterSlot.Tabard;
			WristButton.Slot = CharacterSlot.Wrist;
			HandButton.Slot = CharacterSlot.Hands;
			BeltButton.Slot = CharacterSlot.Waist;
			LegButton.Slot = CharacterSlot.Legs;
			FeetButton.Slot = CharacterSlot.Feet;
			Ring1Button.Slot = CharacterSlot.Finger1;
			Ring2Button.Slot = CharacterSlot.Finger2;
			Trinket1Button.Slot = CharacterSlot.Trinket1;
			Trinket2Button.Slot = CharacterSlot.Trinket2;
			MainHandButton.Slot = CharacterSlot.MainHand;
			OffHandButton.Slot = CharacterSlot.OffHand;
			RangedButton.Slot = CharacterSlot.Ranged;

			ModelCombo.ItemsSource = Calculations.Models.Keys;
			Calculations.ModelChanged += new EventHandler(Calculations_ModelChanged);

			Character c = new Character();
			c.CurrentModel = ConfigModel;
			c.Class = Calculations.ModelClasses[c.CurrentModel];
			Character = c;

			Calculations.ModelChanging += new EventHandler(Calculations_ModelChanging);
			ItemCache.Instance.ItemsChanged += new EventHandler(ItemCacheInstance_ItemsChanged);

			StatusMessaging.Ready = true;
		}

		private string ConfigModel { get { return "Bear"; } }

		private void Calculations_ModelChanged(object sender, EventArgs e)
		{
			foreach (string item in ModelCombo.Items)
			{
				if (item == Character.CurrentModel)
				{
					ModelCombo.SelectedItem = item;
				}
			}
			if (CMP_ClassModel != null)
			{
				try
				{
					bool found = false;
					foreach (Rawr.UI.ClassModelPicker.ClassModelPickerItem i in CMP_ClassModel.Items)
					{
						foreach (Rawr.UI.ClassModelPicker.ClassModelPickerItem j in i.Items)
						{
							if (j.Header == Character.CurrentModel)
							{
								CMP_ClassModel.PrimaryItem = i;
								CMP_ClassModel.PrimaryItem.SelectedItem = j;
								CMP_ClassModel.TextBlockClassModelButtonPrimary.Text = CMP_ClassModel.PrimaryItem.Header;
								CMP_ClassModel.TextBlockClassModelButtonSecondary.Text = CMP_ClassModel.PrimaryItem.SelectedItem.Header;
								found = true;
								break;
							}
						}
						if (found) break;
					}
				}
				catch (Exception ex) {
					new ErrorWindow() { Message = string.Format("Message: {0}\r\nInner Exception: {1}\r\n\r\nStack Trace:\r\n{2}",
						ex.Message, ex.InnerException, ex.StackTrace) }.Show();
				}
			}
			UpdateRaceLimitations();
			OptionsView.Content = Calculations.CalculationOptionsPanel;
			if (!Character.IsLoading) Character = Character;
		}

		private void UpdateRaceLimitations()
		{
			foreach (ComboBoxItem i in RaceCombo.Items)
			{
				if (i.Content != null && i.Content.ToString() != ""
					&& GetClassAllowableRaces[Character.CurrentModel].Contains(i.Content.ToString())) {
					i.Visibility = Visibility.Visible;
				}else{
					i.Visibility = Visibility.Collapsed;
				}
			}
		}

		private void Calculations_ModelChanging(object sender, EventArgs e)
		{
			Character.SerializeCalculationOptions();
		}

		private void ModelCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (!Character.IsLoading)
			{
				Character.CurrentModel = ModelCombo.SelectedItem as string;
				Character.Class = Calculations.ModelClasses[Character.CurrentModel];
				Calculations.LoadModel(Calculations.GetModel(Character.CurrentModel));
			}
		}

		private void ItemCacheInstance_ItemsChanged(object sender, EventArgs e)
		{
			Character.InvalidateItemInstances();
			Character.OnCalculationsInvalidated();
			if (!Character.IsLoading)
			{
				ComparisonGraph.UpdateGraph();
			}
		}

		private void InstallOffline(object sender, System.Windows.RoutedEventArgs e)
		{
#if SILVERLIGHT
			if (Application.Current.InstallState == InstallState.NotInstalled)
			{
				Application.Current.Install();
			}
#endif
		}

		private void PerformanceTest(object sender, System.Windows.RoutedEventArgs e)
		{
			DateTime start = DateTime.Now;
			for (int i = 0; i < 20000; i++)
				Calculations.GetCharacterCalculations(Character);
			TimeSpan ts = DateTime.Now.Subtract(start);
			MessageBox.Show(ts.ToString());
		}

		private void EnsureItemsLoaded(string[] ids)
		{
			List<Item> items = new List<Item>();
			for (int i = 0; i < ids.Length; i++)
			{
				string id = ids[i];
				if (id != null)
				{
					if (id.IndexOf('.') < 0 && ItemCache.ContainsItemId(int.Parse(id))) continue;
					string[] s = id.Split('.');
					Item newItem = Item.LoadFromId(int.Parse(s[0]), false, false, false);
					if (s.Length >= 4)
					{
						Item gem;
						if (s[1] != "*" && s[1] != "0") gem = Item.LoadFromId(int.Parse(s[1]), false, false, false);
						if (s[2] != "*" && s[2] != "0") gem = Item.LoadFromId(int.Parse(s[2]), false, false, false);
						if (s[3] != "*" && s[3] != "0") gem = Item.LoadFromId(int.Parse(s[3]), false, false, false);
					}
					if (newItem != null)
					{
						items.Add(newItem);
					}
				}
			}
			ItemCache.OnItemsChanged();
		}

		private void ItemsAreLoaded(Character character)
		{
			Status.Close();
			Character = character;
		}

		public void LoadCharacterFromArmory(string characterName, CharacterRegion region, string realm)
		{
			ArmoryLoadDialog armoryLoad = new ArmoryLoadDialog();
			armoryLoad.Closed += new EventHandler(armoryLoad_Closed);
			armoryLoad.Show();
			armoryLoad.Load(characterName, region, realm);
		}

		private void armoryLoad_Closed(object sender, EventArgs e)
		{
			ArmoryLoadDialog ald = sender as ArmoryLoadDialog;
			if (((ArmoryLoadDialog)sender).DialogResult.GetValueOrDefault(false))
			{
				Character character = ald.Character;
				// The removes force it to put those items at the end.
				// So we can use that for recall later on what was last used
				if (Rawr.Properties.RecentSettings.Default.RecentChars.Contains(character.Name)) {
					Rawr.Properties.RecentSettings.Default.RecentChars.Remove(character.Name);
				}
				if (Rawr.Properties.RecentSettings.Default.RecentServers.Contains(character.Realm)) {
					Rawr.Properties.RecentSettings.Default.RecentServers.Remove(character.Realm);
				}
				Rawr.Properties.RecentSettings.Default.RecentChars.Add(character.Name);
				Rawr.Properties.RecentSettings.Default.RecentServers.Add(character.Realm);
				Rawr.Properties.RecentSettings.Default.RecentRegion = character.Region.ToString();

				this.Character = character;
			}
		}

		private void armory_ResultReady(Character newChar)
		{
			if (newChar != null)
			{
				Character = newChar;
			}
			Status = null;
		}

		private void charprofLoad_Closed(object sender, EventArgs e)
		{
			CharProfLoadDialog cpld = sender as CharProfLoadDialog;
			if (((CharProfLoadDialog)sender).DialogResult.GetValueOrDefault(false))
			{
				Character character = cpld.Character;

				// So we can use that for recall later on what was last used
				Rawr.Properties.RecentSettings.Default.RecentCharProfiler = cpld.TB_FilePath.Text;

				this.Character = character;
			}
		}

		#region Menus
#if SILVERLIGHT
		/*Obsoleted by implementing MenuButton control
		private void FileMenu_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			if (FileMenu != null)
			{
				int newIndex = FileMenu.SelectedIndex;
				if (newIndex > 0)
				{
					FileMenu.IsDropDownOpen = false;
					FileMenu.SelectedIndex = 0;
					if (newIndex == 1) NewCharacter(null, null);
					else if (newIndex == 2) OpenCharacter(null, null);
					else if (newIndex == 3) SaveCharacter(null, null);
					else if (newIndex == 4) OpenSavedUpgradeList(null, null);
					else if (newIndex == 6) LoadFromArmory(null, null);
					//else if (newIndex == 7) LoadFromCharacterProfiler(null, null);
					else new ErrorWindow() { Message = "Not yet implemented." }.Show();
				}
			}
		}

		private void ToolsMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ToolsMenu != null)
			{
				int newIndex = ToolsMenu.SelectedIndex;
				if (newIndex > 0)
				{
					ToolsMenu.IsDropDownOpen = false;
					ToolsMenu.SelectedIndex = 0;
					if (newIndex == 1) ShowItemEditor(null, null);
					else if (newIndex == 2) ShowGemmingTemplates(null, null);
					else if (newIndex == 3) ShowItemRefinement(null, null);
					else if (newIndex == 4) ShowItemFilters(null, null);
					else if (newIndex == 6) ResetItemCost(null, null);
					else if (newIndex == 7) LoadItemCost(null, null);
					else if (newIndex == 8) SaveItemCost(null, null);
					else if (newIndex == 9) LoadEmblemOfFrostCost(null, null);
					else if (newIndex == 11) ShowOptimizer(null, null);
					else if (newIndex == 12) ShowBatchTools(null, null);
					else new ErrorWindow() { Message = "Not yet implemented." }.Show();
				}
			}
		}

		private void ImportMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ImportMenu != null)
			{
				int newIndex = ImportMenu.SelectedIndex;
				if (newIndex > 0)
				{
					ImportMenu.IsDropDownOpen = false;
					ImportMenu.SelectedIndex = 0;
					new ErrorWindow() { Message = "Not yet implemented." }.Show();
				}
			}
		}

		private void OptionsMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (OptionsMenu != null)
			{
				int newIndex = OptionsMenu.SelectedIndex;
				if (newIndex > 0)
				{
					OptionsMenu.IsDropDownOpen = false;
					OptionsMenu.SelectedIndex = 0;
					if (newIndex == 1) ShowOptions(null, null);
					else if (newIndex == 3) ResetItemCache(null, null);
					else if (newIndex == 4) ResetAllCaches(null, null);
					else new ErrorWindow() { Message = "Not yet implemented." }.Show();
				}
			}

		}

		private void HelpMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (HelpMenu != null)
			{
				int newIndex = HelpMenu.SelectedIndex;
				if (newIndex > 0)
				{
					HelpMenu.IsDropDownOpen = false;
					HelpMenu.SelectedIndex = 0;
					//if (newIndex == 1) ShowHelp("http://rawr.codeplex.com/documentation");
					//else if (newIndex == 2) ShowHelp("http://www.youtube.com/watch?v=OjRM5SUoOoQ");
					//else if (newIndex == 3) ShowHelp("http://rawr.codeplex.com/wikipage?title=Gemmings");
					//else if (newIndex == 4) ShowHelp("http://rawr.codeplex.com/wikipage?title=GearOptimization");
					//else if (newIndex == 5) ShowHelp("http://rawr.codeplex.com/wikipage?title=ItemFiltering");
					//else if (newIndex == 7) ShowHelp("http://rawr.codeplex.com/");
					//else if (newIndex == 8) ShowHelp("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2451163");
					//else new ErrorWindow() { Message = "Not yet implemented." }.Show();
				}
			}
		}
		*/
#endif

		#region File Menu
		private void NewCharacter(object sender, RoutedEventArgs args)
		{
			if (_unsavedChanges) { NeedToSaveCharacter(); }
			Character c = new Character();
			c.CurrentModel = Character.CurrentModel;
			c.Class = Character.Class;
			c.Race = Character.Race;
			Character = c;
		}

		private void OpenCharacter(object sender, RoutedEventArgs args)
		{
			if (_unsavedChanges) { NeedToSaveCharacter(); }
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Filter = "character file (*.xml)|*.xml";
			if (ofd.ShowDialog().GetValueOrDefault(false))
			{
#if SILVERLIGHT
				using (StreamReader reader = ofd.File.OpenText())
#else
				using (StreamReader reader = new StreamReader(ofd.OpenFile()))
#endif
				{
					// TODO: we'll have to expand this considerably to get to Rawr2 functionality
					Character loadedCharacter = Character.LoadFromXml(reader.ReadToEnd());
					EnsureItemsLoaded(loadedCharacter.GetAllEquippedAndAvailableGearIds());
					Character = loadedCharacter;
				}
			}
		}

		public void NeedToSaveCharacter() {
			if (MessageBox.Show("There are unsaved changes to the current character, do you want to save them?\n\nWARNING: Selecting Cancel will lose the unsaved changes.",
				"Unsaved Changes Detected", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
			{
				SaveCharacter(null, null);
			}
		}
		private void SaveCharacter(object sender, RoutedEventArgs args)
		{
			SaveFileDialog sfd = new SaveFileDialog();
			sfd.Filter = "character file (*.xml)|*.xml";
			if (sfd.ShowDialog().GetValueOrDefault(false))
			{
				Character.Save(sfd.OpenFile());
				_unsavedChanges = false;
			}
		}

		private void OpenSavedUpgradeList(object sender, RoutedEventArgs args)
		{
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Filter = "Rawr Upgrade List Files|*.xml";
			if (ofd.ShowDialog().GetValueOrDefault())
			{
#if SILVERLIGHT
				new UpgradesComparison(ofd.File.OpenText()).Show();
#else
				new UpgradesComparison(new StreamReader(ofd.OpenFile())).Show();
#endif
			}
		}

		private void LoadFromArmory(object sender, RoutedEventArgs args)
		{
			if (_unsavedChanges) { NeedToSaveCharacter(); }
			ArmoryLoadDialog armoryLoad = new ArmoryLoadDialog();
			armoryLoad.Closed += new EventHandler(armoryLoad_Closed);
			armoryLoad.Show();
		}

		private void LoadFromCharacterProfiler(object sender, RoutedEventArgs args)
		{
			if (_unsavedChanges) { NeedToSaveCharacter(); }
			CharProfLoadDialog charprofLoad = new CharProfLoadDialog();
			charprofLoad.Closed += new EventHandler(charprofLoad_Closed);
			charprofLoad.Show();
		}
		#endregion

		#region Tools Menu
		private void ShowItemEditor(object sender, RoutedEventArgs args)
		{
			ItemSearch.Show();
		}

		private void ShowGemmingTemplates(object sender, RoutedEventArgs args)
		{
			new GemmingTemplates(Character).Show();
		}

		private void ShowItemRefinement(object sender, RoutedEventArgs args)
		{
			new RelevantItemRefinement().Show();
		}

		private void ShowItemFilters(object sender, RoutedEventArgs args)
		{
			new EditItemFilter().Show();
		}

		private void ResetItemCost(object sender, RoutedEventArgs args)
		{
			ItemCache.ResetItemCost();
		}

		private void LoadItemCost(object sender, RoutedEventArgs args)
		{
			OpenFileDialog dialog = new OpenFileDialog();
#if !SILVERLIGHT
			dialog.DefaultExt = ".cost.xml";
#endif
			dialog.Filter = "Rawr Xml Item Cost Files | *.cost.xml";
			dialog.Multiselect = false;
			if (dialog.ShowDialog().GetValueOrDefault(false))
			{
#if SILVERLIGHT
				using (StreamReader reader = dialog.File.OpenText())
#else
				using (StreamReader reader = new StreamReader(dialog.OpenFile()))
#endif
				{
					ItemCache.LoadItemCost(reader);
				}
			}
		}

		private void SaveItemCost(object sender, RoutedEventArgs args)
		{
			SaveFileDialog dialog = new SaveFileDialog();
			dialog.DefaultExt = ".cost.xml";
			dialog.Filter = "Rawr Xml Item Cost Files | *.cost.xml";
			if (dialog.ShowDialog().GetValueOrDefault(false))
			{
				this.Cursor = Cursors.Wait;
				using (StreamWriter writer = new StreamWriter(dialog.OpenFile()))
				{
					ItemCache.SaveItemCost(writer);
				}
				this.Cursor = Cursors.Arrow;
			}
		}

		private void LoadEmblemOfFrostCost(object sender, RoutedEventArgs args)
		{
			ItemCache.LoadTokenItemCost("Emblem of Frost");
		}

		private void ShowOptimizer(object sender, RoutedEventArgs args)
		{
			new OptimizeWindow(Character).Show();
		}

		private void ShowBatchTools(object sender, RoutedEventArgs args)
		{
#if SILVERLIGHT
			// in silverlight we want to reuse current batch tools
			if (BatchTools.Instance != null)
			{
				App.Current.ShowWindow(BatchTools.Instance);
			}
			else
			{
				App.Current.OpenNewWindow("Batch Tools", new BatchTools());
			}
#else
			App.Current.OpenNewWindow("Batch Tools", new BatchTools());
#endif
		}
		#endregion

		#region Import Menu
		#endregion

		#region Options Menu
		private void ShowOptions(object sender, RoutedEventArgs e)
		{
			new OptionsDialog().Show();
		}

		private void ResetAllCaches(object sender, RoutedEventArgs e)
		{
			ConfirmationWindow.ShowDialog("Are you sure you'd like to clear and redownload all caches?\r\n\r\nWARNING: This will also unload the current character, so be sure to save first!",
				new EventHandler(ResetAllCaches_Confirmation));
		}

		private void ResetAllCaches_Confirmation(object sender, EventArgs e)
		{
			if (((ConfirmationWindow)sender).DialogResult == true)
			{
				Character = new Character();
				new FileUtils(new string[] {
					"BuffCache.xml",
					"EnchantCache.xml",
					"ItemCache.xml",
					"Talents.xml",
					"PetTalents.xml",
					"BuffSets.xml",
					"ItemSource.xml",
					"ItemFilter.xml",
					"Settings.xml"}).Delete();
				LoadScreen ls = new LoadScreen();
				(App.Current.RootVisual as Grid).Children.Add(ls);
				this.Visibility = Visibility.Collapsed;
				ls.StartLoading(new EventHandler(ResetCaches_Finished));
				Character = new Character();
			}
		}

		private void ResetItemCache(object sender, RoutedEventArgs e)
		{
			ConfirmationWindow.ShowDialog("Are you sure you'd like to clear and redownload the item cache?\r\n\r\nWARNING: This will also unload the current character, so be sure to save first!",
				new EventHandler(ResetItemCaches_Confirmation));
		}

		private void ResetItemCaches_Confirmation(object sender, EventArgs e)
		{
			if (((ConfirmationWindow)sender).DialogResult == true)
			{
				Character = new Character();
				new FileUtils("ItemCache.xml").Delete();
				LoadScreen ls = new LoadScreen();
				(App.Current.RootVisual as Grid).Children.Add(ls);
				this.Visibility = Visibility.Collapsed;
				ls.StartLoading(new EventHandler(ResetCaches_Finished));
				Character = new Character();
			}
		}

		private void ResetCaches_Finished(object sender, EventArgs e)
		{
			(App.Current.RootVisual as Grid).Children.Remove(sender as LoadScreen);
			this.Visibility = Visibility.Visible;
		}
		#endregion

		#region Help Menu
		private void ShowHelp(string uri)
		{
#if SILVERLIGHT
			System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(uri, UriKind.Absolute), "_blank");
#else
			System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(uri));
#endif
		}

		private void ShowRawrHelpPage(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://rawr.codeplex.com/documentation");
		}

		private void ShowTourOfRawr(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://www.youtube.com/watch?v=OjRM5SUoOoQ");
		}

		private void ShowGemmingsHelp(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://rawr.codeplex.com/wikipage?title=Gemmings");
		}

		private void ShowGearOptimizationHelp(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://rawr.codeplex.com/wikipage?title=GearOptimization");
		}

		private void ShowItemFilteringHelp(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://rawr.codeplex.com/wikipage?title=ItemFiltering");
		}

		private void ShowRawrWebsite(object sender, RoutedEventArgs args)
		{
			ShowHelp("http://rawr.codeplex.com/");
		}

		private void ShowDonate(object sender, RoutedEventArgs args)
		{
			ShowHelp("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2451163");
		}
		#endregion
		#endregion

		private void character_ClassChanged(object sender, EventArgs e)
		{
			ClassCombo.SelectedIndex = Character.ClassIndex;
		}

		private void ClassCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			Character.ClassIndex = ClassCombo.SelectedIndex;
		}

		private static Dictionary<string, List<string>> classAllowableRaces = null;
		private static Dictionary<string, List<string>> GetClassAllowableRaces
		{
			get
			{
				if (classAllowableRaces == null)
				{
					classAllowableRaces = new Dictionary<string, List<string>>();
					classAllowableRaces.Add("DPSDK", new List<string>() { "Draenei", "Dwarf", "Gnome", "Human", "Night Elf", "Blood Elf", "Orc", "Tauren", "Troll", "Undead", });
					classAllowableRaces.Add("TankDK", new List<string>() { "Draenei", "Dwarf", "Gnome", "Human", "Night Elf", "Blood Elf", "Orc", "Tauren", "Troll", "Undead", });
					classAllowableRaces.Add("Bear", new List<string>() { /*"Draenei",*/ /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ "Night Elf", /*"Blood Elf",*/ /*"Orc",*/ "Tauren", /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("Cat", new List<string>() { /*"Draenei",*/ /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ "Night Elf", /*"Blood Elf",*/ /*"Orc",*/ "Tauren", /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("Moonkin", new List<string>() { /*"Draenei",*/ /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ "Night Elf", /*"Blood Elf",*/ /*"Orc",*/ "Tauren", /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("Tree", new List<string>() { /*"Draenei",*/ /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ "Night Elf", /*"Blood Elf",*/ /*"Orc",*/ "Tauren", /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("Hunter", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ /*"Human",*/ "Night Elf", "Blood Elf", "Orc", "Tauren", "Troll", /*"Undead",*/ });
					classAllowableRaces.Add("Mage", new List<string>() { "Draenei", /*"Dwarf",*/ "Gnome", "Human", /*"Night Elf",*/ "Blood Elf", /*"Orc",*/ /*"Tauren",*/ "Troll", "Undead", });
					classAllowableRaces.Add("Healadin", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ "Human", /*"Night Elf",*/ "Blood Elf", /*"Orc",*/ /*"Tauren",*/ /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("ProtPaladin", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ "Human", /*"Night Elf",*/ "Blood Elf", /*"Orc",*/ /*"Tauren",*/ /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("Retribution", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ "Human", /*"Night Elf",*/ "Blood Elf", /*"Orc",*/ /*"Tauren",*/ /*"Troll",*/ /*"Undead",*/ });
					classAllowableRaces.Add("HealPriest", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ "Human", "Night Elf", "Blood Elf", /*"Orc",*/ /*"Tauren",*/ "Troll", "Undead", });
					classAllowableRaces.Add("ShadowPriest", new List<string>() { "Draenei", "Dwarf", /*"Gnome",*/ "Human", "Night Elf", "Blood Elf", /*"Orc",*/ /*"Tauren",*/ "Troll", "Undead", });
					classAllowableRaces.Add("Rogue", new List<string>() { /*"Draenei",*/ "Dwarf", "Gnome", "Human", "Night Elf", "Blood Elf", "Orc", /*"Tauren",*/ "Troll", "Undead", });
					classAllowableRaces.Add("Enhance", new List<string>() { "Draenei", /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ /*"Night Elf",*/ /*"Blood Elf",*/ "Orc", "Tauren", "Troll", /*"Undead",*/ });
					classAllowableRaces.Add("Elemental", new List<string>() { "Draenei", /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ /*"Night Elf",*/ /*"Blood Elf",*/ "Orc", "Tauren", "Troll", /*"Undead",*/ });
					classAllowableRaces.Add("RestoSham", new List<string>() { "Draenei", /*"Dwarf",*/ /*"Gnome",*/ /*"Human",*/ /*"Night Elf",*/ /*"Blood Elf",*/ "Orc", "Tauren", "Troll", /*"Undead",*/ });
					classAllowableRaces.Add("Warlock", new List<string>() { /*"Draenei",*/ /*"Dwarf",*/ "Gnome", "Human", /*"Night Elf",*/ "Blood Elf", "Orc", /*"Tauren",*/ /*"Troll",*/ "Undead", });
					classAllowableRaces.Add("DPSWarr", new List<string>() { "Draenei", "Dwarf", "Gnome", "Human", "Night Elf", /*"Blood Elf",*/ "Orc", "Tauren", "Troll", "Undead", });
					classAllowableRaces.Add("ProtWarr", new List<string>() { "Draenei", "Dwarf", "Gnome", "Human", "Night Elf", /*"Blood Elf",*/ "Orc", "Tauren", "Troll", "Undead", });
				}
				return classAllowableRaces;
			}
			set { classAllowableRaces = value; }
		}
	}
}


text:
"use strict";

/**
 * Let's plugins implementing support for other compile-to-js add to the list
 * of "resolvable" file extensions. Gatsby supports `.js` and `.jsx` by default.
 * @returns {Array} array of extensions
 */
exports.resolvableExtensions = true;

/**
 * Tell plugins to add pages. This extension point is called only after the initial
 * sourcing and transformation of nodes plus creation of the GraphQL schema are
 * complete so you can query your data in order to create pages.
 *
 * See also [the documentation for the boundActionCreator `createPage`](/docs/bound-action-creators/#createPage).
 * @example
 * exports.createPages = ({ graphql, boundActionCreators }) => {
 *   const { createPage } = boundActionCreators
 *   return new Promise((resolve, reject) => {
 *     const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)
 *     // Query for markdown nodes to use in creating pages.
 *     resolve(
 *       graphql(
 *         `
 *       {
 *         allMarkdownRemark(limit: 1000) {
 *           edges {
 *             node {
 *               fields {
 *                 slug
 *               }
 *             }
 *           }
 *         }
 *       }
 *     `
 *       ).then(result => {
 *         if (result.errors) {
 *           reject(result.errors)
 *         }
 *
 *         // Create blog post pages.
 *         result.data.allMarkdownRemark.edges.forEach(edge => {
 *             createPage({
 *               path: `${edge.node.fields.slug}`, // required
 *               component: slash(blogPostTemplate),
 *               context: {
 *                 slug: edge.node.fields.slug,
 *               },
 *             })
 *         })
 *
 *         return
 *       })
 *     )
 *   })
 * }
 * @returns {Array} array of extensions
 */

exports.createPages = true;

/**
 * Like `createPages` but for plugins who want to manage creating and removing
 * pages themselves in response to changes in data *not* managed by Gatsby.
 * Plugins implementing `createPages` will get called regularly to recompute
 * page information as Gatsby's data changes but those implementing
 * `createPagesStatefully` will not.
 *
 * An example of a plugin that uses this extension point is the internal plugin
 * [component-page-creator](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby/src/internal-plugins/component-page-creator)
 * which monitors the `src/pages` directory for the adding and removal of JS
 * pages. As its source of truth, files in the pages directory, is not known by
 * Gatsby, it needs to keep its own state about its world to know when to
 * add and remove pages.
 */
exports.createPagesStatefully = true;

/**
 * Tell plugins to add layouts. This extension point is called only after the initial
 * sourcing and transformation of nodes plus creation of the GraphQL schema are
 * complete so you can query your data in order to create layouts.
 *
 * See also the documentation for [`createLayout`](/docs/bound-action-creators/#createLayout).
 * @example
 * exports.createLayouts = ({ graphql, boundActionCreators }) => {
 *  boundActionCreators.createLayout({
 *    component: path.resolve(`src/templates/custom-layout.js`),
 *    id: 'custom', // optional - if not provided the filename will be used as id
 *   })
 *  }
 */
exports.createLayouts = true;

/**
 * Extension point to tell plugins to source nodes.
 *
 * See also the documentation for [`createNode`](/docs/bound-action-creators/#createNode).
 * @example
 * exports.sourceNodes = ({ boundActionCreators }) => {
 *   const { createNode } = boundActionCreators
 *   // Create nodes here.
 * }
 */
exports.sourceNodes = true;

/**
 * Called when a new node is created. Plugins wishing to extend or
 * transform nodes created by other plugins should implement this API.
 *
 * See also the documentation for [`createNode`](/docs/bound-action-creators/#createNode)
 * and [`createNodeField`](/docs/bound-action-creators/#createNodeField)
 * @example
 * exports.onCreateNode = ({ node, boundActionCreators }) => {
 *   const { createNode, createNodeField } = boundActionCreators
 *   // Transform the new node here and create a new node or
 *   // create a new node field.
 * }
 */
exports.onCreateNode = true;

/**
 * Called when a new page is created. This extension API is useful
 * for programmatically manipulating pages created by other plugins e.g.
 * if you want paths without trailing slashes.
 *
 * See the guide [Creating and Modifying Pages](/docs/creating-and-modifying-pages/)
 * for more on this API.
 */
exports.onCreatePage = true;

/**
 * Called when a new layout is created. This extension API is useful
 * for programmatically manipulating layouts created by other plugins
 */
exports.onCreateLayout = true;

/**
 * Called during the creation of the GraphQL schema. Allows plugins
 * to add new fields to the types created from data nodes. Many transformer
 * plugins use this to add fields that take arguments.
 *
 * * [`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/)
 * adds an "excerpt" field where the user when writing their query can specify
 * how many characters to prune the markdown source to.
 * * [`gatsby-transformer-sharp`](/packages/gatsby-transformer-sharp/) exposes
 * many image transformation options as GraphQL fields.
 */
exports.setFieldsOnGraphQLNodeType = true;

/**
 * Ask compile-to-js plugins to process source to JavaScript so the query
 * runner can extract out GraphQL queries for running.
 */
exports.preprocessSource = true;

/**
 * Tell plugins with expensive "side effects" from queries to start running
 * those now. This is a soon-to-be-replaced API only currently in use by
 * `gatsby-plugin-sharp`.
 */
exports.generateSideEffects = true;

/**
 * Let plugins extend/mutate the site's Babel configuration.
 * This API will change before 2.0 as it needs still to be converted to use
 * Redux actions.
 */
exports.modifyBabelrc = true;

/**
 * Let plugins extend/mutate the site's webpack configuration.
 *
 * Refer to the [Add custom webpack config docs
 * page](/docs/add-custom-webpack-config/) for detailed documentation on
 * modifying webpack docs).
 */
exports.modifyWebpackConfig = true;

/**
 * Called at the start of the bootstrap process before any other extension APIs are called.
 */
exports.onPreBootstrap = true;

/**
 * Called at the end of the bootstrap process after all other extension APIs have been called.
 */
exports.onPostBootstrap = true;

/**
 * The first extension point called during the build process. Called after the bootstrap has completed but before the build steps start.
 */
exports.onPreBuild = true;

/**
 * The last extension point called after all other parts of the build process
 * are complete.
 */
exports.onPostBuild = true;

/**
 * Run before GraphQL queries/fragments are extracted from JavaScript files. Useful for plugins
 * to add more JavaScript files with queries/fragments e.g. from node_modules.
 *
 * See gatsby-transformer-remark and gatsby-source-contentful for examples.
 */
exports.onPreExtractQueries = true;
//# sourceMappingURL=api-node-docs.js.map

redpajama_set_name: RedPajamaGithub


text:
package com.skycaster.geomapper.bean;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * Created by 廖华凯 on 2017/6/27.
 */

public class Location implements Serializable{
    String title="null";
    int iconStyle;
    double latitude;
    double longitude;
    double altitude;
    String comments="null";
    Tag tag;
    ArrayList<String> picList;
    boolean isBaiduCoordinateSystem;
    String submitDate="null";

    public Location clone(){
        Location location=new Location();
        location.setTitle(this.title);
        location.setIconStyle(this.iconStyle);
        location.setLatitude(this.latitude);
        location.setLongitude(this.longitude);
        location.setAltitude(this.altitude);
        location.setComments(this.comments);
        location.setTag(this.tag);
        location.setPicList(this.picList);
        location.setBaiduCoordinateSystem(this.isBaiduCoordinateSystem);
        location.setSubmitDate(this.submitDate);
        return location;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getIconStyle() {
        return iconStyle;
    }

    public void setIconStyle(int iconStyle) {
        this.iconStyle = iconStyle;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public double getAltitude() {
        return altitude;
    }

    public void setAltitude(double altitude) {
        this.altitude = altitude;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public ArrayList<String> getPicList() {
        return picList;
    }

    public void setPicList(ArrayList<String> picList) {
        this.picList=picList;
    }

    public boolean isBaiduCoordinateSystem() {
        return isBaiduCoordinateSystem;
    }

    public void setBaiduCoordinateSystem(boolean baiduCoordinateSystem) {
        isBaiduCoordinateSystem = baiduCoordinateSystem;
    }

    public Tag getTag() {
        return tag;
    }

    public void setTag(Tag tag) {
        this.tag = tag;
    }

    public String getSubmitDate() {
        return submitDate;
    }

    public void setSubmitDate(String submitDate) {
        this.submitDate = submitDate;
    }

    @Override
    public String toString() {
        return "Location{" +
                "title='" + title + '\'' +
                ", iconStyle=" + iconStyle +
                ", latitude=" + latitude +
                ", longitude=" + longitude +
                ", altitude=" + altitude +
                ", comments='" + comments + '\'' +
                ", tag=" + tag +
                ", picList=" + picList +
                ", isBaiduCoordinateSystem=" + isBaiduCoordinateSystem +
                ", submitDate='" + submitDate + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Location location = (Location) o;

        if (Double.compare(location.latitude, latitude) != 0) return false;
        if (Double.compare(location.longitude, longitude) != 0) return false;
        return Double.compare(location.altitude, altitude) == 0;

    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        temp = Double.doubleToLongBits(latitude);
        result = (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(longitude);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(altitude);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var services_1 = require("./../../../services");
var models_1 = require("../../../models");
var ActivityEntryIndexComponent = (function () {
    function ActivityEntryIndexComponent(_router, _api, _activity, _auth, _logger, _error, _loading, _popup) {
        this._router = _router;
        this._api = _api;
        this._activity = _activity;
        this._auth = _auth;
        this._logger = _logger;
        this._error = _error;
        this._loading = _loading;
        this._popup = _popup;
        this.activitys = [];
        this._loading.setCurtain();
    }
    ActivityEntryIndexComponent.prototype.ngOnInit = function () {
        var _this = this;
        this._loading.setCurtain();
        this._api.getEntries().subscribe(function (data) {
            var body = data.json();
            _this._logger.debug("Data of get Entries");
            _this._logger.debug(data);
            body.data.forEach(function (entry) {
                var activityEntry = new models_1.ActivityEntry();
                activityEntry.assignParams(entry);
                _this.activitys.push(activityEntry);
            });
        }, function (err) {
            _this._error.errorInit(err);
            _this._popup.displayError(err, "Error!");
        }, function () {
            _this._loading.endLoading();
        });
    };
    ActivityEntryIndexComponent.prototype.showResult = function (entry_id) {
        this._loading.setCurtain();
        this._router.navigate(['entries', 'results', entry_id]);
    };
    ActivityEntryIndexComponent.prototype.startEntry = function (entry_id) {
        this._loading.setCurtain();
        localStorage.setItem('CurrentActivity', entry_id);
        this._router.navigate(['entry', 'training', {}]);
    };
    ActivityEntryIndexComponent.prototype.ngAfterViewInit = function () {
    };
    ActivityEntryIndexComponent = __decorate([
        core_1.Component({
            selector: 'courses-show',
            templateUrl: './activity_entry_index.component.html',
            styleUrls: ['./activity_entry_index.component.scss'],
            providers: [
                services_1.ApiService,
                services_1.AuthService,
                services_1.ActivityService,
                services_1.LoggerService,
                services_1.PopupService,
            ]
        })
    ], ActivityEntryIndexComponent);
    return ActivityEntryIndexComponent;
}());
exports.ActivityEntryIndexComponent = ActivityEntryIndexComponent;
//# sourceMappingURL=activity_entry_index.component.js.map


text:
<resources>
    <string name="app_name">ChatSE</string>

    <string name="app_version">V: %1$s</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_logout">Logout</string>
    <string name="title_activity_login">LoginActivity</string>
    <string name="chat_send_description">Send Message</string>
    <string name="chat_input_hint">Enter message</string>
    <string name="removed">(removed)</string>
    <string name="join_room">Join Room</string>
    <string name="title_activity_main">MainActivity</string>

    <string name="act_login_header">Login</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="take_photo">Take Photo</string>
    <string name="choose_from_gallery">Choose from Gallery</string>
    <string name="upload_from_url">Upload from URL</string>
    <string name="upload">Upload</string>
    <string name="stackoverflow">Stack Overflow</string>
    <string name="stackexchange">Stack Exchange</string>
    <string name="upload_image">Upload an Image</string>
    <string name="delete_message">Delete Message</string>
    <string name="star_message">Star Message</string>
    <string name="edit_message">Edit Message</string>
    <string name="room_info">Room Info</string>
    <string name="stars">Stars</string>
    <string name="default_profile_email">jonskeet@stackexchange.com</string>
    <string name="default_profile_name">Jon Skeet</string>

    <string name="about">About</string>
    <string name="about_version">%1$s - Version %2$s</string>
    <string name="about_app">This app was made with love by the Stack Exchange community <3</string>

    <string name="buy_coffee">Buy me a coffee</string>
    <string name="rate_app">Rate This this app!</string>
    <string name="about_app_header_play_store">Check ChatSE on Play Store</string>
    <string name="about_app_header_contact_us">Contact us</string>
    <string name="about_app_header_bug_report">Report a bug</string>
    <string name="about_app_header_changelog">Changelog</string>
    <string name="about_app_header_donate">Donate</string>
    <string name="our_developers">Our developers</string>
    <string name="share_app">Share App</string>
    <string name="avatar">Avatar</string>
    <string name="about_app_dev_github">Github</string>
    <string name="about_app_dev_website">Website</string>
    <string name="about_app_dev_so">Stack Overflow</string>
    <string name="about_app_dev_email">Email</string>
    <string name="about_app_dev_twitter">Twitter</string>
    <string name="beta_text">Thanks for using the alpha. Find bugs? Report them at https://github.com/room-15/ChatSE/</string>

    <!-- Content Description Strings -->
    <string name="content_desc_flag">Flag message to the moderators</string>
    <string name="content_desc_star">Stars the message as interesting</string>
    <string name="content_dec_reply">Reply to this message</string>

    <string name="content_desc_reply">Reply to this message</string>
    <string name="content_desc_edit">Edit this message</string>
</resources>


text:
@interface OFChangePasswordController : OFFormControllerHelper<OFProfileFrame>
{
@private
	UITextField* oldPasswordField;
	UITextField* passwordField;
	UITextField* passwordConfirmationField;

	NSString* oldPassword;
	NSString* password;
	NSString* passwordConfirmation;
}

@property (nonatomic, retain) IBOutlet UITextField* oldPasswordField;
@property (nonatomic, retain) IBOutlet UITextField* passwordField;
@property (nonatomic, retain) IBOutlet UITextField* passwordConfirmationField;

@end


text:
package org.apache.harmony.tests.java.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.ObjectOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

import org.apache.harmony.testframework.serialization.SerializationTest;

public class HashSetTest extends junit.framework.TestCase {

    HashSet hs;

    Object[] objArray;

    /**
     * java.util.HashSet#HashSet()
     */
    public void test_Constructor() {
        // Test for method java.util.HashSet()
        HashSet hs2 = new HashSet();
        assertEquals("Created incorrect HashSet", 0, hs2.size());
    }

    /**
     * java.util.HashSet#HashSet(int)
     */
    public void test_ConstructorI() {
        // Test for method java.util.HashSet(int)
        HashSet hs2 = new HashSet(5);
        assertEquals("Created incorrect HashSet", 0, hs2.size());
        try {
            new HashSet(-1);
        } catch (IllegalArgumentException e) {
            return;
        }
        fail(
                "Failed to throw IllegalArgumentException for capacity < 0");
    }

    /**
     * java.util.HashSet#HashSet(int, float)
     */
    public void test_ConstructorIF() {
        // Test for method java.util.HashSet(int, float)
        HashSet hs2 = new HashSet(5, (float) 0.5);
        assertEquals("Created incorrect HashSet", 0, hs2.size());
        try {
            new HashSet(0, 0);
        } catch (IllegalArgumentException e) {
            return;
        }
        fail(
                "Failed to throw IllegalArgumentException for initial load factor <= 0");
    }

    /**
     * java.util.HashSet#HashSet(java.util.Collection)
     */
    public void test_ConstructorLjava_util_Collection() {
        // Test for method java.util.HashSet(java.util.Collection)
        HashSet hs2 = new HashSet(Arrays.asList(objArray));
        for (int counter = 0; counter < objArray.length; counter++)
            assertTrue("HashSet does not contain correct elements", hs
                    .contains(objArray[counter]));
        assertTrue("HashSet created from collection incorrect size",
                hs2.size() == objArray.length);

        try {
            new HashSet(null);
            fail("NullPointerException expected");
        } catch (NullPointerException e) {
            //expected
        }
    }

    /**
     * java.util.HashSet#add(java.lang.Object)
     */
    public void test_addLjava_lang_Object() {
        // Test for method boolean java.util.HashSet.add(java.lang.Object)
        int size = hs.size();
        hs.add(new Integer(8));
        assertTrue("Added element already contained by set", hs.size() == size);
        hs.add(new Integer(-9));
        assertTrue("Failed to increment set size after add",
                hs.size() == size + 1);
        assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
    }

    /**
     * java.util.HashSet#clear()
     */
    public void test_clear() {
        // Test for method void java.util.HashSet.clear()
        Set orgSet = (Set) hs.clone();
        hs.clear();
        Iterator i = orgSet.iterator();
        assertEquals("Returned non-zero size after clear", 0, hs.size());
        while (i.hasNext())
            assertTrue("Failed to clear set", !hs.contains(i.next()));
    }

    /**
     * java.util.HashSet#clone()
     */
    public void test_clone() {
        // Test for method java.lang.Object java.util.HashSet.clone()
        HashSet hs2 = (HashSet) hs.clone();
        assertTrue("clone returned an equivalent HashSet", hs != hs2);
        assertTrue("clone did not return an equal HashSet", hs.equals(hs2));
    }

    /**
     * java.util.HashSet#contains(java.lang.Object)
     */
    public void test_containsLjava_lang_Object() {
        // Test for method boolean java.util.HashSet.contains(java.lang.Object)
        assertTrue("Returned false for valid object", hs.contains(objArray[90]));
        assertTrue("Returned true for invalid Object", !hs
                .contains(new Object()));

        HashSet s = new HashSet();
        s.add(null);
        assertTrue("Cannot handle null", s.contains(null));
    }

    /**
     * java.util.HashSet#isEmpty()
     */
    public void test_isEmpty() {
        // Test for method boolean java.util.HashSet.isEmpty()
        assertTrue("Empty set returned false", new HashSet().isEmpty());
        assertTrue("Non-empty set returned true", !hs.isEmpty());
    }

    /**
     * java.util.HashSet#iterator()
     */
    public void test_iterator() {
        // Test for method java.util.Iterator java.util.HashSet.iterator()
        Iterator i = hs.iterator();
        int x = 0;
        while (i.hasNext()) {
            assertTrue("Failed to iterate over all elements", hs.contains(i
                    .next()));
            ++x;
        }
        assertTrue("Returned iteration of incorrect size", hs.size() == x);

        HashSet s = new HashSet();
        s.add(null);
        assertNull("Cannot handle null", s.iterator().next());
    }

    /**
     * java.util.HashSet#remove(java.lang.Object)
     */
    public void test_removeLjava_lang_Object() {
        // Test for method boolean java.util.HashSet.remove(java.lang.Object)
        int size = hs.size();
        hs.remove(new Integer(98));
        assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
        assertTrue("Failed to decrement set size", hs.size() == size - 1);

        HashSet s = new HashSet();
        s.add(null);
        assertTrue("Cannot handle null", s.remove(null));
        assertFalse(hs.remove(new Integer(-98)));
    }

    /**
     * java.util.HashSet#size()
     */
    public void test_size() {
        // Test for method int java.util.HashSet.size()
        assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
        hs.clear();
        assertEquals("Cleared set returned non-zero size", 0, hs.size());
    }

    /**
     * java.util.HashSet#SerializationTest
     */
    public void test_Serialization() throws Exception{
        HashSet<String> hs = new HashSet<String>();
        hs.add("hello");
        hs.add("world");
        SerializationTest.verifySelf(hs, comparator);
        SerializationTest.verifyGolden(this, hs, comparator);
    }

    /**
     * Sets up the fixture, for example, open a network connection. This method
     * is called before a test is executed.
     */
    protected void setUp() {
        objArray = new Object[1000];
        for (int i = 0; i < objArray.length; i++) {
            objArray[i] = new Integer(i);
        }

        hs = new HashSet();
        for (int i = 0; i < objArray.length; i++) {
            hs.add(objArray[i]);
        }

        hs.add(null);
    }

    /**
     * Tears down the fixture, for example, close a network connection. This
     * method is called after a test is executed.
     */
    protected void tearDown() {
        hs = null;
        objArray = null;
    }

    private static final SerializationTest.SerializableAssert comparator = new
                                       SerializationTest.SerializableAssert() {
        public void assertDeserialized(Serializable initial, Serializable deserialized) {
            HashSet<String> initialHs = (HashSet<String>) initial;
            HashSet<String> deseriaHs = (HashSet<String>) deserialized;
            assertEquals("should be equal", initialHs.size(), deseriaHs.size());
            assertEquals("should be equal", initialHs, deseriaHs);
        }

    };
}


text:
<?php

namespace Cupon\OfertaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('OfertaBundle:Default:index.html.twig', array('name' => $name));
    }
    public function estaticaAction($pagina)
    {
        return $this->render('OfertaBundle:Sitio:'.$pagina.'.html.twig');
    }
    public function portadaAction($ciudad)
    {
        $em = $this->getDoctrine()->getManager();

        //$oferta = $em->getRepository('OfertaBundle:Oferta')->findOneBy(array(
        //    'ciudad' => $ciudad//,
        //    //'fecha_publicacion' => new \DateTime('today')
        //));
        $oferta = $em->getRepository('OfertaBundle:Oferta')->findOfertaDelDia($ciudad);

        if (!$oferta) {
            throw $this->createNotFoundException(
                'No se ha encontrado la oferta del día para '.$ciudad
            );
        }

        return $this->render('OfertaBundle:Default:portada.html.twig', array(
            'oferta' => $oferta
        ));
    }
    public function ofertaAction($ciudad, $slug)
    {
        $em = $this->getDoctrine()->getManager();
        $oferta = $em->getRepository('OfertaBundle:Oferta')
                     ->findOferta($ciudad, $slug);
        if (!$oferta) {
            throw $this->createNotFoundException('No existe la oferta');
        }
        $relacionadas = $em->getRepository('OfertaBundle:Oferta')
                           ->findRelacionadas($ciudad);

        return $this->render('OfertaBundle:Default:detalle.html.twig', array(
            'oferta'       => $oferta,
            'relacionadas' => $relacionadas
        ));
    }
}


text:
"""Support for AVM FRITZ!SmartHome devices."""
from __future__ import annotations

from datetime import timedelta

from pyfritzhome import Fritzhome, FritzhomeDevice, LoginError
import requests

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    ATTR_DEVICE_CLASS,
    ATTR_ENTITY_ID,
    ATTR_NAME,
    ATTR_UNIT_OF_MEASUREMENT,
    CONF_HOST,
    CONF_PASSWORD,
    CONF_USERNAME,
    EVENT_HOMEASSISTANT_STOP,
)
from homeassistant.core import Event, HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import (
    CoordinatorEntity,
    DataUpdateCoordinator,
)

from .const import CONF_CONNECTIONS, CONF_COORDINATOR, DOMAIN, LOGGER, PLATFORMS
from .model import EntityInfo

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the AVM FRITZ!SmartHome platforms."""
    fritz = Fritzhome(
        host=entry.data[CONF_HOST],
        user=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await hass.async_add_executor_job(fritz.login)
    except LoginError as err:
        raise ConfigEntryAuthFailed from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        CONF_CONNECTIONS: fritz,
    }

    def _update_fritz_devices() -> dict[str, FritzhomeDevice]:
        """Update all fritzbox device data."""
        try:
            devices = fritz.get_devices()
        except requests.exceptions.HTTPError:
            # If the device rebooted, login again
            try:
                fritz.login()
            except requests.exceptions.HTTPError as ex:
                raise ConfigEntryAuthFailed from ex
            devices = fritz.get_devices()

        data = {}
        for device in devices:
            device.update()
            data[device.ain] = device
        return data

    async def async_update_coordinator() -> dict[str, FritzhomeDevice]:
        """Fetch all device data."""
        return await hass.async_add_executor_job(_update_fritz_devices)

    hass.data[DOMAIN][entry.entry_id][
        CONF_COORDINATOR
    ] = coordinator = DataUpdateCoordinator(
        hass,
        LOGGER,
        name=f"{entry.entry_id}",
        update_method=async_update_coordinator,
        update_interval=timedelta(seconds=30),
    )

    await coordinator.async_config_entry_first_refresh()

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    def logout_fritzbox(event: Event) -> None:
        """Close connections to this fritzbox."""
        fritz.logout()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox)
    )

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unloading the AVM FRITZ!SmartHome platforms."""
    fritz = hass.data[DOMAIN][entry.entry_id][CONF_CONNECTIONS]
    await hass.async_add_executor_job(fritz.logout)

    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok

class FritzBoxEntity(CoordinatorEntity):
    """Basis FritzBox entity."""

    def __init__(
        self,
        entity_info: EntityInfo,
        coordinator: DataUpdateCoordinator[dict[str, FritzhomeDevice]],
        ain: str,
    ) -> None:
        """Initialize the FritzBox entity."""
        super().__init__(coordinator)

        self.ain = ain
        self._name = entity_info[ATTR_NAME]
        self._unique_id = entity_info[ATTR_ENTITY_ID]
        self._unit_of_measurement = entity_info[ATTR_UNIT_OF_MEASUREMENT]
        self._device_class = entity_info[ATTR_DEVICE_CLASS]

    @property
    def device(self) -> FritzhomeDevice:
        """Return device object from coordinator."""
        return self.coordinator.data[self.ain]

    @property
    def device_info(self) -> DeviceInfo:
        """Return device specific attributes."""
        return {
            "name": self.device.name,
            "identifiers": {(DOMAIN, self.ain)},
            "manufacturer": self.device.manufacturer,
            "model": self.device.productname,
            "sw_version": self.device.fw_version,
        }

    @property
    def unique_id(self) -> str:
        """Return the unique ID of the device."""
        return self._unique_id

    @property
    def name(self) -> str:
        """Return the name of the device."""
        return self._name

    @property
    def unit_of_measurement(self) -> str | None:
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @property
    def device_class(self) -> str | None:
        """Return the device class."""
        return self._device_class


text:
#ifndef __BZING_PARSER_H__
#define __BZING_PARSER_H__

#include "api/bzing_common.h"

static const unsigned int MAX_SIZE = 0x02000000;

uint64_t parse_var_int(const uint8_t *data, size_t *offset);

#endif


text:
layout: post
title: 'Times Digital Archive: 18th century editorials on Mrs. Inchbald'
categories:
- Serendipity
tags: []
status: draft
type: post
published: false
meta:
  _edit_last: '14'
---
The Times Digital Archive is exactly what it sounds like: an archive of the London Times from 1785 to 1985, unfortunately not including the Sunday edition.   It has wide coverage of the 18th, 19th, and 20th centuries, including the height of the British colonial period, with applicability for most research in history, literary, women's, and postcolonial studies.  It can also be used to find reviews of authors' works as published during their lifetime.  When searching, though, remember, that the further back you go in time, the more issues you might have with language and differences in both spelling and typography.


text:
package com.google.singletondetector;

/**
 * Simple class which stores flags for a SingletonDetector. Each boolean can be
 * set or read.
 *
 * @author David Rubel
 */
public class Flags {
  private boolean verbose = false;
  private boolean showStats = false;
  private boolean showBanner = false;
  private boolean ignoreSingletons = false;
  private boolean ignoreHingletons = false;
  private boolean ignoreMingletons = false;
  private boolean ignoreFingletons = false;
  private boolean ignoreOthers = false;
  private int threshold = -1;

  public boolean isVerbose() {
    return verbose;
  }

  public void setVerbose(boolean verbose) {
    this.verbose = verbose;
  }

  public boolean showStats() {
    return showStats;
  }

  public void setShowStats(boolean showStats) {
    this.showStats = showStats;
  }

  public boolean showBanner() {
    return showBanner;
  }

  public void setShowBanner(boolean showBanner) {
    this.showBanner = showBanner;
  }

  public boolean ignoreSingletons() {
    return ignoreSingletons;
  }

  public void setIgnoreSingletons(boolean ignoreSingletons) {
    this.ignoreSingletons = ignoreSingletons;
  }

  public boolean ignoreHingletons() {
    return ignoreHingletons;
  }

  public void setIgnoreHingletons(boolean ignoreHingletons) {
    this.ignoreHingletons = ignoreHingletons;
  }

  public boolean ignoreMingletons() {
    return ignoreMingletons;
  }

  public void setIgnoreMingletons(boolean ignoreMingletons) {
    this.ignoreMingletons = ignoreMingletons;
  }

  public boolean ignoreFingletons() {
    return ignoreFingletons;
  }

  public void setIgnoreFingletons(boolean ignoreFingletons) {
    this.ignoreFingletons = ignoreFingletons;
  }

  public boolean ignoreOthers() {
    return ignoreOthers;
  }

  public void setIgnoreOthers(boolean ignoreOthers) {
    this.ignoreOthers = ignoreOthers;
  }

  public int getThreshold() {
    return threshold;
  }

  public void setThreshold(int threshold) {
    this.threshold = threshold;
  }
}


text:
package main

import (
	"errors"
	"math"
	"regexp"
	"time"
)

var (
	unitRegexp   = regexp.MustCompile("%[SMHdmy]")
	unitScoreMap = map[string]int{
		"S": 1,
		"M": 60,
		"H": 60 * 60,
		"d": 60 * 60 * 24,
		"m": 60 * 60 * 24 * 30,
		"y": 60 * 60 * 24 * 365,
	}
)

//
// Detect which series to use
//
func DetectSeries(format string, t0 time.Time) Series {
	if unitRegexp.MatchString(format) {
		return NewPeriodSeriesWithGuess(format, t0)
	}
	return NewConstSeries(format)
}

/*
 * Series is a infinite time.Time list that generated from strftime's pattern sucn as:
 * "hoge-%S" => ["hoge-13", "hoge-14", "hoge-15", ...]
 * "%y-%m-%d" => ["2016-2-1", "2016-2-2", ...]
 * Iteration starts at `t0`.
 */
type Series interface {
	Current() time.Time
	Next() Series
	Sub(t time.Time) time.Duration
}

type PeriodSeries struct {
	time   time.Time
	format string
	period time.Duration
}

func NewPeriodSeriesWithGuess(format string, t0 time.Time) Series {
	period, err := guessPeriod(format)
	if err != nil {
		panic("todo impl") //TODO
	}
	return PeriodSeries{t0, format, period}
}

func (s PeriodSeries) Current() time.Time {
	return s.time
}

func (s PeriodSeries) Next() Series {
	return PeriodSeries{
		time:   s.time.Add(s.period),
		format: s.format,
		period: s.period,
	}
}

func (s PeriodSeries) Sub(t time.Time) time.Duration {
	return s.Current().Sub(t)
}

type ConstSeries struct {
	format string
}

func NewConstSeries(format string) Series {
	return ConstSeries{format}
}

func (s ConstSeries) Next() Series {
	return NewConstSeries(s.format)
}

func (s ConstSeries) Current() time.Time {
	return time.Now()
}

func (s ConstSeries) Sub(t time.Time) time.Duration {
	return time.Duration(math.MaxInt64)
}

/*
 * Guess period in second from the argument.
 * In general, the most smallest pattern letter is used.
 */
func guessPeriod(format string) (time.Duration, error) {
	re := unitRegexp
	units := re.FindAllString(format, -1)
	score := unitScoreMap
	// find minimum unit
	minScore := math.MaxInt32
	for _, u := range units {
		// u[1:] is truncation '%'
		value, ok := score[u[1:]]
		if ok && value < minScore {
			minScore = value
		}
	}
	if minScore == math.MaxInt32 {
		return time.Duration(0), errors.New("guessPeriod: fail to period detection from '" + format + "'")
	}
	// convert sec to nanosec
	return time.Duration(minScore * 1000 * 1000 * 1000), nil
}


text:
package com.nikhaldimann.viewselector.android;

import junit.framework.Test;
import junit.framework.TestSuite;
import android.test.suitebuilder.TestSuiteBuilder;

public class AllTests extends TestSuite {
    public static Test suite() {
        return new TestSuiteBuilder(AllTests.class)
                .includeAllPackagesUnderHere()
                .build();
    }
}


text:
package org.jboss.narayana.rest.integration.test.integration;

import org.codehaus.jettison.json.JSONArray;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.jbossts.star.provider.HttpResponseException;
import org.jboss.jbossts.star.util.media.txstatusext.TransactionStatusElement;
import org.jboss.narayana.rest.integration.api.Prepared;
import org.jboss.narayana.rest.integration.api.Vote;
import org.jboss.narayana.rest.integration.test.common.LoggingParticipant;
import org.jboss.narayana.rest.integration.test.common.RestATManagementResource;
import org.jboss.narayana.rest.integration.test.common.TransactionalService;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.io.File;

/**
 * @author Gytis Trikleris
 */
@RunWith(Arquillian.class)
public final class RecoveryIntegrationTestCase extends AbstractIntegrationTestCase {

    private static final String DEPENDENCIES = "Dependencies: org.jboss.narayana.rts,org.jboss.jts,org.codehaus.jettison\n";

    private static final int RECOVERY_PERIOD = 4;

    private static final int RECOVERY_WAIT_CYCLES = 8;

    private static final String VM_ARGUMENTS = System.getProperty("server.jvm.args").trim()
            + " -Dcom.arjuna.ats.arjuna.recovery.periodicRecoveryPeriod=" + RECOVERY_PERIOD;

    private static final String BYTEMAN_ARGUMENTS = "-Dorg.jboss.byteman.verbose -Djboss.modules.system.pkgs=org.jboss.byteman -Dorg.jboss.byteman.transform.all -javaagent:lib/byteman.jar=script:scripts/@BMScript@.btm,boot:lib/byteman.jar,listener:true";

    @Deployment(name = DEPLOYMENT_NAME, managed = false, testable = false)
    public static WebArchive getDeployment() {
        return ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME + ".war")
                .addPackages(false, LoggingParticipant.class.getPackage()).addAsWebInfResource(new File("web.xml"), "web.xml")
                .addAsManifestResource(new StringAsset(DEPENDENCIES), "MANIFEST.MF");
    }

    @After
    public void after() {
        super.after();
        stopContainer();
    }

    @Test
    public void testCrashAfterPrepare() throws Exception {
        startContainer(VM_ARGUMENTS + " " + BYTEMAN_ARGUMENTS.replace("@BMScript@", "CrashAfterPrepare"));

        txSupport.startTx();

        enlistParticipant(txSupport.getDurableParticipantEnlistmentURI(), new Prepared());
        enlistParticipant(txSupport.getDurableParticipantEnlistmentURI(), new Prepared());

        Assert.assertEquals(2, txSupport.getTransactionInfo().getTwoPhaseAware().size());

        try {
            // JVM is killed here.
            txSupport.commitTx();
        } catch (HttpResponseException e) {
        }

        restartContainer(VM_ARGUMENTS);
        registerDeserializer();

        TransactionStatusElement status;
        int cycles = 0;
        JSONArray partricipantsInformation;

        do {
            Thread.sleep(RECOVERY_PERIOD * 2000);
            partricipantsInformation = getParticipantsInformation();
        } while (cycles++ < RECOVERY_WAIT_CYCLES && partricipantsInformation.length() > 0);

        if (partricipantsInformation.length() > 0) {
            Assert.fail("Recovery failed");
        }
    }

    @Test
    public void testCrashBeforeCommit() throws Exception {
        startContainer(VM_ARGUMENTS + " " + BYTEMAN_ARGUMENTS.replace("@BMScript@", "CrashBeforeCommit"));

        txSupport.startTx();

        enlistParticipant(txSupport.getDurableParticipantEnlistmentURI(), new Prepared());
        enlistParticipant(txSupport.getDurableParticipantEnlistmentURI(), new Prepared());

        Assert.assertEquals(2, txSupport.getTransactionInfo().getTwoPhaseAware().size());

        try {
            // JVM is killed here.
            txSupport.commitTx();
        } catch (HttpResponseException e) {
        }

        restartContainer(VM_ARGUMENTS);
        registerDeserializer();

        TransactionStatusElement status;
        int cycles = 0;

        do {
            Thread.sleep(RECOVERY_PERIOD * 2000);
            status = null;
            try {
                // Updates coordinator's active transactions list
                txSupport.getTransactions();
                // After successful recovery transaction is removed and 404 is returned.
                status = txSupport.getTransactionInfo().getStatus();
            } catch (HttpResponseException e) {
            }
        } while (status != null && cycles++ < RECOVERY_WAIT_CYCLES);

        if (status != null) {
            Assert.fail("Recovery failed unexpected status " + status);
        }
    }

    private void enlistParticipant(final String enlistmentUrl, final Vote vote) throws Exception {
        Response clientResponse = ClientBuilder.newClient().target(DEPLOYMENT_URL + "/" + TransactionalService.PATH_SEGMENT)
                .queryParam("participantEnlistmentUrl", enlistmentUrl).queryParam("vote", vote.getClass().getName()).request()
                .post(null);

        Assert.assertEquals(200, clientResponse.getStatus());
    }

    private void registerDeserializer() throws Exception {
        Response clientResponse = ClientBuilder.newClient().target(DEPLOYMENT_URL + "/" + TransactionalService.PATH_SEGMENT)
                .request().put(null);

        Assert.assertEquals(204, clientResponse.getStatus());
    }

    private JSONArray getParticipantsInformation() {
        try {
            final Response response = ClientBuilder.newClient().target(DEPLOYMENT_URL + "/"
                    + RestATManagementResource.BASE_URL_SEGMENT + "/"
                    + RestATManagementResource.PARTICIPANTS_URL_SEGMENT).request().get();
            return new JSONArray(response.readEntity(String.class));
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONArray();
        }
    }

}


text:
'use strict';

var grunt = require('grunt');
var crypto = require('crypto');

var path = 'test/out';

exports.favicons = {

    // html test hashsum with two-space indentation
    htmlsum: function(test) {
        test.expect(1);
        var original = crypto.createHash('sha1').update(grunt.file.read(path + '/test.html.indent')).digest('hex');
        test.ok(original === 'cb5cb4fa1bd93ca4eaf73a4248719c2bd5b8b541', 'html hashsum (' + original + ') not valid');
        test.done();
    }

};


text:
//
// Copyright 2004-present Facebook. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#import <Foundation/Foundation.h>

#import "SimulatorInfo.h"

#import "DTiPhoneSimulatorRemoteClient.h"
#import "SimDevice.h"
#import "SimDeviceSet.h"
#import "SimDeviceType.h"
#import "SimRuntime.h"
#import "XcodeBuildSettings.h"
#import "XCToolUtil.h"

static const NSInteger KProductTypeIphone = 1;
static const NSInteger KProductTypeIpad = 2;

@interface DTiPhoneSimulatorSystemRoot (PlatformName)
- (NSString *)platformName;
@end

@implementation DTiPhoneSimulatorSystemRoot (PlatformName)
- (NSString *)platformName
{
  return [[[[[self runtime] platformPath] lastPathComponent] stringByDeletingPathExtension] lowercaseString];
}
@end

@interface SimulatorInfo ()
@property (nonatomic, assign) cpu_type_t cpuType;
@property (nonatomic, copy) NSString *deviceName;
@property (nonatomic, copy) NSString *OSVersion;
@property (nonatomic, copy) NSUUID *deviceUDID;

@property (nonatomic, strong) SimDevice *simulatedDevice;
@property (nonatomic, strong) SimRuntime *simulatedRuntime;

@property (nonatomic, copy) NSString *testHostPath;
@property (nonatomic, copy) NSString *productBundlePath;
@property (nonatomic, assign) cpu_type_t testHostPathCpuType;
@property (nonatomic, assign) cpu_type_t productBundlePathCpuType;
@property (nonatomic, assign) cpu_type_t simulatedCpuType;
@end

@implementation SimulatorInfo

+ (void)prepare
{
  NSAssert([NSThread isMainThread], @"Should be called on main thread");
  [self _warmUpDTiPhoneSimulatorSystemRootCaches];
}

- (instancetype)init
{
  self = [super init];
  if (self) {
    _cpuType = CPU_TYPE_ANY;
    _testHostPathCpuType = 0;
    _productBundlePathCpuType = 0;
    _simulatedCpuType = 0;
  }
  return self;
}

- (instancetype)copyWithZone:(NSZone *)zone
{
  SimulatorInfo *copy = [[SimulatorInfo allocWithZone:zone] init];
  if (copy) {
    copy.buildSettings = _buildSettings;
    copy.cpuType = _cpuType;
    copy.deviceName = _deviceName;
    copy.OSVersion = _OSVersion;
    copy.deviceUDID = _deviceUDID;
  }
  return copy;
}

#pragma mark - Internal Methods

- (void)setBuildSettings:(NSDictionary *)buildSettings
{
  if (_buildSettings == buildSettings || [_buildSettings isEqual:buildSettings]) {
    return;
  }

  _buildSettings = [buildSettings copy];
  _testHostPath = nil;
  _productBundlePath = nil;
  _testHostPathCpuType = 0;
  _productBundlePathCpuType = 0;
  _simulatedCpuType = 0;
}

- (NSString *)testHostPath
{
  if (!_testHostPath) {
    _testHostPath = TestHostPathForBuildSettings(_buildSettings);
  }
  return _testHostPath;
}

- (NSString *)productBundlePath
{
  if (!_productBundlePath) {
    _productBundlePath = ProductBundlePathForBuildSettings(_buildSettings);
  }
  return _productBundlePath;
}

- (cpu_type_t)testHostPathCpuType
{
  if (_testHostPathCpuType == 0) {
    _testHostPathCpuType = CpuTypeForTestBundleAtPath([self testHostPath]);
  }
  return _testHostPathCpuType;
}

- (cpu_type_t)productBundlePathCpuType
{
  if (_productBundlePathCpuType == 0) {
    _productBundlePathCpuType = CpuTypeForTestBundleAtPath([self productBundlePath]);
  }
  return _productBundlePathCpuType;
}

#pragma mark -
#pragma mark Public methods

- (cpu_type_t)simulatedCpuType
{
  if (_cpuType != CPU_TYPE_ANY) {
    return _cpuType;
  }

  if (_simulatedCpuType == 0) {
    /*
     * We use architecture of test host rather than product bundle one
     * if they don't match and test host doesn't support all architectures.
     */
    if ([self testHostPathCpuType] == CPU_TYPE_ANY) {
      _simulatedCpuType = [self productBundlePathCpuType];
    } else {
      _simulatedCpuType = [self testHostPathCpuType];
    }
  }

  return _simulatedCpuType;
}

- (NSNumber *)simulatedDeviceFamily
{
  return @([_buildSettings[Xcode_TARGETED_DEVICE_FAMILY] integerValue]);
}

- (NSString *)simulatedDeviceInfoName
{
  if (_deviceName) {
    return _deviceName;
  }

  if ([_buildSettings[Xcode_SDK_NAME] hasPrefix:@"macosx"]) {
    return @"My Mac";
  }

  switch ([[self simulatedDeviceFamily] integerValue]) {
    case KProductTypeIphone:
      if ([self simulatedCpuType] == CPU_TYPE_I386) {
        _deviceName = @"iPhone 4s";
      } else {
        // CPU_TYPE_X86_64 or CPU_TYPE_ANY
        _deviceName = @"iPhone 5s";
      }
      break;

    case KProductTypeIpad:
      if ([self simulatedCpuType] == CPU_TYPE_I386) {
        _deviceName = @"iPad 2";
      } else {
        // CPU_TYPE_X86_64 or CPU_TYPE_ANY
        _deviceName = @"iPad Air";
      }
      break;
  }

  DTiPhoneSimulatorSystemRoot *systemRoot = [SimulatorInfo _systemRootWithSDKPath:_buildSettings[Xcode_SDKROOT]];
  if (!systemRoot) {
    return _deviceName;
  }

  // return lowest device that has configuration with simulated sdk where lowest is defined
  // by the order in the returned array of devices from `-[SimDeviceSet availableDevices]`
  SimRuntime *runtime = systemRoot.runtime;
  NSMutableArray *supportedDeviceTypes = [NSMutableArray array];
  for (SimDevice *device in [[SimDeviceSet defaultSet] availableDevices]) {
    if (![device.runtime isEqual:runtime]) {
      continue;
    }

    if ([self simulatedCpuType] == CPU_TYPE_ANY ||
        [[[device deviceType] supportedArchs] containsObject:@([self simulatedCpuType])]) {
      [supportedDeviceTypes addObject:device.deviceType];
      // we need only first one
      break;
    }
  }

  NSAssert([supportedDeviceTypes count] > 0, @"There are no available devices that support provided sdk: %@. Supported devices: %@", [systemRoot sdkVersion], [[SimDeviceType supportedDevices] valueForKeyPath:@"name"]);
  _deviceName = [supportedDeviceTypes[0] name];
  return _deviceName;
}

- (NSString *)simulatedArchitecture
{
  switch ([self simulatedCpuType]) {
    case CPU_TYPE_I386:
      return @"i386";

    case CPU_TYPE_X86_64:
      return @"x86_64";
  }
  return @"i386";
}

- (NSString *)maxSdkVersionForSimulatedDevice
{
  NSMutableArray *runtimes = [SimulatorInfo _runtimesSupportedByDevice:[self simulatedDeviceInfoName]];
  [runtimes sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"version" ascending:YES]]];
  return [[runtimes lastObject] versionString];
}

- (NSString *)simulatedSdkVersion
{
  if (_OSVersion && ![_OSVersion isEqualToString:@"latest"]) {
    return _OSVersion;
  }
  return [self maxSdkVersionForSimulatedDevice];
}

- (NSString *)simulatedSdkRootPath
{
  return [[self systemRootForSimulatedSdk] sdkRootPath];
}

- (NSString *)simulatedSdkShortVersion
{
  return [[[self systemRootForSimulatedSdk] runtime] versionString];
}

- (NSString *)simulatedSdkName
{
  if ([_buildSettings[Xcode_SDK_NAME] hasPrefix:@"macosx"]) {
    return _buildSettings[Xcode_SDK_NAME];
  }

  DTiPhoneSimulatorSystemRoot *systemRoot = [self systemRootForSimulatedSdk];
  NSString *platformName = [systemRoot platformName];
  return [platformName stringByAppendingString:[self simulatedSdkVersion]];
}

- (DTiPhoneSimulatorSystemRoot *)systemRootForSimulatedSdk
{
  NSString *platform = _buildSettings[Xcode_PLATFORM_NAME];
  if (!platform) {
    platform = [[[_buildSettings[Xcode_PLATFORM_DIR] lastPathComponent] stringByDeletingPathExtension] lowercaseString];
  }
  NSAssert([platform isEqualToString:@"iphonesimulator"] || [platform isEqualToString:@"macosx"] || [platform isEqualToString:@"appletvsimulator"], @"Platform '%@' is not yet supported.", platform);
  NSString *sdkVersion = [self simulatedSdkVersion];
  DTiPhoneSimulatorSystemRoot *systemRoot = [SimulatorInfo _systemRootForPlatform:platform sdkVersion:sdkVersion];
  NSAssert(systemRoot != nil, @"Unable to instantiate DTiPhoneSimulatorSystemRoot for platform %@ and sdk version %@. Available roots: %@", platform, sdkVersion, [DTiPhoneSimulatorSystemRoot knownRoots]);
  return systemRoot;
}

- (SimRuntime *)simulatedRuntime
{
  if (!_simulatedRuntime) {
    _simulatedRuntime = [[self systemRootForSimulatedSdk] runtime];
    NSAssert(_simulatedRuntime != nil, @"Unable to find simulated runtime for simulated sdk of version %@ at path %@. Supported runtimes: %@", [[self systemRootForSimulatedSdk] sdkVersion], [[self systemRootForSimulatedSdk] sdkRootPath], [SimRuntime supportedRuntimes]);
  }
  return _simulatedRuntime;
}

- (SimDevice *)simulatedDevice
{
  if (!_simulatedDevice) {
    SimRuntime *runtime = [self simulatedRuntime];
    if (_deviceUDID) {
      return [SimulatorInfo deviceWithUDID:_deviceUDID];
    } else {
      SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][[self simulatedDeviceInfoName]];
      NSAssert(deviceType != nil, @"Unable to find SimDeviceType for the device with name \"%@\". Available device names: %@", [self simulatedDeviceInfoName], [[SimDeviceType supportedDeviceTypesByAlias] allKeys]);
      for (SimDevice *device in [[SimDeviceSet defaultSet] availableDevices]) {
        if ([device.deviceType isEqual:deviceType] &&
            [device.runtime isEqual:runtime]) {
          _simulatedDevice = device;
          break;
        }
      }
    }

    NSAssert(_simulatedDevice != nil, @"Simulator with name \"%@\" doesn't have configuration with sdk version \"%@\". Available configurations: %@.", [self simulatedDeviceInfoName], runtime.versionString, [SimulatorInfo _availableDeviceConfigurationsInHumanReadableFormat]);
  }
  return _simulatedDevice;
}

- (NSNumber *)launchTimeout
{
  NSString *launchTimeoutString = _buildSettings[Xcode_LAUNCH_TIMEOUT];
  if (launchTimeoutString) {
    return @(launchTimeoutString.intValue);
  }
  return @30;
}

/*
 * Passing the same simulator environment as Xcode 6.4.
 */
- (NSMutableDictionary *)simulatorLaunchEnvironment
{
  NSString *sdkName = _buildSettings[Xcode_SDK_NAME];
  NSString *ideBundleInjectionLibPath = [_buildSettings[Xcode_PLATFORM_DIR] stringByAppendingPathComponent:@"Developer/Library/PrivateFrameworks/IDEBundleInjection.framework/IDEBundleInjection"];
  NSMutableDictionary *environment = nil;
  NSMutableArray *librariesToInsert = [NSMutableArray array];
  if ([sdkName hasPrefix:@"macosx"]) {
    environment = OSXTestEnvironment(_buildSettings);
    [librariesToInsert addObject:[XCToolLibPath() stringByAppendingPathComponent:@"otest-shim-osx.dylib"]];
  } else if ([sdkName hasPrefix:@"iphonesimulator"]) {
    environment = IOSTestEnvironment(_buildSettings);
    [librariesToInsert addObject:[XCToolLibPath() stringByAppendingPathComponent:@"otest-shim-ios.dylib"]];
  } else if ([sdkName hasPrefix:@"appletvsimulator"]) {
    environment = TVOSTestEnvironment(_buildSettings);
    [librariesToInsert addObject:[XCToolLibPath() stringByAppendingPathComponent:@"otest-shim-ios.dylib"]];
  } else {
    NSAssert(false, @"'%@' sdk is not yet supported", sdkName);
  }
  [librariesToInsert addObject:ideBundleInjectionLibPath];

  [environment addEntriesFromDictionary:@{
    @"DYLD_INSERT_LIBRARIES" : [librariesToInsert componentsJoinedByString:@":"],
    @"NSUnbufferedIO" : @"YES",
    @"XCInjectBundle" : [self productBundlePath],
    @"XCInjectBundleInto" : [self testHostPath],
    @"AppTargetLocation": [self testHostPath],
    @"TestBundleLocation": [self productBundlePath],
  }];

  return environment;
}

#pragma mark -
#pragma mark Class Methods

+ (NSArray *)availableDevices
{
  return [[SimDeviceType supportedDeviceTypes] valueForKeyPath:@"name"];
}

+ (BOOL)isDeviceAvailableWithAlias:(NSString *)deviceName
{
  return [SimDeviceType supportedDeviceTypesByAlias][deviceName] != nil;
}

+ (SimDevice *)deviceWithUDID:(NSUUID *)deviceUDID
{
  for (SimDevice *device in [[SimDeviceSet defaultSet] availableDevices]) {
    if ([device.UDID isEqual:deviceUDID]) {
      return device;
    }
  }
  return nil;
}

+ (NSString *)deviceNameForAlias:(NSString *)deviceAlias
{
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceAlias];
  return [deviceType name];
}

+ (BOOL)isSdkVersion:(NSString *)sdkVersion supportedByDevice:(NSString *)deviceName
{
  NSAssert(sdkVersion != nil, @"Sdk version shouldn't be nil.");
  NSMutableArray *runtimes = [self _runtimesSupportedByDevice:deviceName];
  if ([runtimes count] == 0) {
    return NO;
  }

  if ([sdkVersion isEqualToString:@"latest"]) {
    return YES;
  }

  for (SimRuntime *runtime in runtimes) {
    if ([runtime.versionString hasPrefix:sdkVersion]) {
      return YES;
    }
  }

  return NO;
}

+ (NSArray *)availableSdkVersions
{
  return [[SimRuntime supportedRuntimes] valueForKeyPath:@"versionString"];
}

+ (NSArray *)sdksSupportedByDevice:(NSString *)deviceName
{
  NSArray *runtimes = [self _runtimesSupportedByDevice:deviceName];
  return [runtimes valueForKeyPath:@"versionString"];
}

+ (cpu_type_t)cpuTypeForDevice:(NSString *)deviceName
{
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceName];
  if ([deviceType.supportedArchs containsObject:@(CPU_TYPE_X86_64)]) {
    return CPU_TYPE_X86_64;
  } else {
    return CPU_TYPE_I386;
  }
}

#pragma mark -
#pragma mark Helpers

+ (NSMutableArray *)_runtimesSupportedByDevice:(NSString *)deviceName
{
  NSMutableArray *supportedRuntimes = [NSMutableArray array];
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceName];
  NSAssert(deviceType != nil, @"Unable to find SimDeviceType for the device with name \"%@\". Available device names: %@", deviceName, [[SimDeviceType supportedDeviceTypesByAlias] allKeys]);
  for (SimRuntime *runtime in [SimRuntime supportedRuntimes]) {
    if ([runtime supportsDeviceType:deviceType]) {
      [supportedRuntimes addObject:runtime];
    }
  }
  return supportedRuntimes;
}

+ (SimRuntime *)_runtimeForSDKPath:(NSString *)sdkPath
{
  DTiPhoneSimulatorSystemRoot *root = [SimulatorInfo _systemRootWithSDKPath:sdkPath];
  return [root runtime];
}

+ (NSArray *)_availableDeviceConfigurationsInHumanReadableFormat
{
  NSMutableArray *configs = [NSMutableArray array];
  for (SimDevice *device in [[SimDeviceSet defaultSet] availableDevices]) {
    [configs addObject:[NSString stringWithFormat:@"%@: %@", device.name, device.runtime.name]];
  }
  return configs;
}

#pragma mark -
#pragma mark Caching methods

/*
 * Caches `DTiPhoneSimulatorSystemRoot` instances.
 *
 * `sdkRootPath` -> `DTiPhoneSimulatorSystemRoot *`
 * `platformName` -> `NSDictionary *`: `sdkVersion` -> `DTiPhoneSimulatorSystemRoot *`
 *
 */
static NSDictionary *__systemRootsSdkPlatformVersionMap;
static NSDictionary *__systemRootsSdkPathMap;

+ (void)_warmUpDTiPhoneSimulatorSystemRootCaches
{
  // cache system roots
  NSArray *roots = [DTiPhoneSimulatorSystemRoot knownRoots];

  // create a map
  NSMutableDictionary *platformVersionMap = [NSMutableDictionary new];
  NSMutableDictionary *pathMap = [NSMutableDictionary new];
  for (DTiPhoneSimulatorSystemRoot *root in roots) {
    pathMap[root.sdkRootPath] = root;
    if (!platformVersionMap[root.platformName]) {
      platformVersionMap[root.platformName] = [NSMutableDictionary dictionary];
    }
    platformVersionMap[root.platformName][root.sdkVersion] = root;
  }
  __systemRootsSdkPlatformVersionMap = [platformVersionMap copy];
  __systemRootsSdkPathMap = [pathMap copy];
}

+ (DTiPhoneSimulatorSystemRoot *)_systemRootWithSDKPath:(NSString *)path
{
  // In Xcode 6 latest sdk path could be a symlink to iPhoneSimulator.sdk.
  // It should be resolved before comparing with `knownRoots` paths.
  path = [path stringByResolvingSymlinksInPath];
  return __systemRootsSdkPathMap[path];
}

+ (DTiPhoneSimulatorSystemRoot *)_systemRootForPlatform:(NSString *)platform sdkVersion:(NSString *)version
{
  for (NSString *cachedPlatform in  __systemRootsSdkPlatformVersionMap) {
    // sometimes platform may include version, for example, iphonesimulator9.2
    if ([cachedPlatform commonPrefixWithString:platform options:NSCaseInsensitiveSearch].length < 5) {
      continue;
    }
    NSDictionary *versions = __systemRootsSdkPlatformVersionMap[cachedPlatform];
    for (NSString *cachedVersion in versions) {
      // sdk version of system root usually consists of 2 numbers, like 9.2
      // but requested sdk version could have 3 numbers, like 9.2.1.
      if ([cachedVersion hasPrefix:version] || [version hasPrefix:cachedVersion]) {
        return versions[cachedVersion];
      }
    }
    break;
  }
  return nil;
}

@end


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

$this->inc('form_setup_html.php', array('view' => $view,
										'fDetails' => $controller->getFilesDetails(false, true),
										'fileSets' => $controller->getFileSetList(),
										'selectedFilesets' => $controller->getSelectedFilesets(),
										'isComposer' => true
										));
?>

<style>
	.ccm-inline-toolbar.ccm-ui.easy-image-toolbar {
		opacity: 1;
	}
	.easy-image-toolbar .ccm-inline-toolbar-button-save,
	.easy-image-toolbar .ccm-inline-toolbar-button-cancel {
		display: none;
	}
</style>