Data now imports.

Data now imports.

--- TeamTracker/App_Code/FileImport.cs
+++ TeamTracker/App_Code/FileImport.cs
@@ -88,7 +88,7 @@

     string GetVersion( List<string> lines )
     {
-      string version = lines.First( x => x.ToLower().Contains( "version=" ) );
+      string version = lines.FirstOrDefault( x => x.ToLower().Contains( "version=" ) );

       if( version == null )
       {
@@ -371,9 +371,16 @@
           Database.ExecSql( "DBCC CHECKIDENT ( '[People]', RESEED, 0 )" );
         }

+        // We need the status types.
+        Dictionary<int, Status> statusTypes = Status.Load();
+
         // Interate through data.
+        Dictionary<int, Person> people = new Dictionary<int, Person>();
+
+        int rowCount;
         int itemCount = 0;
         int importedPeopleCount = 0;
+        int importedContactCount = 0;

         for( lineIndex++; lineIndex < lines.Count; lineIndex++ )
         {
@@ -397,31 +404,100 @@
           }

           string personName = data[ 0 ];
+          string statusName = data[ 1 ];
+          string address = data[ 2 ];
+
+          // Person already in DB?
+          int personId = -1;
+
+          Person person = people.Values.FirstOrDefault( x => x.Name == personName );
+
+          if( person != null )
+          {
+            personId = person.Id;
+          }

           // Add person to People table.
-          int rowCount =
+          if( personId < 0 )
+          {
+            rowCount =
+              Database.ExecSql(
+                string.Format(
+                  "INSERT INTO People ( name ) " +
+                  "VALUES ( '{0}' )",
+                  personName ) );
+
+            if( rowCount == 0 )
+            {
+              Log(
+                string.Format(
+                  "Failed to add item {0} to the People table.",
+                  itemCount ) );
+            }
+            else
+            {
+              importedPeopleCount++;
+            }
+
+            // Reload the People.
+            people = Person.Load( statusTypes );
+
+            person = people.Values.FirstOrDefault( x => x.Name == personName );
+
+            if( person != null )
+            {
+              personId = person.Id;
+            }
+            else
+            {
+              Log(
+                string.Format(
+                  "Failed to find person '{0}' that was just added.",
+                  personName ) );
+
+              continue;
+            }
+          }
+
+          // Add person's contact.
+          Status status = statusTypes.Values.FirstOrDefault( x => x.Name == statusName );
+
+          if( status == null )
+          {
+            Log(
+              string.Format(
+                "Failed to find StatusType with name '{0}' for person '{1}'.",
+                statusName,
+                personName ) );
+
+            continue;
+          }
+
+          rowCount =
             Database.ExecSql(
               string.Format(
-                "INSERT INTO People ( name ) " +
-                "VALUES ( '{0}' )",
+                "INSERT INTO PeopleContact ( peopleId, statusTypeId, address )" +
+                  "VALUES ( {0}, {1}, '{2}' )",
+                personId,
+                status.Id,
+                address ) );
+
+          if( rowCount == 0 )
+          {
+            Log(
+              string.Format(
+                "Failed to import contact '{0}' for person '{0}'.",
+                statusName,
                 personName ) );
-
-          if( rowCount == 0 )
-          {
-            Log(
-              string.Format(
-                "Failed to add item {0} to the People table.",
-                itemCount ) );
           }
           else
           {
-            importedPeopleCount++;
-          }
-
-          // Add
+            importedContactCount++;
+          }
         }

         Log( string.Format( "Imported {0} people.", importedPeopleCount ) );
+        Log( string.Format( "Imported {0} contacts.", importedContactCount ) );
       }
       catch( Exception ex )
       {


SerializationHelpersTests - minor improvements for thread safety tests

--- Tests/SerializationHelpersTests.cs
+++ Tests/SerializationHelpersTests.cs
@@ -249,7 +249,7 @@
 			private void AssertObjEqial(object obj)
 			{
 				if(!sampleObject.Equals((STO)obj))
-					throw new Exception("!sampleObject.Equals<STO>((STO)obj)");
+					throw new Exception("!sampleObject.Equals((STO)obj)");
 			}

 			public void Worker()
@@ -312,14 +312,16 @@
 			//start runners
 			for(int i=0;i<runnerCount;++i)
 			{
-				Assert.AreNotEqual(RunnerState.Failed,runners[i].State);
+				if(runners[i].State == RunnerState.Failed)
+					throw runners[i].Ex;
 				Assert.AreEqual(RunnerState.Init,runners[i].State);
 				runners[i].Start();
 			}
 			//check runners is started
 			for(int i=0;i<runnerCount;++i)
 			{
-				Assert.AreNotEqual(RunnerState.Failed,runners[i].State);
+				if(runners[i].State == RunnerState.Failed)
+					throw runners[i].Ex;
 				while(runners[i].State == RunnerState.Init)
 					Thread.Sleep(1);
 				Assert.AreEqual(RunnerState.Started,runners[i].State);
@@ -327,6 +329,8 @@
 			//enable counters
 			for(int i=0;i<runnerCount;++i)
 			{
+				if(runners[i].State == RunnerState.Failed)
+					throw runners[i].Ex;
 				Assert.AreEqual(RunnerState.Started,runners[i].State);
 				runners[i].StartCounter();
 			}


Visitor: function that returns the error message when trying to access sequence element

--- VineScript/Compiler/VineVisitor.cs
+++ VineScript/Compiler/VineVisitor.cs
@@ -717,6 +717,24 @@
             return vineDict;
         }

+        /// <summary>
+        /// Error message when trying to access a sequence element.
+        /// </summary>
+        /// <param name="varname">The variable's name in which the lookup takes place.
+        /// This can be empty because some variable are anonymous, for e.g. when
+        /// trying to access an element of a function return {{ foo()[0] }}.</param>
+        /// <returns>Formatted error message.</returns>
+        private string SequenceTypeError(string varname)
+        {
+            string str = "";
+            if (!string.IsNullOrWhiteSpace(varname)) {
+                str = " '" + varname + "'";
+            }
+            return "Can't access element with [] because the sequence"
+                    + str + " is neither an array nor a dictionnary"
+                    + " nor a string.";
+        }
+
         private VineVar GetValueInSequence(VineVar startingVar,
             VineParser.SequenceAccessContext[] sequences)
         {
@@ -745,9 +763,7 @@
                 value = lastSequence[lastIndex.AsString];
             } else {
                 throw new VineRuntimeException(
-                    "Can't access element with [] because the variable '"
-                    + lastSequence.name + "' is neither an array nor a dictionnary"
-                    + " nor a string",
+                    SequenceTypeError(lastSequence.name),
                     sequences[0]
                 );
             }
@@ -800,9 +816,7 @@
             else
             {
                 throw new VineRuntimeException(
-                    "Can't access element with [] because the variable '"
-                    + lastSequence.name + "' is neither an array nor a dictionnary"
-                    + " nor a string",
+                    SequenceTypeError(lastSequence.name),
                     sequences[0]
                 );
             }
@@ -864,9 +878,7 @@
                     lastSequence = lastSequence[indexExpr.AsString];
                 } else {
                     throw new VineRuntimeException(
-                        "Can't access element with [] because the variable '"
-                        + lastSequence.name + "' is neither an array nor a dictionnary "
-                        + " nor a string",
+                        SequenceTypeError(lastSequence.name),
                         sequences[0]
                     );
                 }


KATA - string calculator - Let any number of numbers to add

--- kata/tdd/c_sharp/StringCalculatorKata/StringCalculatorKata/Calculator.cs
+++ kata/tdd/c_sharp/StringCalculatorKata/StringCalculatorKata/Calculator.cs
@@ -6,8 +6,6 @@
     {
         public static int Add(string numbers)
         {
-            if (numbers.Split(',').Length > 3)
-                return 0;
             return string.IsNullOrEmpty(numbers) ? 0 : numbers.Split(',').Sum(num => int.Parse(num));
         }
     }


mapminmax

mapminmax

--- WAProject/Actors/MapMinMaxActor.cs
+++ WAProject/Actors/MapMinMaxActor.cs
@@ -26,7 +26,7 @@
 						this._maxMapped [i] = aValue;

 					if (this._minMapped [i] != null) {
-						if (aValue < (int)this._minMapped [i])
+						if (aValue < (int)this._minMapped [i]	)
 							this._minMapped [i] = aValue;
 					} else
 						this._minMapped [i] = Convert.ToInt32 (msg.Row [i]);


Separate address selection logic from registration logic

--- WalletWasabi/Services/CcjClient.cs
+++ WalletWasabi/Services/CcjClient.cs
@@ -454,114 +454,7 @@
 				// If there are no suitable coins to register return.
 				if (!registrableCoins.Any()) return;

