text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using FolderSelect;
using Parsers.Mod;
using TitleGenerator.HistoryRules;
using TitleGenerator.Properties;
using TitleGenerator.Tasks;
using TitleGenerator.Tasks.History;
using TitleGenerator.Tasks.History.Clear;
using TitleGenerator.Tasks.History.Independent;
using TitleGenerator.Tasks.TitleGeneration;

namespace TitleGenerator
{
	public partial class DataUI : Form
	{
		private readonly FolderSelectDialog m_fsd;
		private CK2Data m_ck2Data;
		private Dictionary<string, FileInfo> m_ruleSets;
		private Dictionary<string, FileInfo> m_gainsScripts;
		private Dictionary<string, FileInfo> m_allowsScripts;
		private RuleSet m_rules;
		private Logger m_log;
		private ProgressPopup m_progressPopup;
		private List<Mod> m_selectedMods;
		private bool m_updatePath = true;
		private bool m_hasUIData = false;

		private SettingsStore m_settings;

		public DataUI()
		{
			InitializeComponent();

			m_fsd = new FolderSelectDialog();
			m_fsd.Title = "Please select your Crusader Kings II install directory.";

			m_log = new Logger();
			m_log.LogLength = 100;
			m_progressPopup = new ProgressPopup( m_log );

			m_ck2Data = new CK2Data( m_log );

			m_settings = new SettingsStore();
			m_settings.Filename = "settings.dat";
			m_settings.Version = 5;

			LogHeader();
		}