-				BitcoinAddress changeAddress = null;
-				var activeOutputAddresses = new List<BitcoinAddress>();
-
-				string changeLabel = "ZeroLink Change";
-				string activeLabel = "ZeroLink Mixed Coin";
-
-				IEnumerable<HdPubKey> allChangeKeys = KeyManager.GetKeys(x => x.KeyState != KeyState.Used && x.Label == changeLabel);
-				HdPubKey changeKey = null;
-
-				KeyManager.AssertLockedInternalKeysIndexed(14);
-				IEnumerable<HdPubKey> internalNotCachedLockedKeys = KeyManager.GetKeys(KeyState.Locked, isInternal: true).Except(AccessCache.Keys);
-
-				if (allChangeKeys.Count() >= 7 || !internalNotCachedLockedKeys.Any()) // Then don't generate new keys, because it'd bloat the wallet.
-				{
-					// Find the first one that we did not try to register in the current session.
-					changeKey = allChangeKeys.FirstOrDefault(x => !AccessCache.ContainsKey(x));
-					// If there is no such a key, then use the oldest.
-					if (changeKey == default)
-					{
-						changeKey = AccessCache.Where(x => allChangeKeys.Contains(x.Key)).OrderBy(x => x.Value).First().Key;
-					}
-					changeKey.SetLabel(changeLabel);
-					changeKey.SetKeyState(KeyState.Locked);
-				}
-				else
-				{
-					changeKey = internalNotCachedLockedKeys.RandomElement();
-					changeKey.SetLabel(changeLabel);
-				}
-				changeAddress = changeKey.GetP2wpkhAddress(Network);
-				AccessCache.AddOrReplace(changeKey, DateTimeOffset.UtcNow);
-
-				IEnumerable<HdPubKey> allActiveKeys = KeyManager.GetKeys(x => x.KeyState != KeyState.Used && x.Label == activeLabel);
-				List<HdPubKey> activeKeys = new List<HdPubKey>();
-
-				KeyManager.AssertLockedInternalKeysIndexed(14);
-
-				internalNotCachedLockedKeys = KeyManager.GetKeys(KeyState.Locked, isInternal: true).Except(AccessCache.Keys);
-
-				Money inputSum = Money.Zero;
-				foreach (TxoRef coinReference in registrableCoins)
-				{
-					SmartCoin coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
-					inputSum += coin.Amount;
-				}
-
-				int maximumMixingLevelCount = 1;
-
-				var denominations = new List<Money>
-					{
-						inputRegistrableRound.State.Denomination
-					};
-
-				for (int i = 1; i < inputRegistrableRound.State.SchnorrPubKeys.Count(); i++)
-				{
-					Money denom = denominations.Last() * 2;
-					denominations.Add(denom);
-					if (inputSum > denom)
-					{
-						maximumMixingLevelCount = i + 1;
-					}
-				}
-
-				if (allActiveKeys.Count() >= 7 || !internalNotCachedLockedKeys.Any()) // Then don't generate new keys, because it'd bloat the wallet.
-				{
-					// Find the first one that we did not try to register in the current session.
-					foreach (var ac in allActiveKeys.Where(x => !AccessCache.ContainsKey(x)))
-					{
-						if (activeKeys.Count >= maximumMixingLevelCount)
-						{
-							break;
-						}
-						activeKeys.Add(ac);
-					}
-					// If there is no such a key, then use the oldest, but make sure it's not the same as the change.
-					if (activeKeys.Count < maximumMixingLevelCount)
-					{
-						foreach (var ac in AccessCache.Where(x => allActiveKeys.Contains(x.Key) && changeAddress != x.Key.GetP2wpkhAddress(Network)).OrderBy(x => x.Value).Select(x => x.Key))
-						{
-							if (activeKeys.Count >= maximumMixingLevelCount)
-							{
-								break;
-							}
-							activeKeys.Add(ac);
-						}
-					}
-				}
-				else
-				{
-					foreach (var ac in internalNotCachedLockedKeys.Where(x => changeAddress != x.GetP2wpkhAddress(Network)))
-					{
-						if (activeKeys.Count >= maximumMixingLevelCount)
-						{
-							break;
-						}
-						activeKeys.Add(ac);
-					}
-				}
-
-				foreach (HdPubKey ac in activeKeys)
-				{
-					ac.SetLabel(activeLabel);
-					ac.SetKeyState(KeyState.Locked);
-					activeOutputAddresses.Add(ac.GetP2wpkhAddress(Network));
-					AccessCache.AddOrReplace(ac, DateTimeOffset.UtcNow);
-				}
-
-				KeyManager.ToFile();
+				(BitcoinAddress change, IEnumerable<BitcoinAddress> active) outputAddresses = GetOutputAddressesToRegister(inputRegistrableRound, registrableCoins);

 				SchnorrPubKey[] schnorrPubKeys = inputRegistrableRound.State.SchnorrPubKeys.ToArray();
 				List<Requester> requesters = new List<Requester>();
@@ -571,8 +464,8 @@
 				var registeredAddresses = new List<BitcoinAddress>();
 				for (int i = 0; i < schnorrPubKeys.Length; i++)
 				{
-					if (activeOutputAddresses.Count <= i) break;
-					BitcoinAddress address = activeOutputAddresses.ElementAt(i);
+					if (outputAddresses.active.Count() <= i) break;
+					BitcoinAddress address = outputAddresses.active.ElementAt(i);

 					SchnorrPubKey schnorrPubKey = schnorrPubKeys[i];
 					var outputScriptHash = new uint256(Hashes.SHA256(address.ScriptPubKey.ToBytes()));
@@ -604,7 +497,7 @@
 				AliceClient aliceClient = null;
 				try
 				{
-					aliceClient = await AliceClient.CreateNewAsync(Network, changeAddress, blindedOutputScriptHashes, inputProofs, CcjHostUri, TorSocks5EndPoint);
+					aliceClient = await AliceClient.CreateNewAsync(Network, outputAddresses.change, blindedOutputScriptHashes, inputProofs, CcjHostUri, TorSocks5EndPoint);
 				}
 				catch (HttpRequestException ex) when (ex.Message.Contains("Input is banned", StringComparison.InvariantCultureIgnoreCase))
 				{
@@ -653,7 +546,7 @@
 					State.RemoveCoinFromWaitingList(coin);
 				}

-				var registration = new ClientRoundRegistration(aliceClient, coinsRegistered, changeAddress);
+				var registration = new ClientRoundRegistration(aliceClient, coinsRegistered, outputAddresses.change);

 				CcjClientRound roundRegistered = State.GetSingleOrDefaultRound(aliceClient.RoundId);
 				if (roundRegistered is null)
@@ -669,6 +562,119 @@
 			{
 				Logger.LogError<CcjClient>(ex);
 			}
+		}
+
+		private (BitcoinAddress change, IEnumerable<BitcoinAddress> active) GetOutputAddressesToRegister(CcjClientRound inputRegistrableRound, List<TxoRef> registrableCoins)
+		{
+			BitcoinAddress changeOutputAddress = null;
+			var activeOutputAddresses = new List<BitcoinAddress>();
+			string changeLabel = "ZeroLink Change";
+			string activeLabel = "ZeroLink Mixed Coin";
+
+			IEnumerable<HdPubKey> allChangeKeys = KeyManager.GetKeys(x => x.KeyState != KeyState.Used && x.Label == changeLabel);
+			HdPubKey changeKey = null;
+
+			KeyManager.AssertLockedInternalKeysIndexed(14);
+			IEnumerable<HdPubKey> internalNotCachedLockedKeys = KeyManager.GetKeys(KeyState.Locked, isInternal: true).Except(AccessCache.Keys);
+
+			if (allChangeKeys.Count() >= 7 || !internalNotCachedLockedKeys.Any()) // Then don't generate new keys, because it'd bloat the wallet.
+			{
+				// Find the first one that we did not try to register in the current session.
+				changeKey = allChangeKeys.FirstOrDefault(x => !AccessCache.ContainsKey(x));
+				// If there is no such a key, then use the oldest.
+				if (changeKey == default)
+				{
+					changeKey = AccessCache.Where(x => allChangeKeys.Contains(x.Key)).OrderBy(x => x.Value).First().Key;
+				}
+				changeKey.SetLabel(changeLabel);
+				changeKey.SetKeyState(KeyState.Locked);
+			}
+			else
+			{
+				changeKey = internalNotCachedLockedKeys.RandomElement();
+				changeKey.SetLabel(changeLabel);
+			}
+			changeOutputAddress = changeKey.GetP2wpkhAddress(Network);
+			AccessCache.AddOrReplace(changeKey, DateTimeOffset.UtcNow);
+
+			IEnumerable<HdPubKey> allActiveKeys = KeyManager.GetKeys(x => x.KeyState != KeyState.Used && x.Label == activeLabel);
+			List<HdPubKey> activeKeys = new List<HdPubKey>();
+
+			KeyManager.AssertLockedInternalKeysIndexed(14);
+
+			internalNotCachedLockedKeys = KeyManager.GetKeys(KeyState.Locked, isInternal: true).Except(AccessCache.Keys);
+
+			Money inputSum = Money.Zero;
+			foreach (TxoRef coinReference in registrableCoins)
+			{
+				SmartCoin coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
+				inputSum += coin.Amount;
+			}
+
+			int maximumMixingLevelCount = 1;
+
+			var denominations = new List<Money>
+					{
+						inputRegistrableRound.State.Denomination
+					};
+
+			for (int i = 1; i < inputRegistrableRound.State.SchnorrPubKeys.Count(); i++)
+			{
+				Money denom = denominations.Last() * 2;
+				denominations.Add(denom);
+				if (inputSum > denom)
+				{
+					maximumMixingLevelCount = i + 1;
+				}
+			}
+
+			if (allActiveKeys.Count() >= 7 || !internalNotCachedLockedKeys.Any()) // Then don't generate new keys, because it'd bloat the wallet.
+			{
+				// Find the first one that we did not try to register in the current session.
+				foreach (var ac in allActiveKeys.Where(x => !AccessCache.ContainsKey(x)))
+				{
+					if (activeKeys.Count >= maximumMixingLevelCount)
+					{
+						break;
+					}
+					activeKeys.Add(ac);
+				}
+				// If there is no such a key, then use the oldest, but make sure it's not the same as the change.
+				if (activeKeys.Count < maximumMixingLevelCount)
+				{
+					foreach (var ac in AccessCache.Where(x => allActiveKeys.Contains(x.Key) && changeOutputAddress != x.Key.GetP2wpkhAddress(Network)).OrderBy(x => x.Value).Select(x => x.Key))
+					{
+						if (activeKeys.Count >= maximumMixingLevelCount)
+						{
+							break;
+						}
+						activeKeys.Add(ac);
+					}
+				}
+			}
+			else
+			{
+				foreach (var ac in internalNotCachedLockedKeys.Where(x => changeOutputAddress != x.GetP2wpkhAddress(Network)))
+				{
+					if (activeKeys.Count >= maximumMixingLevelCount)
+					{
+						break;
+					}
+					activeKeys.Add(ac);
+				}
+			}
+
+			foreach (HdPubKey ac in activeKeys)
+			{
+				ac.SetLabel(activeLabel);
+				ac.SetKeyState(KeyState.Locked);
+				activeOutputAddresses.Add(ac.GetP2wpkhAddress(Network));
+				AccessCache.AddOrReplace(ac, DateTimeOffset.UtcNow);
+			}
+
+			KeyManager.ToFile();
+
+			return (changeOutputAddress, activeOutputAddresses);
 		}

 		public async Task QueueCoinsToMixAsync(params SmartCoin[] coins)


Remove redundant logging

Remove redundant logging

--- WalletWasabi/Services/CcjClient.cs
+++ WalletWasabi/Services/CcjClient.cs
@@ -265,21 +265,7 @@
 						Transaction unsignedCoinJoin = await ongoingRound.AliceClient.GetUnsignedCoinJoinAsync();
 						Dictionary<int, WitScript> myDic = SignCoinJoin(ongoingRound, unsignedCoinJoin);

-						try
-						{
-							await ongoingRound.AliceClient.PostSignaturesAsync(myDic);
-						}
-						catch (HttpRequestException)
-						{
-							var toLog = $"{nameof(unsignedCoinJoin)} hex: {unsignedCoinJoin.ToHex()}\n";
-							foreach (var elem in myDic)
-							{
-								toLog += $"\tInput Index: {elem.Key}\t Signature: {elem.Value.ToString()}\n";
-							}
-							Logger.LogWarning<CcjClient>(toLog);
-
-							throw;
-						}
+						await ongoingRound.AliceClient.PostSignaturesAsync(myDic);
 						ongoingRound.Signed = true;
 					}
 				}


Correct possible rounding error

Correct possible rounding error

resolves https://github.com/zkSNACKs/WalletWasabi/issues/1119

--- WalletWasabi/Services/CcjClient.cs
+++ WalletWasabi/Services/CcjClient.cs
@@ -350,7 +350,7 @@
 				minAmountBack -= minimumChangeAmount; // Minus coordinator protections (so it won't create bad coinjoins.)
 			}

-			if (amountBack < minAmountBack)
+			if (amountBack < minAmountBack && !amountBack.Almost(minAmountBack, new Money(10000))) // I catched an issue here, probably rounding. 1000 dust should be enough to catch it, but let's do 10000, why not.
 			{
 				throw new NotSupportedException("Coordinator did not add enough value to our outputs in the coinjoin.");
 			}


Fix newly introduced null reference exception caught by unit tests.

--- Website/DataServices/V2Feed.svc.cs
+++ Website/DataServices/V2Feed.svc.cs
@@ -70,7 +70,10 @@
             // Workaround https://github.com/NuGet/NuGetGallery/issues/674 for NuGet 2.1 client. Can probably eventually be retired (when nobody uses 2.1 anymore...)
             // Note - it was URI un-escaping converting + to ' ', undoing that is actually a pretty conservative substitution because
             // space characters are never acepted as valid by VersionUtility.ParseFrameworkName.
-            targetFrameworks = targetFrameworks.Replace(' ', '+');
+            if (!string.IsNullOrEmpty(targetFrameworks))
+            {
+                targetFrameworks = targetFrameworks.Replace(' ', '+');
+            }

             var idValues = packageIds.Trim().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
             var versionValues = versions.Trim().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);


adding renamed file that was weirdly ignored


CP-15407: Update the function that calculates pool license

Cherry-picked from cream-indigo:
CA-190393: Update the function that calculates pool license
- use Host.GetEdition function, as this function interprets xapi license string "basic" as Free license in XenCenter

Signed-off-by: Mihaela Stoica <be95049f8e30d921fc7e2579c00c48bd84c40606@citrix.com>