		private void LogHeader()
		{
			FileVersionInfo fvi = FileVersionInfo.GetVersionInfo( Assembly.GetExecutingAssembly().Location );
			m_log.Log( "Kingdoms Abound Titular Title Generator Version " + fvi.FileVersion, Logger.LogType.Setting );
			m_log.Log( "CK2 Utility Library Version " + Parsers.Version.GetVersion(), Logger.LogType.Setting );
			m_log.Log( "Logging started at " + DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss" ), Logger.LogType.Setting );
		}

		private void ShowError( string body, string title )
		{
			MessageBox.Show( this, body, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
		}

		private Options GetOptions()
		{
			m_log.Log( "Getting Options", Logger.LogType.Data );

			Options o = new Options();
			Options.CultureOption co;
			Options.ReligionOption ro;
			Options.HistoryOption ho;
			Options.CreateHistoryOption cho;

			Mod m = GetMod();

			#region Culture/Religion

			if( cbTitleRestrictCulture.SelectedIndex == 0 )
				co = Options.CultureOption.None;
			else if( cbTitleRestrictCulture.SelectedIndex == 1 )
				co = Options.CultureOption.Culture;
			else
				co = Options.CultureOption.CultureGroup;

			if( cbTitleRestrictReligion.SelectedIndex == 0 )
				ro = Options.ReligionOption.None;
			else if( cbTitleRestrictReligion.SelectedIndex == 1 )
				ro = Options.ReligionOption.Religion;
			else
				ro = Options.ReligionOption.ReligionGroup;
			#endregion

			#region History
			if( cbHistoryMode.SelectedIndex == 0 )
			{
				ho = Options.HistoryOption.None;
				cho = Options.CreateHistoryOption.None;
			} else if( cbHistoryMode.SelectedIndex == 1 )
			{
				// Clear history mode.
				cho = Options.CreateHistoryOption.None;
				if( cbHistoryClearLevel.SelectedIndex == 0 )
					ho = Options.HistoryOption.Duchy;
				else if( cbHistoryClearLevel.SelectedIndex == 1 )
					ho = Options.HistoryOption.Kingdom;
				else
					ho = Options.HistoryOption.Empire;
			} else
			{
				// Create history mode.
				ho = Options.HistoryOption.County;
				if( cbHistoryCreateType.SelectedIndex == 0 )
					cho = Options.CreateHistoryOption.Counts;
				else if( cbHistoryCreateType.SelectedIndex == 1 )
					cho = Options.CreateHistoryOption.Dukes;
				else if( cbHistoryCreateType.SelectedIndex == 2 )
					cho = Options.CreateHistoryOption.Kings;
				else if( cbHistoryCreateType.SelectedIndex == 3 )
					cho = Options.CreateHistoryOption.Empires;
				else
					cho = Options.CreateHistoryOption.Random;
			}
			#endregion

			o.ReplaceDeJure = cbTitleReplaceDeJure.Checked;

			#region Replaces
			foreach( Mod mod in m_selectedMods )
			{
				if( mod.Replaces.Contains( @"common\landed_titles" ) )
					o.Replaces |= Options.EReplace.Titles;

				if( mod.Replaces.Contains( @"common\cultures" ) )
					o.Replaces |= Options.EReplace.Cultures;

				if( mod.Replaces.Contains( @"common\Religions" ) )
					o.Replaces |= Options.EReplace.Religions;

				if( mod.Replaces.Contains( @"gfx\flags" ) )
					o.Replaces |= Options.EReplace.Flags;

				if( mod.Replaces.Contains( @"localisation" ) )
					o.Replaces |= Options.EReplace.Localisation;

				if( mod.Replaces.Contains( @"history\provinces" ) )
					o.Replaces |= Options.EReplace.Provinces;

				if( mod.Replaces.Contains( @"common\dynasties" ) )
					o.Replaces |= Options.EReplace.Dynasties;

				if( mod.Replaces.Contains( @"common\eu4_converter" ) )
					o.Replaces |= Options.EReplace.Converter;
			}
			#endregion

			o.Data = m_ck2Data;
			o.HistoryState = new HistoryState();
			o.ReligionLimit = ro;
			o.CultureLimit = co;
			o.History = ho;
			o.CreateHistoryType = cho;

			int seed;
			if( cbHistorySeed.Checked )
				seed = (int)nudHistorySeed.Value;
			else
			{
				TimeSpan time = DateTime.Now - new DateTime( 1970, 1, 1, 0, 0, 0 );
				seed = (int)time.TotalSeconds;
			}
			o.Seed = seed;
			o.Random = new Random( seed );
			o.Data.SetMarkovRandom( o.Random );

			o.StartDate = (int)nudStartDate.Value;
			o.HistoryMaxChar = (int)nudHistoryMaxRealms.Value;
			o.HistoryMinChar = (int)nudHistoryMinRealms.Value;
			o.HistoryMaxReps = (int)nudHistoryMaxRepublics.Value;
			o.HistoryMinReps = (int)nudHistoryMinRepublics.Value;
			o.HistoryMinTheoc = (int)nudHistoryMinTheocracies.Value;
			o.HistoryMaxTheoc = (int)nudHistoryMaxTheocracies.Value;
			o.HistoryCulGroupMin = (int)nudHistoryCulGroupMin.Value;
			o.HistoryCulGroupMax = (int)nudHistoryCulGroupMax.Value;
			o.HistoryCulMin = (int)nudHistoryCulMin.Value;
			o.HistoryCulMax = (int)nudHistoryCulMax.Value;

			o.Mod = m;
			o.SelectedMods = m_selectedMods;

			o.KingdomShortNames = cbTitleShortKingdoms.Checked;
			o.EmpireShortNames = cbTitleShortEmpires.Checked;
			o.UseMod = m_selectedMods.Count > 0;

			o.CreateDuchies = cbTitleCreateDuchies.Checked;
			o.CreateKingdoms = cbTitleCreateKingdoms.Checked;
			o.CreateEmpires = cbTitleCreateEmpires.Checked;
			o.CountyLimit = (int)nudTitleLowerCounty.Value;
			o.DuchyLimit = (int)nudTitleLowerDuchy.Value;
			o.KingdomLimit = (int)nudTitleLowerKingdom.Value;
			o.RandomTitleColour = cbTitleRandomColour.Checked;

			ParseScripts( o );
			o.RuleSet = m_rules;

			o.CharID = m_rules.CharacterStartID != -1 ? m_rules.CharacterStartID : 100000000;

			return o;
		}

		private void ParseScripts( Options o )
		{
			List<string> scriptLines = new List<string>();
			string scriptName;

			m_log.Log( "Parsing Allows Scripts", Logger.LogType.Data );
			scriptName = m_allowsScripts[(string)lbAllowsList.SelectedItem].FullName;
			scriptLines.AddRange( File.ReadAllLines( scriptName ) );

			o.DuchyAllowsScript = Parse( scriptLines, o, 'd' );
			o.KingdomAllowsScript = Parse( scriptLines, o, 'k' );
			o.EmpireAllowsScript = Parse( scriptLines, o, 'e' );

			m_log.Log( "Parsing Gains Scripts", Logger.LogType.Data );
			scriptLines.Clear();
			scriptName = m_gainsScripts[(string)lbGainsList.SelectedItem].FullName;
			scriptLines.AddRange( File.ReadAllLines( scriptName ) );

			o.DuchyEffectsScript = Parse( scriptLines, o, 'd' );
			o.KingdomEffectsScript = Parse( scriptLines, o, 'k' );
			o.EmpireEffectsScript = Parse( scriptLines, o, 'e' );
		}

		private string Parse( List<string> lines, Options o, char level )
		{
			StringBuilder sb = new StringBuilder();
			string line;
			int condLvl = 0, delLevel = 0;
			bool delLine = false;

			for( int i = 0; i < lines.Count; i++ )
			{
				line = lines[i].Trim();

				if( line.StartsWith( "$EndIf", true, System.Globalization.CultureInfo.InvariantCulture ) )
				{
					if( condLvl == delLevel )
						delLine = false;

					condLvl--;
					continue;
				}

				if( line.StartsWith( "$If", true, System.Globalization.CultureInfo.InvariantCulture ) )
				{
					condLvl++;
					if( !delLine && !UsingCondition( line, o, level ) )
					{
						delLine = true;
						delLevel = condLvl;
					}
					continue;
				}

				if( !delLine )
				{
					sb.AppendLine( lines[i] );
					continue;
				}
			}

			return sb.ToString();
		}

		private bool UsingCondition( string line, Options o, char level )
		{
			if( line.Equals( "$IfNoCul", StringComparison.InvariantCultureIgnoreCase ) &&
				o.CultureLimit == Options.CultureOption.None )
				return true;
			if( line.Equals( "$IfCul", StringComparison.InvariantCultureIgnoreCase ) &&
				o.CultureLimit == Options.CultureOption.Culture )
				return true;
			if( line.Equals( "$IfCulGroup", StringComparison.InvariantCultureIgnoreCase ) &&
				o.CultureLimit == Options.CultureOption.CultureGroup )
				return true;

			if( line.Equals( "$IfNoRel", StringComparison.InvariantCultureIgnoreCase ) &&
				o.ReligionLimit == Options.ReligionOption.None )
				return true;
			if( line.Equals( "$IfRel", StringComparison.InvariantCultureIgnoreCase ) &&
				o.ReligionLimit == Options.ReligionOption.Religion )
				return true;
			if( line.Equals( "$IfRelGroup", StringComparison.InvariantCultureIgnoreCase ) &&
				o.ReligionLimit == Options.ReligionOption.ReligionGroup )
				return true;

			if( line.Equals( "$IfIsDuchy", StringComparison.InvariantCultureIgnoreCase ) && level == 'd' )
				return true;
			if( line.Equals( "$IfIsKingdom", StringComparison.InvariantCultureIgnoreCase ) && level == 'k' )
				return true;
			if( line.Equals( "$IfIsEmpire", StringComparison.InvariantCultureIgnoreCase ) && level == 'e' )
				return true;

			if( line.Equals( "$IfMakeDeJure", StringComparison.InvariantCultureIgnoreCase ) && o.ReplaceDeJure )
				return true;

			return false;
		}

		private Mod GetMod()
		{
			m_log.Log( "Getting Mod", Logger.LogType.Data );
			Mod m = new Mod();

			string[] invalidChars = {"-", "+", "/", "\\", " ", "[", "]", "<", ">",
                               "*", "^", "%", "$", "#", "@", "!", "(", ")",};

			string cleanedOutput = invalidChars.Aggregate( tbModName.Text, ( c, t ) => c.Replace( t, "" ) );

			m.Name = tbModName.Text;
			m.Path = Path.Combine( "mod", cleanedOutput ).Replace( '\\', '/' );
			m.ModFile = cleanedOutput + ".mod";
			m.ModPathType = ModReader.Folder.MyDocs;

			foreach( Mod mod in m_selectedMods )
				m.Dependencies.Add( mod.Name );

			return m;
		}

		#region Data Panel Functions
		private void LoadCK2()
		{
			m_ck2Data.LoadData( null, CK2Data.DataTypes.Mods );

			DirectoryInfo dir;

			string path = Path.Combine( Environment.CurrentDirectory, "scripts/rules" ).Replace( '\\', '/' );
			dir = new DirectoryInfo( path );
			if( !dir.Exists )
				throw new DirectoryNotFoundException( "Unable to find scripts/rules" );
			m_ruleSets = dir.GetFiles( "*.txt", SearchOption.TopDirectoryOnly ).ToDictionary( f => f.Name.Replace( f.Extension, "" ) );

			path = Path.Combine( Environment.CurrentDirectory, "scripts/gains" ).Replace( '\\', '/' );
			dir = new DirectoryInfo( path );
			if( !dir.Exists )
				throw new DirectoryNotFoundException( "Unable to find scripts/gains" );
			m_gainsScripts = dir.GetFiles( "*.txt", SearchOption.TopDirectoryOnly ).ToDictionary( f => f.Name.Replace( f.Extension, "" ) );

			path = Path.Combine( Environment.CurrentDirectory, "scripts/allows" ).Replace( '\\', '/' );
			dir = new DirectoryInfo( path );
			if( !dir.Exists )
				throw new DirectoryNotFoundException( "Unable to find scripts/allows" );
			m_allowsScripts = dir.GetFiles( "*.txt", SearchOption.TopDirectoryOnly ).ToDictionary( f => f.Name.Replace( f.Extension, "" ) );

			PopulateControls();
		}

		private void PopulateControls()
		{
			int i;
			m_log.Log( "Splitting Selected Rules List", Logger.LogType.Data );
			List<string> names = m_settings.SelectedRules.Split( ';' ).ToList();

			m_log.Log( "Listing Allows Scripts", Logger.LogType.Data );
			foreach( var fi in m_allowsScripts )
			{
				m_log.Log( " --" + fi.Key, Logger.LogType.Data );
				i = lbAllowsList.Items.Add( fi.Key );
				if( fi.Key == m_settings.AllowsSelected )
					lbAllowsList.SelectedIndex = i;
			}
			m_log.Log( "Listing Gains Scripts", Logger.LogType.Data );
			foreach( var fi in m_gainsScripts )
			{
				m_log.Log( " --" + fi.Key, Logger.LogType.Data );
				i = lbGainsList.Items.Add( fi.Key );
				if( fi.Key == m_settings.GainsSelected )
					lbGainsList.SelectedIndex = i;
			}
			m_log.Log( "Listing Rule Sets", Logger.LogType.Data );
			foreach( var fi in m_ruleSets )
			{
				m_log.Log( " --" + fi.Key, Logger.LogType.Data );
				i = cbRuleList.Items.Add( fi.Key );
				if( names.Contains( fi.Key ) )
					cbRuleList.SetItemChecked( i, true );
			}

			m_log.Log( "Fetching Mods", Logger.LogType.Data );
			ReadOnlyCollection<Mod> mods = m_ck2Data.GetMods;
			m_log.Log( "Splitting Selected Mods List", Logger.LogType.Data );
			names = m_settings.SelectedMods.Split( ';' ).ToList();

			m_log.Log( "Filtering and Listing Mods", Logger.LogType.Data );
			foreach( Mod m in mods )
			{
				m_log.Log( " --" + m.Name, Logger.LogType.Data );
				string dirTemp = m.ModPathType == ModReader.Folder.CKDir ? m_ck2Data.InstallDir.FullName : m_ck2Data.MyDocsDir.FullName;
				dirTemp = Path.Combine( dirTemp, m.Path );

				if( !Directory.Exists( Path.Combine( dirTemp, "common/landed_titles" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "common/religions" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "common/cultures" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "common/dynasties" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "gfx/flags" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "localisation" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "history/provinces" ) )
				 && !Directory.Exists( Path.Combine( dirTemp, "map" ) ) )
					continue;

				i = cbModList.Items.Add( m );
				if( names.Contains( m.Name ) )
					cbModList.SetItemChecked( i, true );
			}

			m_log.Log( "Setting Selected Indexes", Logger.LogType.Data );
			if( lbAllowsList.SelectedIndex == -1 )
				lbAllowsList.SelectedIndex = 0;
			if( lbGainsList.SelectedIndex == -1 )
				lbGainsList.SelectedIndex = 0;

			UpdateModName();
		}

		private void ClearCK2()
		{
			m_ck2Data.Clear( CK2Data.DataTypes.Mods | CK2Data.DataTypes.Religions | CK2Data.DataTypes.Cultures
						   | CK2Data.DataTypes.Dynasties | CK2Data.DataTypes.LandedTitles
						   | CK2Data.DataTypes.Localisations | CK2Data.DataTypes.Provinces );

			cbModList.Items.Clear();
			cbRuleList.Items.Clear();
			lbAllowsList.Items.Clear();
			lbGainsList.Items.Clear();
		}

		private void CheckCKDir( string selectedPath )
		{
			m_log.Log( "Checking Directory: " + selectedPath, Logger.LogType.Data );

			try
			{
				if( m_ck2Data.SetInstallPath( new DirectoryInfo( selectedPath ) ) )
				{
					if( m_updatePath )
						tbCKFolder.Text = selectedPath;

					gbAllows.Enabled = true;
					gbGains.Enabled = true;
					gbOther.Enabled = true;
					gbMods.Enabled = true;
					gbRuleSets.Enabled = true;
					btnLoadData.Enabled = true;

					ClearCK2();
					LoadCK2();
					m_hasUIData = true;
				} else
				{
					gbAllows.Enabled = false;
					gbGains.Enabled = false;
					gbOther.Enabled = false;
					gbMods.Enabled = false;
					gbRuleSets.Enabled = false;
					btnLoadData.Enabled = false;

					ShowError( "Unable to find CK2 install in path.\n\n" + selectedPath, "Unable to Find CK2" );

					ClearCK2();
					m_hasUIData = false;
				}
			} catch( Exception ex )
			{
				if( m_ck2Data.HadError )
				{
					m_log.Log( m_ck2Data.Error, Logger.LogType.Error );
					m_log.Log( "", Logger.LogType.Error );
				}

				m_log.Log( ex.ToString(), Logger.LogType.Error );
				m_log.Dump( "log.txt" );
				ShowError( "An error has been encountered while loading. Please check the log file.", "Error" );
			}
		}

		private void UpdateModName()
		{
			var checkedMods = cbModList.CheckedItems;

			if( checkedMods.Count == 0 )
				tbModName.Text = "Kingdoms Abound";
			else if( checkedMods.Count == 1 )
				tbModName.Text = "KA for " + ( (Mod)checkedMods[0] ).Name;
			else
				tbModName.Text = "KA for Multiple Mods";
		}

		private List<Mod> SortMods()
		{
			List<Mod> selected = cbModList.CheckedItems.Cast<Mod>().ToList();

			if( selected.Count <= 1 )
				return selected;

			for( int i = 1; i < selected.Count; i++ )
			{
				for( int j = 0; j < i; j++ )
				{
					Mod current = selected[j];
					Mod next = selected[i];

					if( !current.Dependencies.Contains( next.Name ) && next.Dependencies.Count != 0 )
						continue;

					selected[j] = next;
					selected[i] = current;
				}
			}

			return selected;
		}

		private bool LoadRulesets()
		{
			m_rules = new RuleSet();

			m_log.Log( "Loading Rule Sets", Logger.LogType.Data );
			var rules = cbRuleList.CheckedItems;
			RuleSet rs;
			List<RuleSet> ruleSets = new List<RuleSet>();
			foreach( string s in rules )
			{
				rs = RuleSet.Parse( m_ruleSets[s].FullName, s );

				if( rs.Errors.Count > 0 )
				{
					m_rules = rs;
					return false;
				}

				ruleSets.Add( rs );
			}

			m_log.Log( "Loaded " + ruleSets.Count + " Rule Sets", Logger.LogType.Data );

			#region Check Rule Sets Have Loaded Required Rules.
			bool hasAllLoaded = true;
			List<string> reqList = new List<string>();
			foreach( RuleSet r in ruleSets )
			{
				foreach( string requiredRule in r.RequiredRules )
				{
					if( !rules.Contains( requiredRule ) )
					{
						hasAllLoaded = false;
						reqList.Add( requiredRule );
					}
				}
			}

			if( !hasAllLoaded )
			{
				StringBuilder errorSb = new StringBuilder();
				errorSb.AppendLine( "One or more selected rule sets have requirements that are not checked." );
				errorSb.AppendLine().AppendLine();
				reqList.ForEach( s => errorSb.AppendLine( s ) );
				errorSb.AppendLine();
				errorSb.Append( "Please check the required rule sets." );

				m_log.Log( errorSb.ToString(), Logger.LogType.Data );
				ShowError( errorSb.ToString(), "Rule Sets Required." );
				return false;
			}
			#endregion

			#region Sort Rule Sets
			if( ruleSets.Count > 1 )
			{
				for( int i = 1; i < ruleSets.Count; i++ )
				{
					for( int j = 0; j < i; j++ )
					{
						RuleSet curr = ruleSets[j];
						RuleSet next = ruleSets[i];
						if( curr.RequiredRules.Contains( next.Name ) && next.RequiredRules.Count != 0 )
							continue;

						ruleSets[j] = next;
						ruleSets[i] = curr;
					}
				}
			}
			#endregion

			m_log.Log( "Combining Rule Sets", Logger.LogType.Data );
			#region Combining
			foreach( RuleSet rule in ruleSets )
			{
				foreach( CharacterRule cr in rule.CharRules )
					if( !m_rules.CharRules.Contains( cr ) )
						m_rules.CharRules.Add( cr );

				foreach( string s in rule.IgnoredTitles )
					if( !m_rules.IgnoredTitles.Contains( s ) )
						m_rules.IgnoredTitles.Add( s );

				foreach( string s in rule.FemaleCultures )
					if( !m_rules.FemaleCultures.Contains( s ) )
						m_rules.FemaleCultures.Add( s );

				foreach( string s in rule.FemaleReligions )
					if( !m_rules.FemaleReligions.Contains( s ) )
						m_rules.FemaleReligions.Add( s );

				foreach( string s in rule.MaleCultures )
					if( !m_rules.MaleCultures.Contains( s ) )
						m_rules.MaleCultures.Add( s );

				foreach( string s in rule.MaleReligions )
					if( !m_rules.MaleReligions.Contains( s ) )
						m_rules.MaleReligions.Add( s );

				foreach( string s in rule.MuslimLawFollowers )
					if( !m_rules.MuslimLawFollowers.Contains( s ) )
						m_rules.MuslimLawFollowers.Add( s );

				foreach( Law l in rule.LawRules.GenderLaws )
					if( !m_rules.LawRules.GenderLaws.Contains( l ) )
						m_rules.LawRules.GenderLaws.Add( l );

				foreach( Law l in rule.LawRules.SuccessionLaws )
					if( !m_rules.LawRules.SuccessionLaws.Contains( l ) )
						m_rules.LawRules.SuccessionLaws.Add( l );

				if( rule.LawRules.LevyTax.Min != 0
				  && rule.LawRules.LevyTax.Normal != 0
				  && rule.LawRules.LevyTax.Large != 0
				  && rule.LawRules.LevyTax.Max != 0 )
				{
					m_rules.LawRules.LevyTax = rule.LawRules.LevyTax;
					m_rules.LawRules.ParentRuleSet = m_rules;
				}

				if( rule.LiegeCultureChance != -1 )
					m_rules.LiegeCultureChance = rule.LiegeCultureChance;
				if( rule.LiegeReligionChance != -1 )
					m_rules.LiegeReligionChance = rule.LiegeReligionChance;
				if( rule.FemaleRulerChance != -1 )
					m_rules.FemaleRulerChance = rule.FemaleRulerChance;
				if( rule.RulerSpouseChance != -1 )
					m_rules.RulerSpouseChance = rule.RulerSpouseChance;
				if( rule.RepsForceCustomDuchies != null )
					m_rules.RepsForceCustomDuchies = rule.RepsForceCustomDuchies;
				if( rule.RepublicExpandChance != -1 )
					m_rules.RepublicExpandChance = rule.RepublicExpandChance;
				if( rule.RepublicExpandMax != -1 )
					m_rules.RepublicExpandMax = rule.RepublicExpandMax;

				if( rule.EmpireMinSize != -1 )
					m_rules.EmpireMinSize = rule.EmpireMinSize;
				if( rule.KingdomMinSize != -1 )
					m_rules.KingdomMinSize = rule.KingdomMinSize;
				if( rule.DuchyMinSize != -1 )
					m_rules.DuchyMinSize = rule.DuchyMinSize;

				if( rule.ClearCharacters != null )
					m_rules.ClearCharacters = rule.ClearCharacters;
				if( rule.CharacterStartID != -1 )
					m_rules.CharacterStartID = rule.CharacterStartID;

				if( rule.CulGenDynastyPrefix != -1 )
					m_rules.CulGenDynastyPrefix = rule.CulGenDynastyPrefix;
				if( rule.CulGenBastardPrefix != -1 )
					m_rules.CulGenBastardPrefix = rule.CulGenBastardPrefix;

				if( rule.CulGenPatronymIsPrefix != -1 )
					m_rules.CulGenPatronymIsPrefix = rule.CulGenPatronymIsPrefix;
				if( rule.CulGenMalePatronym != -1 )
					m_rules.CulGenMalePatronym = rule.CulGenMalePatronym;
				if( rule.CulGenFemalePatronym != -1 )
					m_rules.CulGenFemalePatronym = rule.CulGenFemalePatronym;

				if( rule.CulGenAncestorName != -1 )
					m_rules.CulGenAncestorName = rule.CulGenAncestorName;
				if( rule.CulGenDisinheritFromBlinding != -1 )
					m_rules.CulGenDisinheritFromBlinding = rule.CulGenDisinheritFromBlinding;
				if( rule.CulGenDukesCalledKings != -1 )
					m_rules.CulGenDukesCalledKings = rule.CulGenDukesCalledKings;
				if( rule.CulGenFounderNamesDynasty != -1 )
					m_rules.CulGenFounderNamesDynasty = rule.CulGenFounderNamesDynasty;
				if( rule.CulGenDynastyTitleNames != -1 )
					m_rules.CulGenDynastyTitleNames = rule.CulGenDynastyTitleNames;
			}
			#endregion

			return true;
		}

		private void VerifyData()
		{
			bool isInvalid = false;

			if( m_ck2Data.Counties == null || m_ck2Data.Duchies == null )
				isInvalid = true;
			if( m_ck2Data.Kingdoms == null || m_ck2Data.Empires == null )
				isInvalid = true;
			if( m_ck2Data.Cultures == null || m_ck2Data.CultureGroups == null )
				isInvalid = true;
			if( m_ck2Data.Religions == null || m_ck2Data.ReligionGroups == null )
				isInvalid = true;
			if( m_ck2Data.Dynasties == null || m_ck2Data.Provinces == null )
				isInvalid = true;

			if( isInvalid )
				throw new Exception( "One or more data dictionaries are null." );

			if( m_ck2Data.Counties.Count == 0 || m_ck2Data.Duchies.Count == 0 )
				isInvalid = true;
			if( m_ck2Data.Kingdoms.Count == 0 || m_ck2Data.Empires.Count == 0 )
				isInvalid = true;
			if( m_ck2Data.Cultures.Count == 0 || m_ck2Data.CultureGroups.Count == 0 )
				isInvalid = true;
			if( m_ck2Data.Religions.Count == 0 || m_ck2Data.ReligionGroups.Count == 0 )
				isInvalid = true;
			if( m_ck2Data.Dynasties.Count == 0 || m_ck2Data.Provinces.Count == 0 )
				isInvalid = true;

			if( isInvalid )
				throw new Exception( "One or more data dictionaries are empty." );
		}

		#endregion

		private void RunTasks( List<ITask> tasks, string message, Logger.LogType type )
		{
			m_progressPopup.SetTasks( tasks, message );

			if( m_progressPopup.ShowDialog( this ) == DialogResult.Abort )
			{
				ShowError( "An error was encountered running the selected task.\n\nPlease check the log file.", "Unable to complete task." );
				m_log.Log( "An error was encountered running the selected task:", Logger.LogType.Data );
				foreach( ITask t in tasks )
					foreach( string s in t.Errors )
						m_log.Log( s, type );
			}
		}

		#region Data Panel Events
		private void btnCKFolder_Click( object sender, EventArgs e )
		{
			if( m_fsd.ShowDialog( this.Handle ) )
				CheckCKDir( m_fsd.FileName );
		}

		private void tbCKFolder_Leave( object sender, EventArgs e )
		{
			if( String.IsNullOrEmpty( tbCKFolder.Text ) )
				return;

			m_updatePath = false;
			CheckCKDir( tbCKFolder.Text );
			m_updatePath = true;
		}

		private void btnLoadData_Click( object sender, EventArgs e )
		{
			if( cbRuleList.CheckedItems.Count == 0 )
			{
				ShowError( "You must have at least one rule set selected to continue.", "Rule Set Required" );
				return;
			}

			m_log.Log( "Loading CK2 Data.", Logger.LogType.Data );

			FileInfo fi = m_gainsScripts[(string)lbGainsList.SelectedItem];
			if( !fi.Exists )
			{
				m_log.Log( "Unable to find gain_effects script:" + fi.Name, Logger.LogType.Data );
				m_log.Dump( "log.txt" );
				ShowError( "Cannot find Gain Effects script file: " + fi.Name, "Unable to load data." );
				return;
			}

			fi = m_allowsScripts[(string)lbAllowsList.SelectedItem];
			if( !fi.Exists )
			{
				m_log.Log( "Unable to find gain_effects script:" + fi.Name, Logger.LogType.Data );
				m_log.Dump( "log.txt" );
				ShowError( "Cannot find Allows script file: " + fi.Name, "Unable to load data." );
				return;
			}

			m_log.Log( "Sorting Mods", Logger.LogType.Data );
			m_selectedMods = SortMods();
			m_log.Log( m_selectedMods.Count + " Mods Sorted", Logger.LogType.Data );

			if( !LoadRulesets() )
			{
				ShowError( "An error was encountered while parsing the Rule Sets.\n\nPlease check the log file.", "Unable to load data." );
				m_log.Log( "The following errors were encountered parsing the selected Rule Sets: ", Logger.LogType.Data );
				m_log.Dump( "log.txt" );
				foreach( string s in m_rules.Errors )
					m_log.Log( s, Logger.LogType.Data );

				return;
			}

			LoadTask lt = new LoadTask( m_ck2Data, m_log, m_selectedMods );
			List<ITask> tasks = new List<ITask>();
			tasks.Add( lt );
			RunTasks( tasks, "Loading Data from CKII", Logger.LogType.Data );

			VerifyData();

			btnGenerateTitles.Enabled = !TaskStatus.Abort;
		}

		private void cbModList_MouseUp( object sender, MouseEventArgs e )
		{
			UpdateModName();
		}

		private void cbFullLog_CheckedChanged( object sender, EventArgs e )
		{
			m_log.FullLog = cbFullLog.Checked;
		}
		#endregion

		private void DataUI_Load( object sender, EventArgs e )
		{
			m_settings.Load();

			this.Location = m_settings.WindowLocation;

			string dirTemp = m_settings.CKIIDirectory;
			if( !String.IsNullOrEmpty( dirTemp ) )
				CheckCKDir( dirTemp );

			cbHistoryMode.SelectedIndex = m_settings.HistoryMode;
			cbHistoryClearLevel.SelectedIndex = m_settings.HistoryClearLevel;
			cbHistoryCreateType.SelectedIndex = m_settings.HistoryCreateType;
			nudStartDate.Value = m_settings.HistoryStartDate;
			nudHistorySeed.Value = m_settings.HistorySeed;
			cbHistorySeed.Checked = m_settings.HistorySeedEnabled;
			nudHistoryMinRealms.Value = m_settings.HistoryMinRealms;
			nudHistoryMaxRealms.Value = m_settings.HistoryMaxRealms;
			nudHistoryMinRepublics.Value = m_settings.HistoryMinRepublics;
			nudHistoryMaxRepublics.Value = m_settings.HistoryMaxRepublics;
			nudHistoryMinTheocracies.Value = m_settings.HistoryMinTheocracies;
			nudHistoryMaxTheocracies.Value = m_settings.HistoryMaxTheocracies;
			nudHistoryCulGroupMax.Value = m_settings.HistoryCulGroupMax;
			nudHistoryCulGroupMin.Value = m_settings.HistoryCulGroupMin;
			nudHistoryCulMax.Value = m_settings.HistoryCulMax;
			nudHistoryCulMin.Value = m_settings.HistoryCulMin;
			cbHistoryCultureGen.Checked = m_settings.HistoryGenerateCultures;

			cbTitleCreateDuchies.Checked = m_settings.TitleCreateDuchies;
			cbTitleCreateKingdoms.Checked = m_settings.TitleCreateKingdoms;
			cbTitleCreateEmpires.Checked = m_settings.TitleCreateEmpires;
			cbTitleShortKingdoms.Checked = m_settings.TitleShortKingdoms;
			cbTitleShortEmpires.Checked = m_settings.TitleShortEmpires;
			cbTitleRandomColour.Checked = m_settings.TitleRandomColour;

			cbTitleRestrictCulture.SelectedIndex = m_settings.TitleRestrictCulture;
			cbTitleRestrictReligion.SelectedIndex = m_settings.TitleRestrictReligion;
			nudTitleLowerCounty.Value = m_settings.TitleRestrictCounty;
			nudTitleLowerDuchy.Value = m_settings.TitleRestrictDuchy;
			nudTitleLowerKingdom.Value = m_settings.TitleRestrictKingdom;

			cbTitleReplaceDeJure.Checked = m_settings.TitleReplaceDeJure;
		}

		private void DataUI_FormClosed( object sender, FormClosedEventArgs e )
		{
			if( !m_hasUIData )
				return;

			m_settings.WindowLocation = this.Location;

			m_settings.CKIIDirectory = m_ck2Data.InstallDir.FullName;
			m_settings.AllowsSelected = (string)lbAllowsList.SelectedItem;
			m_settings.GainsSelected = (string)lbGainsList.SelectedItem;

			CheckedListBox.CheckedItemCollection checkedItems = cbRuleList.CheckedItems;
			string temp = checkedItems.Cast<string>().Aggregate( string.Empty, ( c, m ) => c + ( m + ";" ) );
			m_settings.SelectedRules = temp;

			checkedItems = cbModList.CheckedItems;
			temp = checkedItems.Cast<Mod>().Aggregate( string.Empty, ( c, m ) => c + ( m.Name + ";" ) );
			m_settings.SelectedMods = temp;

			m_settings.HistoryMode = cbHistoryMode.SelectedIndex;
			m_settings.HistoryClearLevel = cbHistoryClearLevel.SelectedIndex;
			m_settings.HistoryCreateType = cbHistoryCreateType.SelectedIndex;
			m_settings.HistoryStartDate = nudStartDate.Value;
			m_settings.HistorySeed = nudHistorySeed.Value;
			m_settings.HistorySeedEnabled = cbHistorySeed.Checked;
			m_settings.HistoryMinRealms = nudHistoryMinRealms.Value;
			m_settings.HistoryMaxRealms = nudHistoryMaxRealms.Value;
			m_settings.HistoryMinRepublics = nudHistoryMinRepublics.Value;
			m_settings.HistoryMaxRepublics = nudHistoryMaxRepublics.Value;
			m_settings.HistoryMinTheocracies = nudHistoryMinTheocracies.Value;
			m_settings.HistoryMaxTheocracies = nudHistoryMaxTheocracies.Value;
			m_settings.HistoryCulGroupMin = nudHistoryCulGroupMin.Value;
			m_settings.HistoryCulGroupMax = nudHistoryCulGroupMax.Value;
			m_settings.HistoryCulMin = nudHistoryCulMin.Value;
			m_settings.HistoryCulMax = nudHistoryCulMax.Value;
			m_settings.HistoryGenerateCultures = cbHistoryCultureGen.Checked;

			m_settings.TitleCreateDuchies = cbTitleCreateDuchies.Checked;
			m_settings.TitleCreateKingdoms = cbTitleCreateKingdoms.Checked;
			m_settings.TitleCreateEmpires = cbTitleCreateEmpires.Checked;
			m_settings.TitleShortKingdoms = cbTitleShortKingdoms.Checked;
			m_settings.TitleShortEmpires = cbTitleShortEmpires.Checked;
			m_settings.TitleRandomColour = cbTitleRandomColour.Checked;

			m_settings.TitleRestrictCulture = cbTitleRestrictCulture.SelectedIndex;
			m_settings.TitleRestrictReligion = cbTitleRestrictReligion.SelectedIndex;
			m_settings.TitleRestrictCounty = nudTitleLowerCounty.Value;
			m_settings.TitleRestrictDuchy = nudTitleLowerDuchy.Value;
			m_settings.TitleRestrictKingdom = nudTitleLowerKingdom.Value;

			m_settings.TitleReplaceDeJure = cbTitleReplaceDeJure.Checked;

			m_settings.Save();

			if( cbFullLog.Checked )
				m_log.Dump( "log.txt" );
		}

		#region Generate Panel Events
		private void cbHistoryMode_SelectedIndexChanged( object sender, EventArgs e )
		{
			if( cbHistoryMode.SelectedIndex == 0 )
			{
				gbHistoryClearOptions.Enabled = false;
				gbHistoryGenerateOptions.Enabled = false;
			} else if( cbHistoryMode.SelectedIndex == 1 )
			{
				gbHistoryClearOptions.Enabled = true;
				gbHistoryGenerateOptions.Enabled = false;
			} else
			{
				gbHistoryClearOptions.Enabled = false;
				gbHistoryGenerateOptions.Enabled = true;
			}
		}

		private void cbHistorySeed_CheckedChanged( object sender, EventArgs e )
		{
			nudHistorySeed.Enabled = cbHistorySeed.CheckState == CheckState.Checked;
		}

		private void cbHistoryCreateType_SelectedIndexChanged( object sender, EventArgs e )
		{
			gbHistoryFullCreateOptions.Enabled = cbHistoryCreateType.SelectedIndex == 4;
		}

		private void cbHistoryCultureGen_CheckedChanged( object sender, EventArgs e )
		{
			gbHistoryCulGroups.Enabled = cbHistoryCultureGen.Checked;
			gbHistoryCultures.Enabled = cbHistoryCultureGen.Checked;
		}

		private void nudHistoryMinRealms_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMinRealms.Value > nudHistoryMaxRealms.Value )
				nudHistoryMinRealms.Value = nudHistoryMaxRealms.Value;
		}