--- XenModel/XenAPI-Extensions/Pool.cs
+++ XenModel/XenAPI-Extensions/Pool.cs
@@ -117,7 +117,7 @@
                 foreach (Host.Edition edition in Enum.GetValues(typeof(Host.Edition)))
                 {
                     Host.Edition edition1 = edition;
-                    Host host = hosts.Find(h => h.edition == Host.GetEditionText(edition1));
+                    Host host = hosts.Find(h => Host.GetEdition(h.edition) == edition1);

                     if (host != null)
                     {


Rivers looking good?

Rivers looking good?

I got it where there are no strands of white streaking across the
screen, and rivers are visible, blank but visible

--- mst-boredom-remover/mst-boredom-remover/Generator.cs
+++ mst-boredom-remover/mst-boredom-remover/Generator.cs
@@ -9,9 +9,9 @@
     {
         public struct BiomeInfo
         {
-            public char Type;
-            public int X;
-            public int Y;
+            public char type;
+            public int x;
+            public int y;
         };
         public static char[,] generate(int width, int height)
         {
@@ -205,21 +205,21 @@
             //Sets Border To Ocean Biome
             for (int k = 0; k < width; k++)
             {//goes through and sets top and bottom rows to Ocean biome.
-                bio[NumBio + k * 2].Type = '~';
+                bio[NumBio + k * 2].type = '~';
                 bio[NumBio + k * 2].X = k;
                 bio[NumBio + k * 2].Y = 0;

-                bio[NumBio + k * 2 + 1].Type = '~';
+                bio[NumBio + k * 2 + 1].type = '~';
                 bio[NumBio + k * 2 + 1].X = k;
                 bio[NumBio + k * 2 + 1].Y = height - 1;
             }
             for (int l = 0; l < height; l++)
             {//Sets Left and Right border to Ocean biome
-                bio[NumBio + width + l * 2].Type = '~';
+                bio[NumBio + width + l * 2].type = '~';
                 bio[NumBio + width + l * 2].X = 0;
                 bio[NumBio + width + l * 2].Y = l;

-                bio[NumBio + width + l * 2 + 1].Type = '~';
+                bio[NumBio + width + l * 2 + 1].type = '~';
                 bio[NumBio + width + l * 2 + 1].X = width - 1;
                 bio[NumBio + width + l * 2 + 1].Y = l;
             }
@@ -241,7 +241,7 @@
                         int Cdist = Xdiff * Xdiff + Ydiff * Ydiff;
                         if (Cdist < dist)
                         {
-                            nearest = bio[z].Type;
+                            nearest = bio[z].type;
                             dist = Cdist;
                         }

@@ -261,8 +261,8 @@
             }

 			//River Algorithm
-			for(int i=0;i<100;i++){
-				for(int j=0;j<100;j++){
+			for(int i=0;i<height;i++){
+				for(int j=0;j<width;j++){
 					if(field[j, i]=='M')
 						elevation[j, i] = r.Next(40,90);
 					if(field[j, i]=='T')
@@ -281,11 +281,11 @@
 			}

 			for(int i=0;i<numRivers;i++){
-				int riveRX = r.Next(50,width-50);
-				int riveRY = r.Next(50,height-50);
-				if(elevation[riveRX,riveRX]<25){
-					riveRX = r.Next(50,width-50);
-					riveRY = r.Next(50,height-50);
+				int riveRX = r.Next(50,width - 50);
+				int riveRY = r.Next(50,height - 50);
+				if(elevation[riveRX,riveRX] < 25){
+					riveRX = r.Next(50,width - 50);
+					riveRY = r.Next(50,height - 50);
 				}

 				int lastDir =5;
@@ -307,10 +307,10 @@
 				}

 				//make this random length
-				field[riveRX,riveRX] = '-';//Designed for '-' character, but use ocean biome for now.
+				field[riveRX,riveRY] = '-';//Designed for '-' character, but use ocean biome for now.
 				for(int j=0;j<riverLength;j++){
 					int minHeight = 100;
-					if(lastDir != 2 &&elevation[riveRX-1,riveRX]<minHeight){
+					if(lastDir != 2 &&elevation[riveRX-1,riveRY]<minHeight){
 						minHeight = elevation[riveRX-1,riveRY];
 						Direction=0;
 					}
@@ -343,10 +343,10 @@
 							break;
 					}
 					lastDir = Direction;
-					if(field[riveRX,riveRY]=='~')
+					if(field[riveRX,riveRY] == '~')
 						break;
 					else
-						field[riveRX,riveRY]='-';
+						field[riveRX,riveRY] = '-';
 				}
 			}
             //Adding Resources.
@@ -362,7 +362,7 @@
                     else if (field[j, i] == 'F')
                     {
                         if (r.Next(0, MAX_CHANCE) <= IRON_CHANCE)
-                            field[j, i] = 'L';//sawmill for lumber
+                            field[j, i] = 'I';//sawmill for iron
                     }
                     else if (field[j, i] == '%')
                     {
@@ -387,7 +387,7 @@
 						}
 						if(field[j+1,i+1]!='~' && field[j,i+1]!='~' && field[j-1,i+1]!='~')
 						{
-							field[j,i]='%';//Coast tile with land on east.
+							field[j,i]='/';//Coast tile with land on east.
 						}
 						if(field[j+1,i]!='~' && field[j+1,i-1]!='~' && field[j+1,i+1]!='~')
 						{


Fix post-merge errors.

Fix post-merge errors.

--- osu.Game.Modes.Taiko/Objects/Drawable/DrawableHit.cs
+++ osu.Game.Modes.Taiko/Objects/Drawable/DrawableHit.cs
@@ -7,7 +7,7 @@

 namespace osu.Game.Modes.Taiko.Objects.Drawable
 {
-    public abstract class DrawableHit : DrawableTaikoHitObject<TaikoHitObject>
+    public abstract class DrawableHit : DrawableTaikoHitObject
     {
         /// <summary>
         /// A list of keys which can result in hits for this HitObject.


Next release is Dedekind

Next release is Dedekind

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -16,10 +16,10 @@
     : ScenarioModule,
       WindowRenderer.ManagerInterface {

-  private const String next_release_name_ = "Darboux";
-  private const int next_release_lunation_number_ = 227;
+  private const String next_release_name_ = "Dedekind";
+  private const int next_release_lunation_number_ = 228;
   private DateTimeOffset next_release_date_ =
-      new DateTimeOffset(2018, 05, 15, 11, 48, 00, TimeSpan.Zero);
+      new DateTimeOffset(2018, 06, 13, 19, 43, 00, TimeSpan.Zero);

   // From https://forum.kerbalspaceprogram.com/index.php?/topic/84273--/,
   // edited 2017-03-09.  Where the name of the layer is not CamelCase, the


ERROR

ERROR

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -2023,9 +2023,9 @@
         body => {
           double timewarp_limit = body.timeWarpAltitudeLimits[1];
           if (timewarp_limit == 0) {
-            Log.Warning("The timewarp limit for " + body.theName + " vanishes");
+            Log.Error("The timewarp limit for " + body.theName + " vanishes");
             if (body.atmosphereDepth == 0) {
-              Log.Warning(
+              Log.Error(
                   body.theName + " is airless, setting the manageability" +
                   " threshold to 10 km to allow landings");
               timewarp_limit = 10e3;


spheres

spheres

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -865,6 +865,7 @@
       Vector3d camera_to_point = point - camera;
       Vector3d camera_to_body = body.position - camera;
       double inner_product = Vector3d.Dot(camera_to_point, camera_to_body);
+      double r_squared = body.Radius * body.Radius;
       // The projections on the camera-body axis of |point| and of the horizon
       // have lengths |inner_product| / d and d - r^2/d, where d is the distance
       // between the camera and the body and r is the body's radius, thus if
@@ -873,11 +874,15 @@
       // Otherwise, we check whether |point| is within the cone hidden from the
       // camera, by comparing the squared cosines multiplied by
       // d^2|camera_to_point|^2.
+      // In addition, we check whether we're inside the body (this covers the
+      // cap above the horizon plane and below the surface of the body, which
+      // would otherwise be displayed.
       double d_squared_minus_r_squared =
-          camera_to_body.sqrMagnitude - body.Radius * body.Radius;
-      if (inner_product > d_squared_minus_r_squared &&
-          inner_product * inner_product >
-              camera_to_point.sqrMagnitude * d_squared_minus_r_squared) {
+          camera_to_body.sqrMagnitude - r_squared;
+      if ((body.position - point).sqrMagnitude < r_squared ||
+          (inner_product > d_squared_minus_r_squared &&
+           inner_product * inner_product >
+               camera_to_point.sqrMagnitude * d_squared_minus_r_squared)) {
         return true;
       }
     }


Next lunation name, number, and date

Next lunation name, number, and date

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -16,10 +16,10 @@
     : ScenarioModule,
       WindowRenderer.ManagerInterface {

-  private const String next_release_name_ = "Christoffel";
-  private const int next_release_lunation_number_ = 222;
+  private const String next_release_name_ = "Clifford";
+  private const int next_release_lunation_number_ = 223;
   private DateTimeOffset next_release_date_ =
-      new DateTimeOffset(2017, 12, 18, 06, 31, 00, TimeSpan.Zero);
+      new DateTimeOffset(2018, 01, 17, 02, 17, 00, TimeSpan.Zero);

   // From https://forum.kerbalspaceprogram.com/index.php?/topic/84273--/,
   // edited 2017-03-09.  Where the name of the layer is not CamelCase, the


Fix lock not being released on exception

--- src/redlock-cs/Redlock.cs
+++ src/redlock-cs/Redlock.cs
@@ -107,6 +107,8 @@
                 }
                 catch (Exception)
                 {
+                    // make sure we release any lock created on exception
+                    await ForEachRedisRegistered(database => UnlockInstance(database, resource, val));
                     return false;
                 }
             });


Added support for not having write rights in app directory (restarting patcher with administrator privilages) on Windows

--- src/Assets/Scripts/Patcher/Patcher.cs
+++ src/Assets/Scripts/Patcher/Patcher.cs
@@ -1,5 +1,7 @@
 using System;
+using System.Diagnostics;
 using System.IO;
+using System.Linq;
 using System.Threading;
 using PatchKit.Api;
 using PatchKit.Async;
@@ -7,6 +9,7 @@
 using PatchKit.Unity.Utilities;
 using PatchKit.Unity.Web;
 using UnityEngine;
+using Debug = UnityEngine.Debug;

 namespace PatchKit.Unity.Patcher
 {
@@ -189,6 +192,8 @@

             if (commonVersion == null || ShouldDownloadContent(currentVersion, commonVersion.Value))
             {
+                CheckIfCurrentDirectoryIsWritable();
+
                 LogInfo("Local application doesn't exist or files are corrupted.");

                 LogInfo("Clearing local application data.");
@@ -199,6 +204,8 @@
             }
             else if (ShouldDownloadDiff(currentVersion, commonVersion.Value))
             {
+                CheckIfCurrentDirectoryIsWritable();
+
                 LogInfo("Patching local application.");
                 while (currentVersion > commonVersion.Value)
                 {
@@ -518,5 +525,62 @@
                 OnPatcherFinished(this);
             }
         }
+
+        private void CheckIfCurrentDirectoryIsWritable()
+        {
+            bool isWritable;
+
+            try
+            {
+                string permissionsCheckFilePath = Path.Combine(_configuration.ApplicationDataPath, ".permissions_check");
+
+                if (!Directory.Exists(_configuration.ApplicationDataPath))
+                {
+                    Directory.CreateDirectory(_configuration.ApplicationDataPath);
+                }
+
+                using (FileStream fs = new FileStream(permissionsCheckFilePath, FileMode.CreateNew,
+                                                            FileAccess.Write))
+                {
+                    fs.WriteByte(0xff);
+                }
+
+                if (File.Exists(permissionsCheckFilePath))
+                {
+                    File.Delete(permissionsCheckFilePath);
+                    isWritable = true;
+                }
+                else
+                {
+                    isWritable = false;
+                }
+            }
+            catch (Exception)
+            {
+                isWritable = false;
+            }
+
+            if (!isWritable)
+            {
+                if (Application.platform == RuntimePlatform.WindowsPlayer)
+                {
+                    ProcessStartInfo info = new ProcessStartInfo
+                    {
+                        FileName = Application.dataPath.Replace("_Data", ".exe"),
+                        Arguments = string.Join(" ", Environment.GetCommandLineArgs().Select(s => "\"" + s + "\"").ToArray()),
+                        UseShellExecute = true,
+                        Verb = "runas"
+                    };
+
+                    Process.Start(info);
+
+                    Application.Quit();
+                    throw new OperationCanceledException();
+                }
+
+                throw new UnauthorizedAccessException("Missing write access for working directory - " +
+                                                      _configuration.ApplicationDataPath);
+            }
+        }
     }
 }


Push some temporary Console.WriteLines to debug failures on TeamCity

--- src/BloomExe/Publish/PublishHelper.cs
+++ src/BloomExe/Publish/PublishHelper.cs
@@ -251,15 +251,18 @@
 			// This temporary code is to help us figure out why javascript errors are
 			// occurring on TeamCity but not locally.
 			Console.WriteLine("*****IsDisplayed*************");
-			Console.WriteLine(elt.OuterXml);
-			Console.WriteLine("******************");
-			if (elt.OwnerDocument != null)
-				Console.WriteLine(elt.OwnerDocument.OuterXml);
-			Console.WriteLine("******************");
-			Console.WriteLine(id);
+			Console.WriteLine("id: " + id);
+			var getElement = _browser.RunJavaScript("document.getElementById('" + id + "').outerHTML");
+			if (String.IsNullOrWhiteSpace(getElement) || getElement == "null" || getElement == "undefined")
+			{
+				Console.WriteLine("document.getElementById('" + id + "'): ");
+				Console.WriteLine(getElement);
+				Console.WriteLine(_browser.RunJavaScript("document.documentElement.outerHTML"));
+			}
+			var display = _browser.RunJavaScript ("getComputedStyle(document.getElementById('" + id + "'), null).display");
+			Console.WriteLine("IsDisplayed result: " + display);
 			Console.WriteLine();
-
-			var display = _browser.RunJavaScript ("getComputedStyle(document.getElementById('" + id + "'), null).display");
+			Console.WriteLine();
 			return display != "none";
 		}


Fixing Issue #29

Fixing Issue #29

--- src/CacheCow.Client/CachingHandler.cs
+++ src/CacheCow.Client/CachingHandler.cs
@@ -107,7 +107,7 @@
 					// client can tell CachingHandler not to do caching for a particular request
 					if(request.Headers.CacheControl!=null)
 					{
-						if (request.Headers.CacheControl.NoCache || request.Headers.CacheControl.NoStore)
+						if (request.Headers.CacheControl.NoStore)
 							return true;
 					}


Updating XML comment

Updating XML comment

--- src/CommandLine/UnParserExtensions.cs
+++ src/CommandLine/UnParserExtensions.cs
@@ -11,7 +11,7 @@
 namespace CommandLine
 {
     /// <summary>
-    /// Defines overloads to unparse options instance.
+    /// Adds a method to unparse options instance.
     /// </summary>
     public static class UnParserExtensions
     {


Vectorize some Guid APIs (ctor, TryWriteBytes) (dotnet/coreclr#21336)

* Optimize some Guid APIs

* get rid of WriteByteHelper

* use TryWrite instead of Write

* Optimize ctor `Guid(ReadOnlySpan<byte> b)` and remove `Equals` optimization (move to separate PR).

Signed-off-by: dotnet-bot <03c4cb6107ae99956a7681f2c97ff7104809a2bd@microsoft.com>

--- src/Common/src/CoreLib/System/Guid.cs
+++ src/Common/src/CoreLib/System/Guid.cs
@@ -51,6 +51,14 @@
             if ((uint)b.Length != 16)
                 throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));

+            if (BitConverter.IsLittleEndian)
+            {
+                this = MemoryMarshal.Read<Guid>(b);
+                return;
+            }
+
+            // slower path for BigEndian:
+            _k = b[15];  // hoist bounds checks
             _a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0];
             _b = (short)(b[5] << 8 | b[4]);
             _c = (short)(b[7] << 8 | b[6]);
@@ -61,7 +69,6 @@
             _h = b[12];
             _i = b[13];
             _j = b[14];
-            _k = b[15];
         }

         [CLSCompliant(false)]
@@ -93,6 +100,7 @@
             _a = a;
             _b = b;
             _c = c;
+            _k = d[7]; // hoist bounds checks
             _d = d[0];
             _e = d[1];
             _f = d[2];
@@ -100,7 +108,6 @@
             _h = d[4];
             _i = d[5];
             _j = d[6];
-            _k = d[7];
         }

         // Creates a new GUID initialized to the value represented by the
@@ -768,9 +775,34 @@
             str[i] == '0' &&
             (str[i + 1] | 0x20) == 'x';

-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private void WriteByteHelper(Span<byte> destination)
-        {
+        // Returns an unsigned byte array containing the GUID.
+        public byte[] ToByteArray()
+        {
+            var g = new byte[16];
+            if (BitConverter.IsLittleEndian)
+            {
+                MemoryMarshal.TryWrite<Guid>(g, ref this);
+            }
+            else
+            {
+                TryWriteBytes(g);
+            }
+            return g;
+        }
+
+        // Returns whether bytes are sucessfully written to given span.
+        public bool TryWriteBytes(Span<byte> destination)
+        {
+            if (BitConverter.IsLittleEndian)
+            {
+                return MemoryMarshal.TryWrite(destination, ref this);
+            }
+
+            // slower path for BigEndian
+            if (destination.Length < 16)
+                return false;
+
+            destination[15] = _k; // hoist bounds checks
             destination[0] = (byte)(_a);
             destination[1] = (byte)(_a >> 8);
             destination[2] = (byte)(_a >> 16);
@@ -786,24 +818,6 @@
             destination[12] = _h;
             destination[13] = _i;
             destination[14] = _j;
-            destination[15] = _k;
-        }
-
-        // Returns an unsigned byte array containing the GUID.
-        public byte[] ToByteArray()
-        {
-            var g = new byte[16];
-            WriteByteHelper(g);
-            return g;
-        }
-
-        // Returns whether bytes are sucessfully written to given span.
-        public bool TryWriteBytes(Span<byte> destination)
-        {
-            if (destination.Length < 16)
-                return false;
-
-            WriteByteHelper(destination);
             return true;
         }


Return a proper error code when attempting to use a javascript filter function but the filter compiler is not set

--- src/Couchbase.Lite.Shared/Database.cs
+++ src/Couchbase.Lite.Shared/Database.cs
@@ -662,11 +662,6 @@
             }

             if(result == null) {
-                var filterCompiler = FilterCompiler;
-                if(filterCompiler == null) {
-                    return null;
-                }
-
                 string language = null;
                 var sourceCode = GetDesignDocFunction(name, "filters", out language) as string;

@@ -674,6 +669,15 @@
                     if(status != null) {
                         status.Code = StatusCode.NotFound;
                     }
+                    return null;
+                }
+
+                var filterCompiler = FilterCompiler;
+                if(filterCompiler == null) {
+                    if(status != null) {
+                        status.Code = StatusCode.NotImplemented;
+                    }
+
                     return null;
                 }


--- src/Cuemon.Core/GlobalSuppressions.cs
+++ src/Cuemon.Core/GlobalSuppressions.cs
@@ -271,3 +271,4 @@
 [assembly: SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "By design.", Scope = "member", Target = "~F:Cuemon.Reflection.MemberReflection.Everything")]
 [assembly: SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "By design.", Scope = "member", Target = "~M:Cuemon.Reflection.MemberReflection.#ctor(System.Action{Cuemon.Reflection.MemberReflectionOptions})")]
 [assembly: SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "By design.", Scope = "member", Target = "~M:Cuemon.Globalization.ResourceAttribute.GetString(System.String)~System.String")]
+[assembly: SuppressMessage("Major Code Smell", "S1854:Unused assignments should be removed", Justification = "False Positive", Scope = "member", Target = "~M:Cuemon.DateSpan.#ctor(System.DateTime,System.DateTime,System.Globalization.Calendar)")]


Add initial implementations IPolynomial for order 1 and 2

--- src/FireworksNet/TempEliteStrategy.cs
+++ src/FireworksNet/TempEliteStrategy.cs
@@ -36,6 +36,56 @@
         /// <param name="upperBound">The upper bound.</param>
         /// <returns>Elite point.</returns>
         double SelectElitePoint(Func<double, double> polynomialFunc, double lowerBound, double upperBound);
+    }
+
+    public class FirstOrderPolynomial : IPolynomial
+    {
+        private readonly int order;
+
+        public FirstOrderPolynomial()
+        {
+            this.order = 1;
+        }
+
+        public virtual Func<double, double> Approximate(double[] fireworkQualities, double[] fireworkCoordinates)
+        {
+            if (fireworkQualities == null)
+            {
+                throw new ArgumentNullException("fireworkQualities");
+            }
+
+            if (fireworkCoordinates == null)
+            {
+                throw new ArgumentNullException("fireworkCoordinates");
+            }
+
+            return Fit.PolynomialFunc(fireworkQualities, fireworkCoordinates, this.order, DirectRegressionMethod.QR);
+        }
+    }
+
+    public class SecondOrderPolynomial : IPolynomial
+    {
+        private readonly int order;
+
+        public SecondOrderPolynomial()
+        {
+            this.order = 2;
+        }
+
+        public virtual Func<double, double> Approximate(double[] fireworkQualities, double[] fireworkCoordinates)
+        {
+            if (fireworkQualities == null)
+            {
+                throw new ArgumentNullException("fireworkQualities");
+            }
+
+            if (fireworkCoordinates == null)
+            {
+                throw new ArgumentNullException("fireworkCoordinates");
+            }
+
+            return Fit.PolynomialFunc(fireworkQualities, fireworkCoordinates, this.order, DirectRegressionMethod.QR);
+        }
     }

     public class TempEliteStrategy


Suggest names in invalid member access diagnostics

--- src/Flame.Ecs/ExpressionConverters.cs
+++ src/Flame.Ecs/ExpressionConverters.cs
@@ -683,7 +683,12 @@
                     // log an error only if it's used.
                     return new ErrorValue(
                         CreateFailedMemberAccessLogEntry(
-                            "value of type", Target.Expression.Type, MemberName, MemberLocation, Scope));
+                            "value of type",
+                            Target.Expression.Type,
+                            MemberName,
+                            Scope.Function.GetInstanceAndExtensionMembers(Target.Expression.Type),
+                            MemberLocation,
+                            Scope));
                 }
             }
             else if (Target.IsType)
@@ -708,7 +713,12 @@
                     }
                     return new ErrorValue(
                         CreateFailedMemberAccessLogEntry(
-                            "type", intersectionType, MemberName, MemberLocation, Scope));
+                            "type",
+                            intersectionType,
+                            MemberName,
+                            typeArray.SelectMany(Scope.Function.GetStaticMembers).Distinct(),
+                            MemberLocation,
+                            Scope));
                 }
             }
             else
@@ -724,17 +734,32 @@

         private static LogEntry CreateFailedMemberAccessLogEntry(
             string AccessedValueKind, IType AccessedValueType,
-            string MemberName, SourceLocation Location,
-            LocalScope Scope)
-        {
+            string MemberName, IEnumerable<ITypeMember> AllTypeMembers,
+            SourceLocation Location, LocalScope Scope)
+        {
+            var suggestedName = NameSuggestionHelpers.SuggestName(
+                MemberName,
+                AllTypeMembers
+                    .Select(item => item.Name)
+                    .OfType<SimpleName>()
+                    .Select(item => item.Name));
             return new LogEntry(
                 "member access",
-                NodeHelpers.HighlightEven(
+                NodeHelpers.HighlightEven(new string[]
+                {
                     AccessedValueKind + " '",
                     Scope.Function.Global.NameAbbreviatedType(AccessedValueType),
                     "' does not expose a member called '",
-                    MemberName,
-                    "'."),
+                    MemberName
+                }.Concat(
+                    suggestedName == null
+                    ? new string[] { "'." }
+                    : new string[]
+                {
+                    "'. Did you mean '",
+                    suggestedName,
+                    "'?"
+                }).ToArray()),
                 Location);
         }


Fix join with authorization code redirect

--- src/GRA.Controllers/HomeController.cs
+++ src/GRA.Controllers/HomeController.cs
@@ -76,18 +76,30 @@
             }
             if (AuthUser.Identity.IsAuthenticated)
             {
-                if (TempData.ContainsKey(TempDataKey.UserJoined)
-                    && UserHasPermission(Permission.AccessPerformerRegistration)
-                    && !UserHasPermission(Permission.AccessMissionControl))
-                {
-                    var dates = await _performerSchedulingService.GetSettingsAsync();
-                    var schedulingStage = _performerSchedulingService.GetSchedulingStage(dates);
-
-                    if (schedulingStage != PsSchedulingStage.Unavailable)
+                if (TempData.ContainsKey(TempDataKey.UserJoined))
+                {
+                    if (UserHasPermission(Permission.AccessMissionControl))
                     {
-                        TempData.Remove(TempDataKey.UserJoined);
-                        return RedirectToAction(nameof(PerformerRegistration.HomeController.Index),
-                            "Home", new { Area = "PerformerRegistration" });
+                        if (GetSiteStage() == SiteStage.BeforeRegistration
+                            || GetSiteStage() == SiteStage.AccessClosed)
+                        {
+                            return RedirectToAction(nameof(MissionControl.HomeController.Index),
+                                "Home",
+                                new { Area = nameof(MissionControl) });
+                        }
+                    }
+                    else if (UserHasPermission(Permission.AccessPerformerRegistration))
+                    {
+                        var dates = await _performerSchedulingService.GetSettingsAsync();
+                        var schedulingStage = _performerSchedulingService.GetSchedulingStage(dates);
+
+                        if (schedulingStage != PsSchedulingStage.Unavailable)
+                        {
+                            TempData.Remove(TempDataKey.UserJoined);
+                            return RedirectToAction(nameof(PerformerRegistration.HomeController.Index),
+                                "Home",
+                                new { Area = nameof(PerformerRegistration) });
+                        }
                     }
                 }


Lucene.Net.Core.Util.TimSorter: commented unused label

--- src/Lucene.Net.Core/Util/TimSorter.cs
+++ src/Lucene.Net.Core/Util/TimSorter.cs
@@ -363,7 +363,7 @@
                     Copy(i--, dest--);
                 }
                 Restore(j--, dest--);
-            outerContinue: ;
+            //outerContinue: ; // LUCENENET NOTE: Not referenced
             }
         outerBreak:
             for (; j >= 0; --dest)


BREAKING: Lucene.Net.Search.BooleanQuery: Changed protected m_weights field from List<Weight> to IList<Weight>

--- src/Lucene.Net/Search/BooleanQuery.cs
+++ src/Lucene.Net/Search/BooleanQuery.cs
@@ -238,7 +238,7 @@
             /// The <see cref="Similarities.Similarity"/> implementation. </summary>
             protected Similarity m_similarity;

-            protected List<Weight> m_weights;
+            protected IList<Weight> m_weights;
             protected int m_maxCoord; // num optional + num required
             private readonly bool disableCoord;


Fix client with hotbar slot.

Fix client with hotbar slot.

--- src/MiNET/MiNET.Client/MiNetClient.cs
+++ src/MiNET/MiNET.Client/MiNetClient.cs
@@ -1685,7 +1685,7 @@
 		{
 			McpeContainerSetSlot message = (McpeContainerSetSlot) msg;
 			Item itemStack = message.item;
-			if (Log.IsDebugEnabled) Log.Debug($"Set inventory slot on window 0x{message.windowId:X2} with slot: {message.slot} HOTBAR: {message.unknown} Item ID: {itemStack.Id} Item Count: {itemStack.Count} Meta: {itemStack.Metadata}: DatagramSequenceNumber: {message.DatagramSequenceNumber}, ReliableMessageNumber: {message.ReliableMessageNumber}, OrderingIndex: {message.OrderingIndex}");
+			if (Log.IsDebugEnabled) Log.Debug($"Set inventory slot on window 0x{message.windowId:X2} with slot: {message.slot} HOTBAR: {message.hotbarslot} Item ID: {itemStack.Id} Item Count: {itemStack.Count} Meta: {itemStack.Metadata}: DatagramSequenceNumber: {message.DatagramSequenceNumber}, ReliableMessageNumber: {message.ReliableMessageNumber}, OrderingIndex: {message.OrderingIndex}");
 		}

 		private void OnMcpeContainerSetContent(Package message)