		private void nudHistoryMaxRealms_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMaxRealms.Value < nudHistoryMinRealms.Value )
				nudHistoryMaxRealms.Value = nudHistoryMinRealms.Value;
		}

		private void nudHistoryMinRepublics_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMinRepublics.Value > nudHistoryMaxRepublics.Value )
				nudHistoryMinRepublics.Value = nudHistoryMaxRepublics.Value;
		}

		private void nudHistoryMaxRepublics_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMaxRepublics.Value < nudHistoryMinRepublics.Value )
				nudHistoryMaxRepublics.Value = nudHistoryMinRepublics.Value;
		}

		private void nudHistoryMinTheocracies_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMinTheocracies.Value > nudHistoryMaxTheocracies.Value )
				nudHistoryMinTheocracies.Value = nudHistoryMaxTheocracies.Value;
		}

		private void nudHistoryMaxTheocracies_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryMaxTheocracies.Value < nudHistoryMinTheocracies.Value )
				nudHistoryMaxTheocracies.Value = nudHistoryMinTheocracies.Value;
		}

		private void nudHistoryCulGroupMin_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryCulGroupMin.Value > nudHistoryCulGroupMax.Value )
				nudHistoryCulGroupMin.Value = nudHistoryCulGroupMax.Value;
		}

		private void nudHistoryCulGroupMax_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryCulGroupMax.Value < nudHistoryCulGroupMin.Value )
				nudHistoryCulGroupMax.Value = nudHistoryCulGroupMin.Value;
		}

		private void nudHistoryCulMin_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryCulMin.Value > nudHistoryCulMax.Value )
				nudHistoryCulMin.Value = nudHistoryCulMax.Value;
		}

		private void nudHistoryCulMax_ValueChanged( object sender, EventArgs e )
		{
			if( nudHistoryCulMax.Value < nudHistoryCulMin.Value )
				nudHistoryCulMax.Value = nudHistoryCulMin.Value;
		}

		private void GetHistoryTasks( List<ITask> taskList, Options options )
		{
			if( options.History != Options.HistoryOption.None )
			{
				if( options.History == Options.HistoryOption.County )
				{
					taskList.Add( new ClearCountsTask( options, m_log ) );
					taskList.Add( new ClearDukesTask( options, m_log ) );
					taskList.Add( new ClearKingsTask( options, m_log ) );
					taskList.Add( new ClearEmperorsTask( options, m_log ) );
				}
				if( options.History == Options.HistoryOption.Duchy )
				{
					taskList.Add( new ClearDukesTask( options, m_log ) );
					taskList.Add( new ClearKingsTask( options, m_log ) );
					taskList.Add( new ClearEmperorsTask( options, m_log ) );
				}
				if( options.History == Options.HistoryOption.Kingdom )
				{
					taskList.Add( new ClearKingsTask( options, m_log ) );
					taskList.Add( new ClearEmperorsTask( options, m_log ) );
				}
				if( options.History == Options.HistoryOption.Empire )
				{
					taskList.Add( new ClearEmperorsTask( options, m_log ) );
				}
			}

			if( options.CreateHistoryType != Options.CreateHistoryOption.None )
			{
				if( options.RuleSet.ClearCharacters == true )
					taskList.Add( new ClearCharactersTask( options, m_log ) );

				if( options.CreateHistoryType == Options.CreateHistoryOption.Counts )
					taskList.Add( new IndependentCountsTask( options, m_log ) );

				if( options.CreateHistoryType == Options.CreateHistoryOption.Dukes )
					taskList.Add( new IndependentDukesTask( options, m_log ) );

				if( options.CreateHistoryType == Options.CreateHistoryOption.Kings )
					taskList.Add( new IndependentKingsTask( options, m_log ) );

				if( options.CreateHistoryType == Options.CreateHistoryOption.Empires )
					taskList.Add( new IndependentEmperorsTask( options, m_log ) );

				if( options.CreateHistoryType == Options.CreateHistoryOption.Random )
					taskList.Add( new FullHistoryTask( options, m_log ) );
			}
		}

		private void btnGenerateTitles_Click( object sender, EventArgs e )
		{
			try
			{
				m_log.Log( "", Logger.LogType.Setting );
				Options o = GetOptions();
				m_log.Log( o.ToString(), Logger.LogType.Setting );
				nudHistorySeed.Value = o.Seed;

				List<ITask> taskList = new List<ITask>();
				//taskList.Add( new DumpDataTask( o, m_log ) );
				taskList.Add( new DeleteModTask( o, m_log ) );
				taskList.Add( new ApplyProvinceHistory( o, m_log ) );
				if( m_ck2Data.HasFullMarkovChains )
				{
					if( cbHistoryCultureGen.Checked )
						taskList.Add( new CultureGenerationTask( o, m_log ) );
				} else
				{
					var res = MessageBox.Show( this,
									"Unable to generate cultures because of incomplete Name Data.\n\n" +
									"Continue with generation?",
									"Incomplete Name Data",
									 MessageBoxButtons.YesNo, MessageBoxIcon.Warning );
					if( res == DialogResult.No )
						return;
				}
				taskList.Add( new CheckTitleTask( o, m_log ) );

				if( o.CreateDuchies || o.CreateKingdoms || o.CreateEmpires )
				{
					taskList.Add( new LocalisationTask( o, m_log ) );
					taskList.Add( new CreateTitleTask( o, m_log ) );
					taskList.Add( new FlagTask( o, m_log ) );
					taskList.Add( new NationTableTask( o, m_log ) );
				}

				GetHistoryTasks( taskList, o );

				taskList.Add( new ModWriteTask( o, m_log ) );
				taskList.Add( new ResetHistory( o, m_log ) );
				RunTasks( taskList, "Generating Titles", Logger.LogType.Generate );

				o.Data.ClearCustomCultures( o );

			} catch( Exception ex )
			{
				m_log.Log( ex.ToString(), Logger.LogType.Data );
				ShowError( "An error was encountered generating the mod.\n\nPlease check the log file.", "An Error was Encountered" );
				m_log.Dump( "log.txt" );
			}
		}

		#endregion
	}
}