add page name to template

add page name to template

--- src/Moonlit.Mvc/Templates/Template.cs
+++ src/Moonlit.Mvc/Templates/Template.cs
@@ -9,7 +9,7 @@
         public string Title { get; set; }
         public string Description { get; set; }
         public abstract string ViewName { get; }
-
+        public string PageName { get; set; }
         public ISite Site { get; set; }

         public virtual void OnReadyRender(ControllerContext context)


MultiFileWatcher - Improve error handling if FileSystemWatcher fails

--- src/NLog/Internal/MultiFileWatcher.cs
+++ src/NLog/Internal/MultiFileWatcher.cs
@@ -140,36 +140,61 @@
                 if (_watcherMap.ContainsKey(fileName))
                     return;

-                var watcher = new FileSystemWatcher
-                {
-                    Path = directory,
-                    Filter = Path.GetFileName(fileName),
-                    NotifyFilter = NotifyFilters
-                };
-
-                watcher.Created += OnFileChanged;
-                watcher.Changed += OnFileChanged;
-                watcher.Deleted += OnFileChanged;
-                watcher.Renamed += OnFileChanged;
-                watcher.Error += OnWatcherError;
-                watcher.EnableRaisingEvents = true;
-
-                InternalLogger.Debug("Watching path '{0}' filter '{1}' for changes.", watcher.Path, watcher.Filter);
-
-                _watcherMap.Add(fileName, watcher);
+                FileSystemWatcher watcher = null;
+
+                try
+                {
+                    watcher = new FileSystemWatcher
+                    {
+                        Path = directory,
+                        Filter = Path.GetFileName(fileName),
+                        NotifyFilter = NotifyFilters
+                    };
+
+                    watcher.Created += OnFileChanged;
+                    watcher.Changed += OnFileChanged;
+                    watcher.Deleted += OnFileChanged;
+                    watcher.Renamed += OnFileChanged;
+                    watcher.Error += OnWatcherError;
+                    watcher.EnableRaisingEvents = true;
+
+                    InternalLogger.Debug("Watching path '{0}' filter '{1}' for changes.", watcher.Path, watcher.Filter);
+
+                    _watcherMap.Add(fileName, watcher);
+                }
+                catch (Exception ex)
+                {
+                    InternalLogger.Error(ex, "Failed Watching path '{0}' with file '{1}' for changes.", directory, fileName);
+                    if (ex.MustBeRethrown())
+                        throw;
+
+                    if (watcher != null)
+                    {
+                        StopWatching(watcher);
+                    }
+                }
             }
         }

         private void StopWatching(FileSystemWatcher watcher)
         {
-            InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
-            watcher.EnableRaisingEvents = false;
-            watcher.Created -= OnFileChanged;
-            watcher.Changed -= OnFileChanged;
-            watcher.Deleted -= OnFileChanged;
-            watcher.Renamed -= OnFileChanged;
-            watcher.Error -= OnWatcherError;
-            watcher.Dispose();
+            try
+            {
+                InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
+                watcher.EnableRaisingEvents = false;
+                watcher.Created -= OnFileChanged;
+                watcher.Changed -= OnFileChanged;
+                watcher.Deleted -= OnFileChanged;
+                watcher.Renamed -= OnFileChanged;
+                watcher.Error -= OnWatcherError;
+                watcher.Dispose();
+            }
+            catch (Exception ex)
+            {
+                InternalLogger.Error(ex, "Failed to stop file watcher for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
+                if (ex.MustBeRethrown())
+                    throw;
+            }
         }

         private void OnWatcherError(object source, ErrorEventArgs e)


Fix ShowPlanBuilder so that literals are displayed correctly

--- src/NQuery/Algebra/ShowPlanBuilder.cs
+++ src/NQuery/Algebra/ShowPlanBuilder.cs
@@ -178,7 +178,12 @@
         {
             var properties = Enumerable.Empty<KeyValuePair<string, string>>();
             var children = Enumerable.Empty<ShowPlanNode>();
-            return new ShowPlanNode("Literal (" + node.Value + ")", properties, children, true);
+            var value = node.Value == null
+                            ? "NULL"
+                            : node.Value is string
+                                  ? "'" + node.Value.ToString().Replace("'", "''") + "'"
+                                  : node.Value.ToString();
+            return new ShowPlanNode("Literal (" + value + ")", properties, children, true);
         }

         private static ShowPlanNode BuildValueSlotExpression(AlgebraValueSlotExpression node)


Exclude nunit and nCrunch from automatic bootstrap registration

--- src/Nancy/DefaultNancyBootstrapper.cs
+++ src/Nancy/DefaultNancyBootstrapper.cs
@@ -35,6 +35,8 @@
                 asm => asm.FullName.StartsWith("SMDiagnostics", StringComparison.Ordinal),
                 asm => asm.FullName.StartsWith("CppCodeProvider", StringComparison.Ordinal),
                 asm => asm.FullName.StartsWith("WebDev.WebHost40", StringComparison.Ordinal),
+                asm => asm.FullName.StartsWith("nunit", StringComparison.Ordinal),
+                asm => asm.FullName.StartsWith("nCrunch", StringComparison.Ordinal),
             };

         /// <summary>


Move some of the grain instance initialization logic outside lock.

- Can move some of the grain instance initialization logic outside lock.

--- src/OrleansRuntime/Catalog/Catalog.cs
+++ src/OrleansRuntime/Catalog/Catalog.cs
@@ -569,28 +569,38 @@
             GrainTypeData grainTypeData = GrainTypeManager[grainClassName];

             Type grainType = grainTypeData.Type;
+            Grain grain = (Grain) Activator.CreateInstance(grainType);
+            // Inject runtime hookups into grain instance
+            grain.Runtime = grainRuntime;
+            grain.Data = data;
+
             Type stateObjectType = grainTypeData.StateObjectType;
+            GrainState state;
+            if (stateObjectType != null)
+            {
+                state = (GrainState) Activator.CreateInstance(stateObjectType);
+                state.InitState(null);
+            }
+            else
+            {
+                state = null;
+            }
+
             lock (data)
             {
-                var grain = (Grain) Activator.CreateInstance(grainType);
                 grain.Identity = data.Identity;
-                grain.Runtime = grainRuntime;
                 data.SetGrainInstance(grain);

-                if (stateObjectType != null)
+                if (state != null)
                 {
                     SetupStorageProvider(data);

-                    var state = (GrainState)Activator.CreateInstance(stateObjectType);
-                    state.InitState(null);
                     data.GrainInstance.GrainState = state;
                     data.GrainInstance.Storage = new GrainStateStorageBridge(data.GrainTypeName, data.GrainInstance, data.StorageProvider);
                 }
             }

             activations.IncrementGrainCounter(grainClassName);
-
-            data.GrainInstance.Data = data;

             if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
         }


getmypid(), posix_getpid()

getmypid(), posix_getpid()

return the current thread ID instead of process ID - these functions are often used to get a unique ID of the current "request" but PID is always the same in .NET. In this way we get different values for different requests and also we don't expose system process ID.

--- src/Peachpie.Library/Miscellaneous.cs
+++ src/Peachpie.Library/Miscellaneous.cs
@@ -344,17 +344,31 @@
         /// Returns the PID of the current process.
         /// </summary>
         /// <returns>The PID.</returns>
+        /// <remarks>
+        /// The current thread ID instead of process ID -
+        /// oftenly used to get a unique ID of the current "request"
+        /// but PID is always the same in .NET.
+        /// In this way we get different values for different requests and also we don't expose system process ID
+        /// </remarks>
         public static int getmypid()
         {
-            return System.Diagnostics.Process.GetCurrentProcess().Id;
+            return System.Threading.Thread.CurrentThread.ManagedThreadId;
+            //return System.Diagnostics.Process.GetCurrentProcess().Id;
         }

         /// <summary>
         /// Return the process identifier of the current process.
         /// </summary>
+        /// <remarks>
+        /// The current thread ID instead of process ID -
+        /// oftenly used to get a unique ID of the current "request"
+        /// but PID is always the same in .NET.
+        /// In this way we get different values for different requests and also we don't expose system process ID
+        /// </remarks>
         public static int posix_getpid()
         {
-            return System.Diagnostics.Process.GetCurrentProcess().Id;
+            return System.Threading.Thread.CurrentThread.ManagedThreadId;
+            //return System.Diagnostics.Process.GetCurrentProcess().Id;
         }

         /// <summary>


implemented new ISettings interface for version 3