text:
default['mysql']['server_root_password'] = 'rootpass'
default['mysql']['server_debian_password'] = 'debpass'
default['mysql']['server_repl_password'] = 'rootpass'

redpajama_set_name: RedPajamaGithub


text:
<form class="form-inline">

        <button class="btn" ng-class="{true:'btn-danger',false:'btn-primary'}[updateActive]"
                btn-checkbox ng-model="updateActive"
                tooltip-placement="bottom" tooltip="Start/Stop continuous metrics updates.">
            {{ updateActive ? 'Enabled' : 'Disabled' }}({{metricsActive}})
        </button>
        <button class="btn btn-primary" ng-click="refresh()">Gather</button>
        <button class="btn btn-primary" ng-click="$broadcast('timeSeriesClear')"
                tooltip-placement="bottom" tooltip="Clear the timeline.">
            Clear
        </button>

        <select ng-model="updateFrequency" tooltip-placement="bottom" class="form-control"
                tooltip="How often to update the metrics.">
            <option value="1000">Every second</option>
            <option value="2000">Every 2 seconds</option>
            <option value="5000">Every 5 seconds</option>
            <option value="15000">Every 15 seconds</option>
        </select>

        <select ng-model="metricWindow" tooltip-placement="bottom" class="form-control"
                tooltip="How long to retain metric data.">
            <option value="60000">1 minute</option>
            <option value="120000">2 minutes</option>
            <option value="300000">5 minutes</option>
        </select>

        Filter:
        <input ng-model="viewFilter" type="text" size="40" class="form-control"
               placeholder="filter metrics..." id="packetFilter"
               tooltip-placement="bottom" tooltip="Search for metric...">
        </input>

        <button class="btn btn-primary" ng-click="selectAllFilteredItems(true)">Select Filtered</button>
        <button class="btn btn-primary" ng-click="selectAllFilteredItems(false)">Deselect Filtered</button>