--- src/Plugin.Settings.Tizen/Settings.cs
+++ src/Plugin.Settings.Tizen/Settings.cs
@@ -15,123 +15,16 @@
     public class SettingsImplementation : ISettings
     {
         private readonly object locker = new object();
-
-        /// <summary>
-        /// Adds or updates a value
-        /// </summary>
-        /// <param name="key">key to update</param>
-        /// <param name="value">value to set</param>
-        /// <param name="fileName">Name of file for settings to be stored and retrieved (iOS = SuiteName, Android = Name, Windows Store/RT8.1/UWP = Container name, WinPhone 8 SL = Doesn't Apply, Tizen = Prefix)</param>
-        /// <returns>True if added or update and you need to save</returns>
-        public bool AddOrUpdateValue<T>(string key, T value, string fileName = null)
-        {
-            Type typeOf = typeof(T);
-            if (typeOf.GetTypeInfo().IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>))
-            {
-                typeOf = Nullable.GetUnderlyingType(typeOf);
-            }
-            var typeCode = Type.GetTypeCode(typeOf);
-            return AddOrUpdateValue(key, value, typeCode, fileName);
-        }
-        private bool AddOrUpdateValue(string key, object value, TypeCode typeCode, string fileName)
-        {
-            lock (locker)
-            {
-                var prefKey = GetFullPrefKey(key, fileName);
-                switch (typeCode)
-                {
-                    case TypeCode.Decimal:
-                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
-                        break;
-                    case TypeCode.Boolean:
-                        Preference.Set(prefKey, Convert.ToBoolean(value));
-                        break;
-                    case TypeCode.Int64:
-                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
-                        break;
-                    case TypeCode.Double:
-                        Preference.Set(prefKey, Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture));
-                        break;
-                    case TypeCode.String:
-                        Preference.Set(prefKey, Convert.ToString(value));
-                        break;
-                    case TypeCode.Int32:
-                        Preference.Set(prefKey, Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture));
-                        break;
-                    case TypeCode.Single:
-                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
-                        break;
-                    case TypeCode.DateTime:
-                        Preference.Set(Convert.ToString(-(Convert.ToDateTime(value)).ToUniversalTime().Ticks), prefKey);
-                        break;
-                    default:
-                        if (value is Guid)
-                        {
-                            if (value == null)
-                                value = Guid.Empty;
-
-                            Preference.Set(((Guid)value).ToString(), prefKey);
-                        }
-                        else
-                        {
-                            throw new ArgumentException($"Value of type {typeCode} is not supported.");
-                        }
-                        break;
-                }
-            }
-            return true;
-        }
-
-        /// <summary>
-        /// Clear all keys from settings
-        /// </summary>
-        /// <param name="fileName">Name of file for settings to be stored and retrieved (iOS = SuiteName, Android = Name, Windows Store/RT8.1/UWP = Container name, WinPhone 8 SL = Doesn't Apply, Tizen = Prefix)</param>
-        public void Clear(string fileName = null)
-        {
-            lock (locker)
-            {
-                if (string.IsNullOrEmpty(fileName))
-                {
-                    Preference.RemoveAll();
-                }
-                else
-                {
-                    var keys = Preference.Keys.Where(key => key.StartsWith($"{fileName}_")).ToList();
-                    keys.ForEach(Preference.Remove);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Checks to see if the key has been added.
-        /// </summary>
-        /// <param name="key">Key to check</param>
-        /// <param name="fileName">Name of file for settings to be stored and retrieved (iOS = SuiteName, Android = Name, Windows Store/RT8.1/UWP = Container name, WinPhone 8 SL = Doesn't Apply, Tizen = Prefix)</param>
-        /// <returns>True if contains key, else false</returns>
-        public bool Contains(string key, string fileName = null)
-        {
-            lock (locker)
-            {
-                return Preference.Contains(GetFullPrefKey(key, fileName));
-            }
-        }
-
-        /// <summary>
-        /// Gets the current value or the default that you specify.
-        /// </summary>
-        /// <typeparam name="T">Vaue of t (bool, int, float, long, string)</typeparam>
-        /// <param name="key">Key for settings</param>
-        /// <param name="defaultValue">default value if not set</param>
-        /// <param name="fileName">Name of file for settings to be stored and retrieved (iOS = SuiteName, Android = Name, Windows Store/RT8.1/UWP = Container name, WinPhone 8 SL = Doesn't Apply, Tizen = Prefix)</param>
-        /// <returns>Value or default</returns>
-        public T GetValueOrDefault<T>(string key, T defaultValue = default(T), string fileName = null)
+        #region Internal
+
+        T GetValueOrDefaultInternal<T>(string key, T defaultValue = default(T), string fileName = null)
         {
             lock (locker)
             {
                 var prefkey = GetFullPrefKey(key, fileName);
                 if (!Preference.Contains(prefkey))
                     return defaultValue;
-
+
                 Type typeOf = typeof(T);
                 if (typeOf.GetTypeInfo().IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>))
                 {
@@ -215,12 +108,118 @@
                 return null != value ? (T)value : defaultValue;
             }
         }
+
+        bool AddOrUpdateValueInternal<T>(string key, T value, string fileName = null)
+        {
+            Type typeOf = typeof(T);
+            if (typeOf.GetTypeInfo().IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>))
+            {
+                typeOf = Nullable.GetUnderlyingType(typeOf);
+            }
+            var typeCode = Type.GetTypeCode(typeOf);
+            return AddOrUpdateValueCore(key, value, typeCode, fileName);
+        }
+        bool AddOrUpdateValueCore(string key, object value, TypeCode typeCode, string fileName)
+        {
+            lock (locker)
+            {
+                var prefKey = GetFullPrefKey(key, fileName);
+                switch (typeCode)
+                {
+                    case TypeCode.Decimal:
+                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
+                        break;
+                    case TypeCode.Boolean:
+                        Preference.Set(prefKey, Convert.ToBoolean(value));
+                        break;
+                    case TypeCode.Int64:
+                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
+                        break;
+                    case TypeCode.Double:
+                        Preference.Set(prefKey, Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture));
+                        break;
+                    case TypeCode.String:
+                        Preference.Set(prefKey, Convert.ToString(value));
+                        break;
+                    case TypeCode.Int32:
+                        Preference.Set(prefKey, Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture));
+                        break;
+                    case TypeCode.Single:
+                        Preference.Set(prefKey, Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
+                        break;
+                    case TypeCode.DateTime:
+                        Preference.Set(Convert.ToString(-(Convert.ToDateTime(value)).ToUniversalTime().Ticks), prefKey);
+                        break;
+                    default:
+                        if (value is Guid)
+                        {
+                            if (value == null)
+                                value = Guid.Empty;
+
+                            Preference.Set(((Guid)value).ToString(), prefKey);
+                        }
+                        else
+                        {
+                            throw new ArgumentException($"Value of type {typeCode} is not supported.");
+                        }
+                        break;
+                }
+            }
+            return true;
+        }
+
+        string GetFullPrefKey(string key, string fileName = null)
+        {
+            if (string.IsNullOrEmpty(fileName))
+            {
+                return key;
+            }
+            return $"{fileName}_{key}";
+        }
+        #endregion
+
+
+        /// <summary>
+        /// Clear all keys from settings
+        /// </summary>
+        /// <param name="fileName">Prefix for the key</param>
+        public void Clear(string fileName = null)
+        {
+            lock (locker)
+            {
+                if (string.IsNullOrEmpty(fileName))
+                {
+                    Preference.RemoveAll();
+                }
+                else
+                {
+                    var keys = Preference.Keys.Where(key => key.StartsWith($"{fileName}_")).ToList();
+                    keys.ForEach(Preference.Remove);
+                }
+            }
+        }
+
+        /// <summary>
+        /// Checks to see if the key has been added.
+        /// </summary>
+        /// <param name="key">Key to check</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True if contains key, else false</returns>
+        public bool Contains(string key, string fileName = null)
+        {
+            lock (locker)
+            {
+                return Preference.Contains(GetFullPrefKey(key, fileName));
+            }
+        }
+
+

         /// <summary>
         /// Removes a desired key from the settings
         /// </summary>
         /// <param name="key">Key for setting</param>
-        /// <param name="fileName">Name of file for settings to be stored and retrieved (iOS = SuiteName, Android = Name, Windows Store/RT8.1/UWP = Container name, WinPhone 8 SL = Doesn't Apply, Tizen = Prefix)</param>
+        /// <param name="fileName">Prefix for the key</param>
         public void Remove(string key, string fileName = null)
         {
             lock (locker)
@@ -232,13 +231,173 @@
                 }
             }
         }