</form>


text:
import { ObjectLiteral } from "../common/ObjectLiteral";
import { EntityMetadata } from "../metadata/EntityMetadata";
import { ColumnMetadata } from "../metadata/ColumnMetadata";
import { RelationMetadata } from "../metadata/RelationMetadata";
/**
 * Holds information about insert operation into junction table.
 */
export interface JunctionInsert {
    /**
     * Relation of the junction table.
     */
    relation: RelationMetadata;
    /**
     * Entities that needs to be "bind" to the subject.
     */
    junctionEntities: ObjectLiteral[];
}
/**
 * Holds information about remove operation from the junction table.
 */
export interface JunctionRemove {
    /**
     * Relation of the junction table.
     */
    relation: RelationMetadata;
    /**
     * Entity ids that needs to be removed from the junction table.
     */
    junctionRelationIds: any[];
}
/**
 * Holds information about relation update in some subject.
 */
export interface RelationUpdate {
    /**
     * Relation that needs to be updated.
     */
    relation: RelationMetadata;
    /**
     * New value that needs to be set into into new relation.
     */
    value: any;
}
/**
 * Subject is a subject of persistence.
 * It holds information about each entity that needs to be persisted:
 * - what entity should be persisted
 * - what is database representation of the persisted entity
 * - what entity metadata of the persisted entity
 * - what is allowed to with persisted entity (insert/update/remove)
 *
 * Having this collection of subjects we can perform database queries.
 */
export declare class Subject {
    /**
     * Persist entity (changed entity).
     */
    private _persistEntity?;
    /**
     * Database entity.
     */
    private _databaseEntity?;
    /**
     * Entity metadata of the subject entity.
     */
    readonly metadata: EntityMetadata;
    /**
     * Date when this entity is persisted.
     */
    readonly date: Date;
    /**
     * Indicates if this subject can be inserted into the database.
     * This means that this subject either is newly persisted, either can be inserted by cascades.
     */
    canBeInserted: boolean;
    /**
     * Indicates if this subject can be updated in the database.
     * This means that this subject either was persisted, either can be updated by cascades.
     */
    canBeUpdated: boolean;
    /**
     * Indicates if this subject MUST be removed from the database.
     * This means that this subject either was removed, either was removed by cascades.
     */
    mustBeRemoved: boolean;
    /**
     * Differentiated columns between persisted and database entities.
     */
    diffColumns: ColumnMetadata[];
    /**
     * Differentiated relations between persisted and database entities.
     */
    diffRelations: RelationMetadata[];
    /**
     * List of relations which need to be unset.
     * This is used to update relation from inverse side.
     */
    relationUpdates: RelationUpdate[];
    /**
     * Records that needs to be inserted into the junction tables of this subject.
     */
    junctionInserts: JunctionInsert[];
    /**
     * Records that needs to be removed from the junction tables of this subject.
     */
    junctionRemoves: JunctionRemove[];
    /**
     * When subject is newly persisted it may have a generated entity id.
     * In this case it should be written here.
     */
    generatedMap?: ObjectLiteral;
    /**
     * Generated id of the parent entity. Used in the class-table-inheritance.
     */
    parentGeneratedId?: any;
    /**
     * Used in newly persisted entities which are tree tables.
     */
    treeLevel?: number;
    constructor(metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral);
    /**
     * Gets entity sent to the persistence (e.g. changed entity).
     * Throws error if persisted entity was not set.
     */
    readonly entity: ObjectLiteral;
    /**
     * Checks if subject has a persisted entity.
     */
    readonly hasEntity: boolean;
    /**
     * Gets entity from the database (e.g. original entity).
     * THIS IS NOT RAW ENTITY DATA.
     * Throws error if database entity was not set.
     */
    /**
     * Sets entity from the database (e.g. original entity).
     * Once database entity set it calculates differentiated columns and relations
     * between persistent entity and database entity.
     */
    databaseEntity: ObjectLiteral;
    /**
     * Checks if subject has a database entity.
     */
    readonly hasDatabaseEntity: boolean;
    /**
     * Gets entity target from the entity metadata of this subject.
     */
    readonly entityTarget: Function | string;
    /**
     * Checks if this subject must be inserted into the database.
     * Subject can be inserted into the database if it is allowed to be inserted (explicitly persisted or by cascades)
     * and if it does not have database entity set.
     */
    readonly mustBeInserted: boolean;
    /**
     * Checks if this subject must be updated into the database.
     * Subject can be updated in the database if it is allowed to be updated (explicitly persisted or by cascades)
     * and if it does have differentiated columns or relations.
     */
    readonly mustBeUpdated: boolean;
    /**
     * Checks if this subject has relations to be updated.
     */
    readonly hasRelationUpdates: boolean;
    /**
     * Gets id of the persisted entity.
     * If entity is not set then it returns undefined.
     * If entity itself has an id then it simply returns it.
     * If entity does not have an id then it returns newly generated id.

    get getPersistedEntityIdMap(): any|undefined {
        if (!this.hasEntity)
            return undefined;

        const entityIdMap = this.metadata.getDatabaseEntityIdMap(this.entity);
        if (entityIdMap)
            return entityIdMap;

        if (this.newlyGeneratedId)
            return this.metadata.createSimpleDatabaseIdMap(this.newlyGeneratedId);

        return undefined;
    }*/
    /**
     * Validates this subject for errors.
     * Subject cannot be at the same time inserted and updated, removed and inserted, removed and updated.
     */
    validate(): void;
    /**
     * Performs entity re-computations.
     */
    recompute(): void;
    /**
     * Differentiate columns from the updated entity and entity stored in the database.
     */
    protected computeDiffColumns(): void;
    /**
     * Difference columns of the owning one-to-one and many-to-one columns.
     */
    protected computeDiffRelationalColumns(): void;
}


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

namespace Microsoft.Research.Wwt.TileGenerator
{
    /// <summary>
    /// Coordinate position values.
    /// </summary>
    public enum Position
    {
        /// <summary>
        /// Top left position
        /// </summary>
        TopLeft,

        /// <summary>
        /// Bottom right position
        /// </summary>
        BottomRight
    }

    /// <summary>
    /// Tags for progress bar status.
    /// </summary>
    public enum ProgressBarStatus
    {
        /// <summary>
        /// Status to represent processing state.
        /// </summary>
        Processing,

        /// <summary>
        /// Status to represent error state.
        /// </summary>
        Error,

        /// <summary>
        /// Status to represent success state.
        /// </summary>
        Success
    }

    /// <summary>
    /// Steps in pyramids generation.
    /// </summary>
    public enum PyramidGenerationSteps
    {
        /// <summary>
        /// Loading image.
        /// </summary>
        LoadingImage,

        /// <summary>
        /// Generating pyramids.
        /// </summary>
        PyramidGeneration,

        /// <summary>
        /// Generating plate file.
        /// </summary>
        PlateFileGeneration,

        /// <summary>
        /// Generating thumbnail.
        /// </summary>
        ThumbnailGeneration,

        /// <summary>
        /// Generating WTML file.
        /// </summary>
        WTMLGeneration,
    }

    /// <summary>
    /// Status of pyramid generation.
    /// </summary>
    public enum PyramidGenerationStatus
    {
        /// <summary>
        /// Steps has started.
        /// </summary>
        Started,

        /// <summary>
        /// Step has completed.
        /// </summary>
        Completed,
    }

    /// <summary>
    /// ProjectionTypes values.
    /// </summary>
    public enum InputProjections
    {
        /// <summary>
        /// EquiRectangular projection
        /// </summary>
        EquiRectangular,

        /// <summary>
        /// Mercator projection.
        /// </summary>
        Mercator,
    }
}


text:
using DataBridge.Tests.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

namespace DataBridge.Tests.Db
{
    [TestClass]
    public class ManipulationTests : TestsBase
    {
        [TestMethod]
        public void InsertPost()
        {
            var post = PostHydrador.GetSingle();

            Bridge.Insert(post);
        }

        [TestMethod]
        public void InsertPosts()
        {
            var posts = PostHydrador.GetList(1000);

            Bridge.InsertRange(posts);
        }

        [TestMethod]
        public void UpdatePost()
        {
            var post = PostHydrador.GetSingle();
            Bridge.Insert(post);

            post.Title = "Changed title!";

            Bridge.Update(post.Id, post);

            post = Bridge.Get(post.Id) as Post;
            Assert.AreEqual("Changed title!", post.Title);
        }

        [TestMethod]
        public void UpdatePostUpdatesIndexes()
        {
            var post = PostHydrador.GetSingle();
            Bridge.Insert(post);

            post.Title = "Changed title!";

            Bridge.Update(post.Id, post);

            var match = Bridge.Query<Post>()
                .Filter(new Eq(new Field("Title"), new Literal("Changed title!")))
                .Count();

            Assert.AreEqual(1, match);
        }

        [TestMethod]
        public void DeletePost()
        {
            var post = PostHydrador.GetSingle();
            Bridge.Insert(post);

            Bridge.Delete(post.Id);
        }

        [TestMethod]
        public void DeletePosts()
        {
            var posts = PostHydrador.GetList(1000);
            Bridge.InsertRange(posts);

            Bridge.DeleteRange(posts.Select(o => o.Id));
        }
    }
}