-        private string GetFullPrefKey(string key, string fileName = null)
-        {
-            if(string.IsNullOrEmpty(fileName))
-            {
-                return key;
-            }
-            return $"{fileName}_{key}";
-        }
+
+        #region GetValueOrDefault
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public decimal GetValueOrDefault(string key, decimal defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public bool GetValueOrDefault(string key, bool defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public long GetValueOrDefault(string key, long defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public string GetValueOrDefault(string key, string defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public int GetValueOrDefault(string key, int defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public float GetValueOrDefault(string key, float defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public DateTime GetValueOrDefault(string key, DateTime defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public Guid GetValueOrDefault(string key, Guid defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        /// <summary>
+        /// Gets the current value or the default that you specify.
+        /// </summary>
+        /// <param name="key">Key for settings</param>
+        /// <param name="defaultValue">default value if not set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>Value or default</returns>
+        public double GetValueOrDefault(string key, double defaultValue, string fileName = null) =>
+            GetValueOrDefaultInternal(key, defaultValue, fileName);
+        #endregion
+        #region AddOrUpdateValue
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, decimal value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, bool value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, long value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, string value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, int value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, float value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, DateTime value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, Guid value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+        /// <summary>
+        /// Adds or updates the value
+        /// </summary>
+        /// <param name="key">Key for settting</param>
+        /// <param name="value">Value to set</param>
+        /// <param name="fileName">Prefix for the key</param>
+        /// <returns>True of was added or updated and you need to save it.</returns>
+        public bool AddOrUpdateValue(string key, double value, string fileName = null) =>
+            AddOrUpdateValueInternal(key, value, fileName);
+
+        #endregion
     }
 }


(#44): Add description for all QueueArguments

--- src/RawRabbit/Common/QueueArgument.cs
+++ src/RawRabbit/Common/QueueArgument.cs
@@ -2,8 +2,21 @@
 {
 	public class QueueArgument
 	{
+		///
+		/// Indicates that the queue is a priority queue that honours the

+		/// priority property of a recieved message.
+		///
 		public static readonly string MaxPriority = "x-max-priority";
+
+		///
+		/// Sets what exchange that will be used as a dead letter exchange.

+		/// More information: https://www.rabbitmq.com/dlx.html
+		///
 		public static readonly string DeadLetterExchange = "x-dead-letter-exchange";
+
+		///
+		/// Sets the Time To Live (TTL) in milliseconds for messages in the queue.
+		///
 		public static readonly string MessageTtl = "x-message-ttl";

 		///


Making sure channel is inactive before dispose

This is done by checking number of publishes made during one second. If none,
then the channel is considered inactive and closed. If there are any publishes,
it will check again after ten seconds.

--- src/RawRabbit/Operations/Publisher.cs
+++ src/RawRabbit/Operations/Publisher.cs
@@ -53,13 +53,27 @@
 			}
 			_channelTimer = new Timer(state =>
 			{
-				_channelTimer?.Dispose();
-				_channel.Dispose();
-			}, null, TimeSpan.FromSeconds(10), new TimeSpan(-1));
+				var firstRef = _channel.NextPublishSeqNo;
+				Timer inner = null;
+				inner = new Timer(o =>
+				{
+					inner?.Dispose();
+					var secondRef = _channel.NextPublishSeqNo;
+					if (firstRef != secondRef)
+					{
+						_logger.LogDebug($"Channel has published ${secondRef-firstRef} message(s) the last second and is still considered active.");
+						return;
+					}
+					_logger.LogInformation($"sClosing publish channel '{_channel.ChannelNumber}'");
+					_channelTimer?.Dispose();
+					_channel.Dispose();
+				}, null, TimeSpan.FromSeconds(1), new TimeSpan(-1));
+			}, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
+
 			_channel = ChannelFactory.CreateChannel();
 			_acknowledger.SetActiveChannel(_channel);
+			DeclareExchange(config.Exchange, _channel);

-			DeclareExchange(config.Exchange, _channel);
 			return _channel;
 		}


Woops, forgot to make the windowing functions static.

--- csvorbis/Window.cs
+++ csvorbis/Window.cs
@@ -2096,7 +2096,7 @@
 		/// </summary>
 		/// <param name="n">The index to get the window table array at.</param>
 		/// <returns>The window table array at the given index.</returns>
-		internal float[] GetWindow(int n)
+		internal static float[] GetWindow(int n)
 		{
 			if (n < 0 || n > vwin.Length)
 				throw new ArgumentException("Went out of the window table's bounds.", "n");
@@ -2104,7 +2104,7 @@
 			return vwin[n];
 		}

-		internal void ApplyWindow(ref float[] d, int[] winno, long[] blockSizes, int lW, int w, int nW)
+		internal static void ApplyWindow(ref float[] d, int[] winno, long[] blockSizes, int lW, int w, int nW)
 		{
 			lW = (w != 0) ? lW : 0;
 			nW = (w != 0) ? nW : 0;


Using 32 bit msbuild directory in node handshake communication (#4958)

--- src/Shared/CommunicationsUtilities.cs
+++ src/Shared/CommunicationsUtilities.cs
@@ -655,14 +655,10 @@
         /// <returns>Base Handshake</returns>
         private static long GetBaseHandshakeForContext(TaskHostContext hostContext)
         {
-            // Use the directory, rather than the full path, because this is in Shared and may
-            // be compiled into several different assemblies. We also want to make sure
-            // MSBuildTaskHost.exe gets the same path as MSBuild.exe/Microsoft.Build.dll.
-            string msbuildDirectory = Path.GetDirectoryName(FileUtilities.ExecutingAssemblyPath);
-            string salt = Environment.GetEnvironmentVariable("MSBUILDNODEHANDSHAKESALT") + msbuildDirectory;
+            string salt = Environment.GetEnvironmentVariable("MSBUILDNODEHANDSHAKESALT") + BuildEnvironmentHelper.Instance.MSBuildToolsDirectory32;
             long nodeHandshakeSalt = GetHandshakeHashCode(salt);

-            Trace("MSBUILDNODEHANDSHAKESALT=\"{0}\", msbuildDirectory=\"{1}\", hostContext={2}, FileVersionHash={3}", Environment.GetEnvironmentVariable("MSBUILDNODEHANDSHAKESALT"), msbuildDirectory, hostContext, FileVersionHash);
+            Trace("MSBUILDNODEHANDSHAKESALT=\"{0}\", msbuildDirectory=\"{1}\", hostContext={2}, FileVersionHash={3}", Environment.GetEnvironmentVariable("MSBUILDNODEHANDSHAKESALT"), BuildEnvironmentHelper.Instance.MSBuildToolsDirectory32, hostContext, FileVersionHash);

             //FileVersionHash (32 bits) is shifted 8 bits to avoid session ID collision
             //hostContext (4 bits) is shifted just after the FileVersionHash


14: temp removed result set

14: temp removed result set

--- src/SharpConnect.MySql/MySqlPacket.cs
+++ src/SharpConnect.MySql/MySqlPacket.cs
@@ -550,11 +550,19 @@
             else
             {
                 int i = 0;
-                while (query.ReadRow())
+                if (query.ReadRow())
                 {
-                    MAX_ALLOWED_PACKET = query.resultSet.rows[0].GetDataInField("@@global.max_allowed_packet").myLong;
-                    dbugConsole.WriteLine("Rows Data " + i + " : " + query.resultSet.rows[i++]);
+                    MAX_ALLOWED_PACKET = query.GetFieldData(0).myLong;
+                    //MAX_ALLOWED_PACKET = query.resultSet.rows[0].GetDataInField("@@global.max_allowed_packet").myLong;
+                    //dbugConsole.WriteLine("Rows Data " + i + " : " + query.resultSet.rows[i++]);
                 }
+
+                //while (query.ReadRow())
+                //{
+
+                //    MAX_ALLOWED_PACKET = query.resultSet.rows[0].GetDataInField("@@global.max_allowed_packet").myLong;
+                //    dbugConsole.WriteLine("Rows Data " + i + " : " + query.resultSet.rows[i++]);
+                //}
             }
         }

@@ -798,7 +806,8 @@
         public PrepareStatement values;
         public bool typeCast;
         public bool nestTables;
-        public ResultSet resultSet;
+        //public ResultSet resultSet;
+        TableHeader tableHeader;
         public ErrPacket loadError;
         public OkPacket okPacket;
         public int index;
@@ -842,7 +851,7 @@
             this.values = values;
             typeCast = true;
             nestTables = false;
-            resultSet = null;
+            //resultSet = null;
             //this._results   = [];
             //this._fields    = [];
             index = 0;
@@ -860,7 +869,7 @@
             this.values = values;
             typeCast = config.typeCast;
             nestTables = false;
-            resultSet = null;
+            //resultSet = null;
             //this._results   = [];
             //this._fields    = [];
             index = 0;
@@ -1010,35 +1019,38 @@
         {
             ResultSetHeaderPacket resultPacket = new ResultSetHeaderPacket();
             resultPacket.ParsePacket(parser);
-            resultSet = new ResultSet(resultPacket);
+            //resultSet = new ResultSet(resultPacket);
+
+            List<FieldPacket> fields = new List<FieldPacket>();
             while (receiveBuffer[parser.Position + 4] != EOF_CODE)
             {
                 FieldPacket fieldPacket = new FieldPacket(protocol41);
                 fieldPacket.ParsePacketHeader(parser);
                 receiveBuffer = CheckLimit(fieldPacket.GetPacketLength(), receiveBuffer, DEFAULT_BUFFER_SIZE);
                 fieldPacket.ParsePacket(parser);
-                resultSet.Add(fieldPacket);
+                fields.Add(fieldPacket);
                 receiveBuffer = CheckBeforeParseHeader(receiveBuffer, (int)parser.Position, DEFAULT_BUFFER_SIZE);
             }

+            this.tableHeader = new TableHeader(fields);

             EofPacket fieldEof = new EofPacket(protocol41);//if temp[4]=0xfe then eof packet
             fieldEof.ParsePacketHeader(parser);
             receiveBuffer = CheckLimit(fieldEof.GetPacketLength(), receiveBuffer, DEFAULT_BUFFER_SIZE);
             fieldEof.ParsePacket(parser);
-            resultSet.Add(fieldEof);
+            //resultSet.Add(fieldEof);

             receiveBuffer = CheckBeforeParseHeader(receiveBuffer, (int)parser.Position, DEFAULT_BUFFER_SIZE);
         }

         public bool ReadRow()
         {
-            if (resultSet == null)
+            if (tableHeader == null)
             {
                 return false;
             }

-            TableHeader tableHeader = resultSet.GetTableHeader();
+
             switch (receiveBuffer[parser.Position + 4])
             {
                 case ERROR_CODE:
@@ -1053,7 +1065,8 @@
                         rowDataEof.ParsePacketHeader(parser);
                         receiveBuffer = CheckLimit(rowDataEof.GetPacketLength(), receiveBuffer, DEFAULT_BUFFER_SIZE);
                         rowDataEof.ParsePacket(parser);
-                        resultSet.Add(rowDataEof);
+
+                        //resultSet.Add(rowDataEof);
                         return false;
                     }
                 default:
@@ -1067,7 +1080,7 @@

                         receiveBuffer = CheckLimit(rowData.GetPacketLength(), receiveBuffer, DEFAULT_BUFFER_SIZE);
                         rowData.ParsePacket(parser);
-                        resultSet.Add(rowData);
+                        //resultSet.Add(rowData);
                         receiveBuffer = CheckBeforeParseHeader(receiveBuffer, (int)parser.Position, DEFAULT_BUFFER_SIZE);

                         dbugConsole.WriteLine("After parse Row [Position] : " + parser.Position);
@@ -1493,50 +1506,50 @@
         }
     }

-    class ResultSet
-    {
-        TableHeader tableHeader;
-        ResultSetHeaderPacket resultSetHeaderPacket;
-        List<FieldPacket> fieldPackets;
-        public List<RowDataPacket> rows;
-        public ResultSet(ResultSetHeaderPacket resultHeader)
-        {
-            resultSetHeaderPacket = resultHeader;
-            fieldPackets = new List<FieldPacket>();
-            rows = new List<RowDataPacket>();
-        }
-        public void Add(FieldPacket packet)
-        {
-            fieldPackets.Add(packet);
-        }
-        public void Add(RowDataPacket packet)
-        {
-            rows.Add(packet);
-        }
-        public void Add(EofPacket packet)
-        {
-
-        }
-
-
-        public TableHeader GetTableHeader()
-        {
-            if (tableHeader == null)
-            {
-                return tableHeader = new TableHeader(fieldPackets);
-            }
-            else
-            {
-                return tableHeader;
-            }
-        }
-
-    }
-
-    class FieldInfo
-    {
-
-    }
+    //class ResultSet
+    //{
+    //    TableHeader tableHeader;
+    //    ResultSetHeaderPacket resultSetHeaderPacket;
+    //    List<FieldPacket> fieldPackets;
+    //    public List<RowDataPacket> rows;
+    //    public ResultSet(ResultSetHeaderPacket resultHeader)
+    //    {
+    //        resultSetHeaderPacket = resultHeader;
+    //        fieldPackets = new List<FieldPacket>();
+    //        rows = new List<RowDataPacket>();
+    //    }
+    //    public void Add(FieldPacket packet)
+    //    {
+    //        fieldPackets.Add(packet);
+    //    }
+    //    public void Add(RowDataPacket packet)
+    //    {
+    //        rows.Add(packet);
+    //    }
+    //    public void Add(EofPacket packet)
+    //    {
+
+    //    }
+
+
+    //    public TableHeader GetTableHeader()
+    //    {
+    //        if (tableHeader == null)
+    //        {
+    //            return tableHeader = new TableHeader(fieldPackets);
+    //        }
+    //        else
+    //        {
+    //            return tableHeader;
+    //        }
+    //    }
+
+    //}
+
+    //class FieldInfo
+    //{
+
+    //}


Code cleanup.

Code cleanup.