text:
[![Build Status](https://travis-ci.org/danielemoraschi/sitemap-common.png?branch=master)](https://travis-ci.org/danielemoraschi/sitemap-common)
[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/danielemoraschi/sitemap-common/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/danielemoraschi/sitemap-common/)

This package provides all of the components to crawl a website and build and write sitemaps file.

Example of console application using the library: [dmoraschi/sitemap-app](https://github.com/danielemoraschi/sitemap-app)

## Installation

Run the following command and provide the latest stable version (e.g v1.0.0):

```bash
composer require dmoraschi/sitemap-common
```

or add the following to your `composer.json` file :

```json
"dmoraschi/sitemap-common": "1.0.*"
``````

`SiteMapGenerator`
-----
**Basic usage**

``` php
$generator = new SiteMapGenerator(
    new FileWriter($outputFileName),
    new XmlTemplate()
);
```

Add a URL:
``` php
$generator->addUrl($url, $frequency, $priority);
```

Add a single `SiteMapUrl` object or array:
``` php
$siteMapUrl = new SiteMapUrl(
    new Url($url), $frequency, $priority
);

$generator->addSiteMapUrl($siteMapUrl);

$generator->addSiteMapUrls([
    $siteMapUrl, $siteMapUrl2
]);
```

Set the URLs of the sitemap via `SiteMapUrlCollection`:
``` php
$siteMapUrl = new SiteMapUrl(
    new Url($url), $frequency, $priority
);

$collection = new SiteMapUrlCollection([
    $siteMapUrl, $siteMapUrl2
]);

$generator->setCollection($collection);
```

Generate the sitemap:
``` php
$generator->execute();
```

`Crawler`
-----
**Basic usage**

``` php
$crawler = new Crawler(
    new Url($baseUrl),
    new RegexBasedLinkParser(),
    new HttpClient()
);
```

You can tell the `Crawler` **not to visit** certain url's by adding policies. Below the default policies provided by the library:
```php
$crawler->setPolicies([
    'host' => new SameHostPolicy($baseUrl),
    'url'  => new UniqueUrlPolicy(),
    'ext'  => new ValidExtensionPolicy(),
]);
// or
$crawler->setPolicy('host', new SameHostPolicy($baseUrl));
```
`SameHostPolicy`, `UniqueUrlPolicy`, `ValidExtensionPolicy` are provided with the library, you can define your own policies by implementing the interface `Policy`.

Calling the function `crawl` the object will start from the base url in the contructor and crawl all the web pages with the specified depth passed as a argument.
The function will return with the array of all unique visited `Url`'s:
```php
$urls = $crawler->crawl($deep);
```

You can also instruct the `Crawler` to collect custom data while visiting the web pages by adding `Collector`'s to the main object:
```php
$crawler->setCollectors([
    'images' => new ImageCollector()
]);
// or
$crawler->setCollector('images', new ImageCollector());
```
And then retrive the collected data:
```php
$crawler->crawl($deep);

$imageCollector = $crawler->getCollector('images');
$data = $imageCollector->getCollectedData();
```
`ImageCollector` is provided by the library, you can define your own collector by implementing the interface `Collector`.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.springframework.org/schema/beans
							http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="csrfFilter" class="org.springframework.security.web.csrf.CsrfFilter">
		<constructor-arg>
			<bean class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository"/>
		</constructor-arg>
	</bean>
	<bean id="requestDataValueProcessor" class="org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor"></bean>

</beans>


text:
<!doctype html>

		<title>directive</title>

		<hello></hello>


text:
<?php

  // HighRoller: include class files
  require_once('_assets/HighRoller/HighRoller.php');
  require_once('_assets/HighRoller/HighRollerSeriesData.php');
  require_once('_assets/HighRoller/HighRollerLineChart.php');

  // HighRoller: Line chart sample data
  $chartData = array(5324, 7534, 6234, 7234, 8251, 10324);

  // HighRoller: create and modify Line chart
  $linechart = new HighRollerLineChart();
  $linechart->chart->renderTo = 'linechart';
  $linechart->title->text = 'jQuery Line Chart';

  // HighRoller: create and add Series 1 data
  $series1 = new HighRollerSeriesData();
  $series1->addName('myData')->addData($chartData);

  // HighRoller: add series data to chart
  $linechart->addSeries($series1);

  // HighRoller: create and modify Line chart
  $linechart2 = new HighRollerLineChart();
  $linechart2->chart->renderTo = 'linechart2';
  $linechart2->title->text = 'MooTools Line Chart';

  // HighRoller: create and add Series 1 data
  $series1 = new HighRollerSeriesData();
  $series1->addName('myData')->addData($chartData);

  // HighRoller: add series data to chart
  $linechart2->addSeries($series1);

?>

  <title>HighRoller | Build How To</title>
  <link href='http://fonts.googleapis.com/css?family=Open+Sans&v1' rel='stylesheet' type='text/css'>
  <link href='_assets/jquery.snippet.css' rel='stylesheet' type='text/css'>
  <link href='_assets/highroller.css' rel='stylesheet' type='text/css'>

  <?php echo HighRoller::setHighChartsLocation("_assets/highcharts/highcharts.js");?>

HighRoller: Build and Test

  <?php require_once('nav.php');?>

How To Roll Your Own

HighRoller has a few handy developer features to help you create custom builds of HighRoller.

Developer Features:

Build Script - script for creating new releases.

Test Area - mini-site for verifying your latest build is stable.

Release Packaging - a .zip file is created for you.

How To Build

This guide assumes you have bash and already modified the contents of the /src directory to your needs and are ready to roll your own HighRoller.

In a bash shell, 'cd' over to the /tools dir

Execute the build script using a version argument (i.e. './build.sh 1.0.1').

Done. You just created a new .zip in the /releases folder and moved a copy of this build into the /test/_assets folder for use by this Test Suite

IMPORTANT NOTE: Using the same build version ('1.0.1') when you execute the build.sh script will overwrite all existing files in the /build and /releases folders.

How To Test

This guide assumes you have a web server running locally on your HighRoller build machine and that you already know how to setup a virtual host.

Name your web server vhost something simple like 'highroller' (or whatever you like).

Point your web server vhost DocumentRoot to HighRoller's /test folder.

Open up a browser and point it to 'highroller'.

Done. You can now use HighRoller's Test Suite to verify your custom build.

Caveats and Assumptions

You have an adventurous attitude about technology and are curious about how the world works.

Your environment is unix-based, has bash and you know at least some basic commands.

You have previously setup virtual hosts in your web server.

You are fluent in the PHP scripting language.

You have previously used jQuery and/or MooTools in web applications.

You have read Highcharts instructions for setting up HighCharts.

You have read Highcharts or are familiar with the Highcharts API.

You know how to test and debug web based applications.

You know how to ask for help if you need it (just ask!).

You do not have a gambling problem or intend to use HighRoller for wagering.

  <?php require_once('footer.php');?>


text:
class TaskMapper < ROM::Mapper
  relation :tasks
  register_as :entity

  model Minder::Task

  attribute :id
  attribute :description
  attribute :selected
  attribute :started
end


text:
public class IncludedOptional {

}


text:
Version 2.0.66 by Volodymyr Volynets

	<time class="change_log_date_commit" datetime="2019-10-04">2019-10-04</time>

Framework

	Enhancement #1253 (Misc changes due to UM Credentials.)

Repository / Git:
	Name: Numbers\Framework
	Title: Numbers Framework
	Version: 2.0.65
	Last Tag: 2.0.65
	User Name: Volodymyr Volynets
	User Email: volodymyr.volynets@gmail.com
Statistics:
	Addition: 35
	Deletion: 17
Modules:
	Numbers Framework (Numbers\Framework, 2.0.65)                                             |    35   17
		    2    1	 | Functions.php
		   16    5	 | Object/Collection.php
		   11   10	 | Object/Data/Domains.php
		    5    0	 | Object/Form/Base.php
		    1    1	 | Object/Form/Wrapper/Base.php


text:
'use strict';

var _classCallCheck3 = _interopRequireDefault(require('babel-runtime/helpers/classCallCheck'));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var EXISTENT = require('./RelayRecordState').EXISTENT,
    NONEXISTENT = require('./RelayRecordState').NONEXISTENT,
    UNKNOWN = require('./RelayRecordState').UNKNOWN;

/**
 * An implementation of the `MutableRecordSource` interface (defined in
 * `RelayStoreTypes`) that holds all records in memory.
 */

var RelayInMemoryRecordSource = function () {
  function RelayInMemoryRecordSource(records) {
    (0, _classCallCheck3['default'])(this, RelayInMemoryRecordSource);

    this._records = records || {};
  }

  RelayInMemoryRecordSource.prototype.clear = function clear() {
    this._records = {};
  };

  RelayInMemoryRecordSource.prototype['delete'] = function _delete(dataID) {
    this._records[dataID] = null;
  };

  RelayInMemoryRecordSource.prototype.get = function get(dataID) {
    return this._records[dataID];
  };

  RelayInMemoryRecordSource.prototype.getRecordIDs = function getRecordIDs() {
    return Object.keys(this._records);
  };

  RelayInMemoryRecordSource.prototype.getStatus = function getStatus(dataID) {
    if (!this._records.hasOwnProperty(dataID)) {
      return UNKNOWN;
    }
    return this._records[dataID] == null ? NONEXISTENT : EXISTENT;
  };

  RelayInMemoryRecordSource.prototype.has = function has(dataID) {
    return this._records.hasOwnProperty(dataID);
  };

  RelayInMemoryRecordSource.prototype.load = function load(dataID, callback) {
    callback(null, this.get(dataID));
  };

  RelayInMemoryRecordSource.prototype.remove = function remove(dataID) {
    delete this._records[dataID];
  };

  RelayInMemoryRecordSource.prototype.set = function set(dataID, record) {
    this._records[dataID] = record;
  };

  RelayInMemoryRecordSource.prototype.size = function size() {
    return Object.keys(this._records).length;
  };

  RelayInMemoryRecordSource.prototype.toJSON = function toJSON() {
    return this._records;
  };

  return RelayInMemoryRecordSource;
}();

module.exports = RelayInMemoryRecordSource;


text: autoreconf --force --install --verbose "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"


text:
namespace P01_1BillsPaymentSystem.Interfaces
{
    public interface IIPayBills
    {
        void Deposit(decimal amount);
        void Withdraw(decimal amount);
    }
}


text:
//
//  BRSlideMenuView.h
//  MyLiveProject
//
//  Created by 任波 on 17/2/9.
//  Copyright © 2017年 RENB. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef void(^BRSlideMenuBlock)(NSInteger tag);

@interface BRSlideMenuView : UIView
@property (nonatomic, copy) BRSlideMenuBlock slideMenuBlock;
/** 重写构造方法 */
- (instancetype)initWithFrame:(CGRect)frame andTitleArr:(NSArray *)titleArr;
/** 滑动菜单下划线方法(滑动scrollView时调用,保证scrollView和lineView联动) */
- (void)scrollLineView:(NSInteger)index;

@end


text:
package name.valery1707.megatel.sorm.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.BigInteger;

@Entity
@SuppressWarnings("unused")
public class BroBinary {
	@Id
	@NotNull
	private BigDecimal ts;

	@NotNull
	private String uid;

	@Column(name = "id_orig_h")
	@NotNull
	private String idOrigHost;
	@Column(name = "id_orig_h_ip")
	@NotNull
	private BigInteger idOrigIp;
	@Column(name = "id_orig_p")
	@NotNull
	private int idOrigPort;

	@Column(name = "id_resp_h")
	@NotNull
	private String idRespHost;
	@Column(name = "id_resp_h_ip")
	@NotNull
	private BigInteger idRespIp;
	@Column(name = "id_resp_p")
	@NotNull
	private int idRespPort;

	@NotNull
	private String protocol;

	private String amtTasksList;

	public BigDecimal getTs() {
		return ts;
	}

	public void setTs(BigDecimal ts) {
		this.ts = ts;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getIdOrigHost() {
		return idOrigHost;
	}

	public void setIdOrigHost(String idOrigHost) {
		this.idOrigHost = idOrigHost;
	}

	public BigInteger getIdOrigIp() {
		return idOrigIp;
	}

	public void setIdOrigIp(BigInteger idOrigIp) {
		this.idOrigIp = idOrigIp;
	}

	public int getIdOrigPort() {
		return idOrigPort;
	}

	public void setIdOrigPort(int idOrigPort) {
		this.idOrigPort = idOrigPort;
	}

	public String getIdRespHost() {
		return idRespHost;
	}

	public void setIdRespHost(String idRespHost) {
		this.idRespHost = idRespHost;
	}

	public BigInteger getIdRespIp() {
		return idRespIp;
	}

	public void setIdRespIp(BigInteger idRespIp) {
		this.idRespIp = idRespIp;
	}

	public int getIdRespPort() {
		return idRespPort;
	}

	public void setIdRespPort(int idRespPort) {
		this.idRespPort = idRespPort;
	}

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getAmtTasksList() {
		return amtTasksList;
	}

	public void setAmtTasksList(String amtTasksList) {
		this.amtTasksList = amtTasksList;
	}
}


text:
layout: page
title: General setup - Sinon.JS
breadcrumb: general-setup
---

We will be making fakes, spies and stubs. By default these are created in the _default sandbox_.
Be sure to `restore` this sandbox after each test.

For example, if you're using mocha you can place this in a test file at the root level:

```js
afterEach(() => {
  // Restore the default sandbox here
  sinon.restore();
});
```

On Mocha v8.0.0 or newer you can now add a root hook to your entire test suite, which will execute before/after every test:

```js
// tests/hooks.js

// Restores the default sandbox after every test
exports.mochaHooks = {
  afterEach() {
    sinon.restore();
  },
};
```

This root file needs to be loaded using the `--require` option:

```shell
mocha --require tests/hooks.js
```

Or in Jasmine you should place it in each describe:

```js
describe("My test suite", () => {
  afterEach(() => {
    // Restore the default sandbox here
    sinon.restore();
  });
});
```

Forgetting to restore your sandbox results in a memory leak.

For more advanced setups using multiple sandboxes, please see [sandbox](../sandbox)


text:
require "test_helper"

#  Test MO extensions to Ruby Fixnum class
class FixnumExtensionsTest < UnitTestCase
  def test_convert_decimal_to_base62
    assert_equal("0", 0.alphabetize)
    assert_equal("g", 42.alphabetize)
    assert_equal("8M0kX", 123_456_789.alphabetize)
  end

  def test_alphabetize_decimal_to_hex
    assert_equal("0", 0.alphabetize("0123456789ABCDEF"))
    assert_equal("2A", 42.alphabetize("0123456789ABCDEF"))
    assert_equal("75BCD15", 123_456_789.alphabetize("0123456789ABCDEF"))
  end
end


text:
<?php

namespace App\Database\Models;

class Plugin extends \App\Common\Models\Database\Plugin
{
    /**
     * 检查插件是否存在
     *
     * @param string $name
     * @return bool True/False
     */
    public function checkPluginNameExist($name)
    {
        $check = $this->findOne(array(
            'name' => $name
        ));
        if (!empty($check)) {
            return true;
        }
        return false;
    }
}


text:
import React from 'react';
import { Link } from 'react-router-dom';

export default ({ bundler, compiler, framework }: HelloProps) => (

Hello from {framework}, running on {compiler} and bundled with {bundler}!

    <Link to={`/page2`}>Page 2</Link>

);


text:
var test = require('tape')
var hyperkv = require('../')
var memdb = require('memdb')
var hyperlog = require('hyperlog')

test('batch', function (t) {
  t.plan(5)
  var kv = hyperkv({
    log: hyperlog(memdb(), { valueEncoding: 'json' }),
    db: memdb()
  })
  kv.batch([
    { type: 'put', key: 'A', value: 123 },
    { type: 'put', key: 'B', value: 456 }
  ], onbatch)

  function onbatch (err, nodes) {
    t.error(err)
    kv.get('A', function (err, values) {
      t.error(err)
      var expected = {}
      expected[nodes[0].key] = { value: 123 }
      t.deepEqual(values, expected, 'expected values for key A')
    })
    kv.get('B', function (err, values) {
      t.error(err)
      var expected = {}
      expected[nodes[1].key] = { value: 456 }
      t.deepEqual(values, expected, 'expected values for key B')
    })
  }
})


text:
    Global = {}

	Global.storage=OLA.storage.."/BabyGo/"
	Log:d("Global","Global.storage="..Global.storage)

    Global.version=0;
	Global.run_mile=0;
	Global.walk_mile=0;

 function Global.getItemText(index)
	local text="";
	if index=="1" or index==1 then text="母乳" end
	if index=="2" or index==2 then text="奶粉" end
	if index=="3" or index==3 then text="水" end
	if index=="4" or index==4 then text="药" end
	if index=="5" or index==5 then text="大便" end
	if index=="6" or index==6 then text="小便" end
	if index=="7" or index==7 then text="体重" end
	if index=="8" or index==8 then text="身高" end
	return text
end

    function Global.loadProperties()
	local fin = fis:open(Global.storage.."Health.properties")
	Log:d("test Global","loadProperties")
         if fin:exists() then
                Global.run_mile=fin:readInt()
                Global.walk_mile=fin:readInt()
	      fin:close()
	    else
                Global.saveProperties();
        end
    end
    function Global.saveProperties()
	local fout = fos:open(Global.storage.."Health.properties")
       fout:writeInt(Global.run_mile);
        fout:writeInt(Global.walk_mile);
        fout:close()
    end
Log:d("test Global","0")
    Global.loadProperties()
Log:d("test Global","Global.loadProperties executed")

Log:d("test Global","Global.currentBookFileName="..Global.currentBookFileName)


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

namespace WebArticleURLToText
{
    public class NewsPage
    {
        //Dictionary comtainning information partating to the way we read a HTML site/article for a specific newssite
        private static Dictionary<string, Tuple<string, string>> websites = new Dictionary<string, Tuple<string, string>>();
        //HTMLDocument: Provides top-level programmatic access to a HTML document hosted by the WebBrowser control.
        private HtmlDocument doc;
        private string domain;
        public string Headline { get; private set; }
        public List<string> BodyText = new List<string>();

        public NewsPage(string webaddress)
        {
            InitializeWebsite();
            doc = GetWebsite(webaddress);
            GetArticleHead();
            GetArticleBody();
        }

        //Method that downloads the HTMLcode from website.
        private HtmlDocument GetWebsite(string webaddress)
        {
            HtmlDocument doc1 = new HtmlDocument();
            //Intanciates a WebClient and specifies the encoding type to UTF8 to prevent weird characters
            WebClient client = new WebClient { Encoding = System.Text.Encoding.UTF8 };
            //Fetches Html document of the webite
            string websiteString = client.DownloadString(webaddress);
            //Loads the websiteString to a HtmlDocument type
            doc1.LoadHtml(websiteString);
            //Gets the host name of a website eks. "http:/www.123.com/1341341 --> www.123.com
            domain = new Uri(webaddress).Host;

            return doc1;

        }

        //Methode that gets article nods - (A node is any piece of individual content)
        private HtmlNode GetArticleNode()
        {
            //Gets the Xpath from the dictionary
            //A turple contains a set of values in this case 2
            Tuple<string, string> vals = websites[domain];
            //GetElementById: Retrieves a single HtmlElement using the element's ID attribute as a search key.
            //SelectNodes: Return a list of nodes matching the Xpath expression, but we only want the nodes at the end of the path -> Last();
            return doc.GetElementbyId(vals.Item1).SelectNodes(vals.Item2).Last();

        }

        //Methode: Gets the article title.
        private void GetArticleHead()
        {
            //We have one node which is converted to a list of childnodes wherein
            //we search nodes classified with h1. h1: Headline 1, the biggest headline in Htmlcode
            foreach (HtmlNode node in GetArticleNode().SelectNodes("//h1"))
            {
                //Gets the InnerText inside Html-tags
Innertext

                Headline = node.InnerText + "\n";
            }
        }

        //Methode: Gets the article content.
        private void GetArticleBody()
        {
            //We have one node which is converted to a list of childnodes wherein
            //we search nodes classified with p. p: paragraph, for regular text in Htmlcode
            foreach (HtmlNode node in GetArticleNode().SelectNodes("//p"))
            {
                //If the node is a p class node, the node is ignored
                if (node.ChildAttributes("class").Count() != 0)
                {
                    continue;
                }
                //Gets the InnerText inside Html-tags
Innertext
 and adds it to a list
                BodyText.Add(node.InnerText);
            }
        }

        //Initiaizes preinserted newssites
        private void InitializeWebsite()
        {
            //Dictionary(Key: Webpage hostname, Value: Turple(Xpath))
            //Xpath: Contains the id/pointer for a newsspecific overall
 and a path to where the body text is located
            websites.Add("www.bbc.com", Tuple.Create("page", "//div[2]/div[2]/div/div[1]/div[1]"));
            websites.Add("www.theguardian.com", Tuple.Create("article", "//div[4]/div/div[1]/div[5]"));
            websites.Add("news.sky.com", Tuple.Create("", "//html/body/div[1]/div[2]"));
            websites.Add("www.washingtonpost.com", Tuple.Create("article-body", "//article"));
            websites.Add("www.cbsnews.com", Tuple.Create("article-entry", "//div[2]"));
            //websites.Add("www.huffingtonpost.com", Tuple.Create("us_jhhcvkh6546", "//div"));
            //websites.Add("tytnetwork.com", Tuple.Create("post-469222", "//div[2]/div"));
            //websites.Add("abcnews.go.com", Tuple.Create("article-feed", "//article[1]/div"));
            //websites.Add("edition.cnn.com", Tuple.Create("body-text", "//div/div[1]"));
            //Fake
            websites.Add("abcnews.com.co", Tuple.Create("", "//html/body/div"));
            //websites.Add("www.breitbart.com", Tuple.Create("post-6594146", "//div"));
            //websites.Add("www.cnn.com.de", Tuple.Create("post-705", "//div[3]"));
        }
    }
}


text:
/**
 * Created by 10177553 on 2016/12/13.
 */
"use strict";
/**
 * 第一个控件的demo
 */
var select_1 = require("./select/select");
exports.Select = select_1.default;
//# sourceMappingURL=index.js.map


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

public class CellBehaviour : MonoBehaviour
{
    private GlobalSettings _gs;
    private Color _nextColor;
    private int generation = 0;

	// Use this for initialization
	void Start ()
    {
        _gs = GlobalSettings.Instance;
    }

	// Update is called once per frame
	void Update ()
    {
        if (_gs.getCurrentGeneration() > generation)
        {
            generation++;
            StartCoroutine("CrossFade");
        }
	}

    IEnumerator CrossFade()
    {
        Color current = GetComponent<SpriteRenderer>().color;

        int n = -1;
        _gs.currentStates.TryGetValue(new Vector2(transform.position.x, transform.position.y), out n);
        Color next = _gs.Rules.getColorValue(n);

        if (current.Equals(next)) yield break;

        for (float t = 0f; t < 1.0f; t += Time.deltaTime / 1.0f)
        {
            Color nc = new Color(
                Mathf.Lerp(current.r, next.r, t),
                Mathf.Lerp(current.g, next.g, t),
                Mathf.Lerp(current.b, next.b, t),
                Mathf.Lerp(current.a, next.a, t)
            );

            GetComponent<SpriteRenderer>().color = nc;
            yield return null;
        }
    }
}