Fix wording.

Fix wording.

--- source/Nuke.Core/Execution/InjectionService.cs
+++ source/Nuke.Core/Execution/InjectionService.cs
@@ -20,7 +20,7 @@
                     continue;
                 ControlFlow.Assert(attributes.Count == 1, $"Field '{field.Name}' has multiple injection attributes applied.");

-                Logger.Info($"Injecting value for '{field.Name}'...");
+                Logger.Info($"Handling value injection for '{field.Name}'...");

                 var attribute = attributes.Single();
                 attribute.InjectValue(field, build);


Revert changes to TestCaseCountingText

Revert changes to TestCaseCountingText

--- osu.Framework.Tests/Visual/TestCaseCountingText.cs
+++ osu.Framework.Tests/Visual/TestCaseCountingText.cs
@@ -3,7 +3,6 @@

 using System;
 using System.Globalization;
-using NUnit.Framework;
 using OpenTK;
 using osu.Framework.Configuration;
 using osu.Framework.Graphics;
@@ -17,8 +16,7 @@
     {
         private readonly Bindable<CountType> countType = new Bindable<CountType>();

-        [Test]
-        public void RunTest() => Schedule(() =>
+        public TestCaseCountingText()
         {
             Counter counter;

@@ -47,7 +45,7 @@
             AddStep("1 -> 4 -> 1 | 6 sec", beginStep(() => counter.CountTo(1).CountTo(4, 3000).Then().CountTo(1, 3000)));
             AddStep("1 -> 4 -> 1 | 2 sec", beginStep(() => counter.CountTo(1).CountTo(4, 1000).Then().CountTo(1, 1000)));
             AddStep("1 -> 100 | 5 sec | OutQuint", beginStep(() => counter.CountTo(1).CountTo(100, 5000, Easing.OutQuint)));
-        });
+        }

         private Action lastStep;
         private Action beginStep(Action stepAction) => () =>


Fix autosize regression (order of execution issue).

--- osu.Framework/Graphics/Containers/FlowContainer.cs
+++ osu.Framework/Graphics/Containers/FlowContainer.cs
@@ -144,6 +144,9 @@

                 current.X += size.X;
             }
+
+            //todo: remove this temporary call (required to make autosize work properly).
+            base.UpdateSubTree();
         }
     }


Inp.ut now correctly handles taps on touchpads

--- Inp.cs
+++ Inp.cs
@@ -130,7 +130,7 @@
 			AddInput(mouseId, Input.mousePosition);
 		}

-		if (Input.GetMouseButtonDown(0))
+		if(Input.GetMouseButtonDown(0))
 		{
 			inputHistoryCount[mouseId] = 1; //so that when we do any sampling,
 											// it doesn't try to go beyond where the touch started.
@@ -145,17 +145,20 @@
 			//using our custom method here because of computers with touch screen being funky
 			inputOverUIHistory[mouseId] = PositionIsOverUI(Input.mousePosition);
 		}
-		else if (Input.GetMouseButtonUp(0)) //in case we're on a touchscreen with a mouse
+		if(Input.GetMouseButtonUp(0)) //in case we're on a touchscreen with a mouse
 		{
 			inputToBeRemoved.Add(mouseId);
 		}
-		else
+		if(!Input.GetMouseButtonDown(0) && !Input.GetMouseButtonUp(0))
 		{
 			//no need for our custom (probably more expensive) method here
 			//inputOverUIHistory[mouseId] = PositionIsOverUI(Input.mousePosition);
 			inputOverUIHistory[mouseId] =
 				EventSystem.current != null && EventSystem.current.IsPointerOverGameObject();
 		}
+
+		//the structure above used to be if(down) else if (up) else, but...
+		//...on touchpads, down & up can happen during the same frame!

 		inputHistoryIndex[mouseId] = (inputHistoryIndex[mouseId] + 1) % historySize;
 		inputHistory[mouseId][inputHistoryIndex[mouseId]] = Input.mousePosition;
@@ -393,13 +396,11 @@

 			if(touchEnabled && Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled))
 			{
-				//Debug.Log("First up touch");
 				return true;
 			}

 			if(mouseEnabled && Input.touchCount == 0 && Input.GetMouseButtonUp(0))
 			{
-				//Debug.Log("First up mouse");
 				return true;
 			}

@@ -430,7 +431,6 @@
 			{
 				if(inputStart.Count < 1) //in case a second touch on a touchscreen with mouse has let go
 				{
-					//Debug.Log("touch already removed mouse");
 					return false;
 				}


Confirm pass fix

Confirm pass fix

--- Login/Register_frm.cs
+++ Login/Register_frm.cs
@@ -41,6 +41,11 @@

         private void RegisterBtn_Click(object sender, EventArgs e)
         {
+            if (ConfirmInput.Text != PasswordInput.Text)
+            {
+                MessageBox.Show("Confirm password is wrong.");
+                return;
+            }
             if (ConfirmInput.Text == "")
             {
                 MessageBox.Show(Program.LanguageManager.Translation.RegistMsb1);


[#362] Decode returns null since 0.16.4

[#362] Decode returns null since 0.16.4

--- Source/lib/oned/ITFReader.cs
+++ Source/lib/oned/ITFReader.cs
@@ -40,7 +40,7 @@
     public sealed class ITFReader : OneDReader
     {
         private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.38f);
-        private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.5f);
+        private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.6f);

         private const int W = 3; // Pixel width of a wide line
         private const int w = 2; // Pixel width of a wide line


Updates to Plugin  - Added more fields  - Added the OnUpdate method to update player positions  - Added OnNewTick method

--- FameBot/Core/Plugin.cs
+++ FameBot/Core/Plugin.cs
@@ -11,6 +11,10 @@
 using Lib_K_Relay.Networking;
 using System.Runtime.InteropServices;
 using FameBot.Helpers;
+using Lib_K_Relay.Networking.Packets;
+using Lib_K_Relay.Networking.Packets.Server;
+using Lib_K_Relay.Networking.Packets.DataObjects;
+using Lib_K_Relay.Utilities;

 namespace FameBot.Core
 {
@@ -44,6 +48,10 @@
         private IntPtr flashPtr;
         private bool followTarget = false;
         private Queue<Target> targets;
+        private Dictionary<int, Target> playerPosisions;
+        private Client connectedClient;
+
+        private float autoNexusThreshold = 0.45f;

         #region WINAPI
         // Get the focused window
@@ -54,6 +62,7 @@
         public void Initialize(Proxy proxy)
         {
             targets = new Queue<Target>();
+            playerPosisions = new Dictionary<int, Target>();

             Process[] processes = Process.GetProcessesByName("flash");
             if (processes.Length == 1)
@@ -71,8 +80,12 @@

             proxy.HookCommand("activate", ReceiveCommand);

+            proxy.HookPacket(PacketType.UPDATE, OnUpdate);
+            proxy.HookPacket(PacketType.NEWTICK, OnNewTick);
+
             proxy.ClientConnected += (client) =>
             {
+                connectedClient = client;
                 Stop();
             };
         }
@@ -106,5 +119,51 @@
             followTarget = false;
             targets.Clear();
         }
+
+        #region PacketHookMethods
+        private void OnUpdate(Client client, Packet p)
+        {
+            UpdatePacket packet = p as UpdatePacket;
+
+            // Get new info
+            foreach(Entity obj in packet.NewObjs)
+            {
+                if(Enum.IsDefined(typeof(Classes), obj.ObjectType))
+                {
+                    PlayerData playerData = new PlayerData(obj.Status.ObjectId);
+                    playerData.Class = (Classes)obj.ObjectType;
+                    playerData.Pos = obj.Status.Position;
+                    foreach(var data in obj.Status.Data)
+                    {
+                        playerData.Parse(data.Id, data.IntValue, data.StringValue);
+                    }
+
+                    if (playerPosisions.ContainsKey(obj.Status.ObjectId))
+                        playerPosisions.Remove(obj.Status.ObjectId);
+                    playerPosisions.Add(obj.Status.ObjectId, new Target(obj.Status.ObjectId, playerData.Name, playerData.Pos));
+
+                    // TODO: add portals. (object id 1810)
+                }
+            }
+
+            // Remove old info
+            foreach(int dropId in packet.Drops)
+            {
+                if (playerPosisions.ContainsKey(dropId))
+                    playerPosisions.Remove(dropId);
+            }
+        }
+
+        private void OnNewTick(Client client, Packet p)
+        {
+            NewTickPacket packet = p as NewTickPacket;
+
+            // Autonexus
+            float healthPercentage = (float)client.PlayerData.Health / (float)client.PlayerData.MaxHealth;
+            if (healthPercentage < autoNexusThreshold)
+                client.SendToServer(Packet.Create(PacketType.ESCAPE));
+
+        }
+        #endregion
     }
 }


Also show instance counts

Also show instance counts

--- osu.Framework/Statistics/TypePerformanceMonitor.cs
+++ osu.Framework/Statistics/TypePerformanceMonitor.cs
@@ -14,7 +14,7 @@

         private static readonly Stack<Type> current_collection_type_stack = new Stack<Type>();

-        private static readonly Dictionary<Type, double> collected_times = new Dictionary<Type, double>();
+        private static readonly Dictionary<Type, Collection> collected_times = new Dictionary<Type, Collection>();

         private static double consumptionTime;

@@ -35,8 +35,10 @@
             {
                 Type t = current_collection_type_stack.Peek();

-                if (!collected_times.ContainsKey(t)) collected_times[t] = 0;
-                collected_times[t] += consumeStopwatchElapsedTime();
+                if (!collected_times.TryGetValue(t, out var collection))
+                    collected_times[t] = collection = new Collection();
+
+                collection.TotalMilliseconds += consumeStopwatchElapsedTime();
             }

             current_collection_type_stack.Push(type);
@@ -53,8 +55,11 @@

             current_collection_type_stack.Pop();

-            if (!collected_times.ContainsKey(type)) collected_times[type] = 0;
-            collected_times[type] += consumeStopwatchElapsedTime();
+            if (!collected_times.TryGetValue(type, out var collection))
+                collected_times[type] = collection = new Collection();
+
+            collection.TotalMilliseconds += consumeStopwatchElapsedTime();
+            collection.Count++;
         }

         private static double lastReport;
@@ -88,8 +93,14 @@
                 GlobalStatistics.Clear(group_name);

                 int i = 0;
-                foreach (var t in collected_times.OrderByDescending(t => t.Value).Take(5))
-                    GlobalStatistics.Get<string>(group_name, $"{++i}. {t.Key.Name}").Value = $"{t.Value / framesSinceLastReport:N1}ms";
+
+                foreach (var t in collected_times.OrderByDescending(t => t.Value.TotalMilliseconds).Take(5))
+                {
+                    string runCount = t.Value.Count / framesSinceLastReport > 1 ? $" ({t.Value.Count / framesSinceLastReport} instances)" : string.Empty;
+
+                    GlobalStatistics.Get<string>(group_name, $"{++i}. {t.Key.Name}{runCount}").Value =
+                        $"{t.Value.TotalMilliseconds / framesSinceLastReport:N1}ms";
+                }

                 collected_times.Clear();
                 framesSinceLastReport = 0;
@@ -107,5 +118,11 @@

             return consumptionTime - last;
         }
+
+        private class Collection
+        {
+            public int Count;
+            public double TotalMilliseconds;
+        }
     }
 }


Fix weird bool check

Fix weird bool check

Co-authored-by: Dan Balasescu <c9bd76907373126dff70d71f8b944159a669cbf1@smgi.me>

--- osu.Game/Screens/OnlinePlay/Match/RoomSubScreen.cs
+++ osu.Game/Screens/OnlinePlay/Match/RoomSubScreen.cs
@@ -172,7 +172,7 @@

             Ruleset.Value = selected.Ruleset.Value;

-            if (selected.AllowedMods.Any() != true)
+            if (!selected.AllowedMods.Any())
             {
                 UserModsSection?.Hide();
                 userModsSelectOverlay.Hide();


Split AlignElements into two methods in order to force parameter validation to happen on call, and not on consumation of the returned collection.

--- DiffLib/Diff.Static.cs
+++ DiffLib/Diff.Static.cs
@@ -88,6 +88,12 @@
             if (aligner == null)
                 throw new ArgumentNullException(nameof(aligner));

+            return AlignElementsImplementation(collection1, collection2, diffSections, aligner);
+        }
+
+        [NotNull]
+        private static IEnumerable<DiffElement<T>> AlignElementsImplementation<T>([NotNull] IList<T> collection1, [NotNull] IList<T> collection2, [NotNull] IEnumerable<DiffSection> diffSections, [NotNull] IDiffElementAligner<T> aligner)
+        {
             int start1 = 0;
             int start2 = 0;


Remove XmlUtils class

Remove XmlUtils class

--- Src/WHampson.Bft/XmlUtils.cs
+++ Src/WHampson.Bft/XmlUtils.cs
@@ -1,45 +0,0 @@
-#region License
-/* Copyright (c) 2017 Wes Hampson
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-#endregion
-
-using System.Xml;
-using System.Xml.Linq;
-
-namespace WHampson.Bft
-{
-    internal static class XmlUtils
-    {
-        public static string BuildXmlErrorMsg(XObject o, string msgFmt, params object[] fmtArgs)
-        {
-            IXmlLineInfo lineInfo = o;
-            string msg = string.Format(msgFmt, fmtArgs);
-            if (!msg.EndsWith("."))
-            {
-                msg += ".";
-            }
-
-            msg += " " + string.Format(" Line {0}, position {1}.", lineInfo.LineNumber, lineInfo.LinePosition);
-
-            return msg;
-        }
-    }
-}


Reset StatTracker and TimeTracker addresses when game isn't running

--- Statman/Engines/HM3Engine.cs
+++ Statman/Engines/HM3Engine.cs
@@ -273,6 +273,10 @@
                 {
                     m_GameProcess = null;
                     Active = false;
+                    StatTracker.StatAddress = IntPtr.Zero;
+                    StatTracker.DifficultyAddress = IntPtr.Zero;
+                    TimeTracker.TimeAddress = IntPtr.Zero;
+
                 }
             }


[Aardvark.Base] reporting of speed up over child job time

--- src/Aardvark.Base/IO/Report.cs
+++ src/Aardvark.Base/IO/Report.cs
@@ -705,7 +705,7 @@
         public static double End(int level)
         {
             CountCallsToEnd.Increment();
-            return s_reporter.End(level, RootTarget, null);
+            return s_reporter.End(level, RootTarget, null, false);
         }

         /// <summary>
@@ -716,7 +716,7 @@
         public static double End()
         {
             CountCallsToEnd.Increment();
-            return s_reporter.End(0, RootTarget, null);
+            return s_reporter.End(0, RootTarget, null, false);
         }

         /// <summary>
@@ -731,7 +731,7 @@
         public static double End(int level, [Localizable(true)] string message, params object[] args)
         {
             CountCallsToEnd.Increment();
-            return s_reporter.End(level, RootTarget, Format(message, args));
+            return s_reporter.End(level, RootTarget, Format(message, args), false);
         }

         /// <summary>
@@ -746,7 +746,59 @@
         public static double End([Localizable(true)] string message, params object[] args)
         {
             CountCallsToEnd.Increment();
-            return s_reporter.End(0, RootTarget, Format(message, args));
+            return s_reporter.End(0, RootTarget, Format(message, args), false);
+        }
+
+        /// <summary>
+        /// Ends a block of messages. If the block was timed, its runtime is
+        /// reported. The End call MUST use the same level as the
+        /// corresponding Begin/BeginTimed. The runtime in seconds is also returned.
+        /// </summary>
+        public static double EndTimed(int level)
+        {
+            CountCallsToEnd.Increment();
+            return s_reporter.End(level, RootTarget, null, true);
+        }
+
+        /// <summary>
+        /// Ends a block of messages. If the block was timed, its runtime is
+        /// reported. The End call MUST use the same level as the
+        /// corresponding Begin/BeginTimed. The runtime in seconds is also returned.
+        /// </summary>
+        public static double EndTimed()
+        {
+            CountCallsToEnd.Increment();
+            return s_reporter.End(0, RootTarget, null, true);
+        }
+
+        /// <summary>
+        /// Ends a block of messages, and supply an end message. If the end
+        /// message is the very same as the begin message it is suppressed.
+        /// If the end message starts with a continuation character (a space,
+        /// a colon or a comma), it is viewed as a continuation message of
+        /// the begin message, and appended as appropriate. If it is not the
+        /// same and does not start with a continuation character, it is used
+        /// as a distinct end message.
+        /// </summary>
+        public static double EndTimed(int level, [Localizable(true)] string message, params object[] args)
+        {
+            CountCallsToEnd.Increment();
+            return s_reporter.End(level, RootTarget, Format(message, args), true);
+        }
+
+        /// <summary>
+        /// Ends a block of messages, and supply an end message. If the end
+        /// message is the very same as the begin message it is suppressed.
+        /// If the end message starts with a continuation character (a space,
+        /// a colon or a comma), it is viewed as a continuation message of
+        /// the begin message, and appended as appropriate. If it is not the
+        /// same and does not start with a continuation character, it is used
+        /// as a distinct end message.
+        /// </summary>
+        public static double EndTimed([Localizable(true)] string message, params object[] args)
+        {
+            CountCallsToEnd.Increment();
+            return s_reporter.End(0, RootTarget, Format(message, args), true);
         }

         /// <summary>
@@ -1056,7 +1108,7 @@
         void Text(int level, ILogTarget target, string text);
         void Wrap(int level, ILogTarget target, string text);
         ReportJob Begin(ReportJob parentJob, int level, ILogTarget target, string text, bool timed, bool noLog = false);
-        double End(int level, ILogTarget target, string text);
+        double End(int level, ILogTarget target, string text, bool addTimeToParent);
         void Tests(TestInfo testInfo);
         void Progress(int level, ILogTarget target, double progress, bool relative = false);
         void Values(int level, ILogTarget target, string name, string separator, object[] values);
@@ -1119,6 +1171,7 @@
         internal string Message;
         public readonly int HierarchyLevel;
         public readonly ReportJob ParentJob;
+        public double ChildrenTime;
         internal int Level;
         internal Stopwatch Timer;
         internal double Progress;
@@ -1131,6 +1184,7 @@
             Disposed = false;
             Message = message;
             ParentJob = parentJob;
+            ChildrenTime = 0.0;
             HierarchyLevel = parentJob == null ? 0 : parentJob.HierarchyLevel + 1;
             Level = level;
             Progress = -1.0;
@@ -1162,7 +1216,7 @@
             return null;
         }

-        public double End(int level, ILogTarget target, string text)
+        public double End(int level, ILogTarget target, string text, bool addTimeToParent)
         {
             return 0.0;
         }
@@ -1294,7 +1348,7 @@
             m_job.ReportTests = true;
         }

-        public double End(int level, ILogTarget target, string text)
+        public double End(int level, ILogTarget target, string text, bool addTimeToParent)
         {
             var parentJob = m_job.ParentJob;
             double seconds; string time; LogOpt opt;
@@ -1341,6 +1395,13 @@
             }
             else
             {
+                var childrenTime = m_job.ChildrenTime;
+                if (seconds > 0.0 && childrenTime > 0.0)
+                    time = String.Format(Localization.FormatEnUS, "[{0:F3}x] ", childrenTime / seconds) + time;
+                if (addTimeToParent)
+                {
+                    lock (parentJob) parentJob.ChildrenTime += seconds;
+                }
                 if (m_jobStack.Count > 0)
                     m_job = m_jobStack.Pop();
                 else
@@ -1485,9 +1546,9 @@
             return CurrentReporter(target).Begin(parentJob, level, target, text, timed, noLog);
         }

-        public double End(int level, ILogTarget target, string text)
-        {
-            return CurrentReporter(target).End(level, target, text);
+        public double End(int level, ILogTarget target, string text, bool addTimeToParent)
+        {
+            return CurrentReporter(target).End(level, target, text, addTimeToParent);
         }

         public void Tests(TestInfo testInfo)


Added preliminary client implementation

Added preliminary client implementation

--- MessageBird/Client.cs
+++ MessageBird/Client.cs
@@ -1,12 +1,42 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using MessageBird.Objects;
+using MessageBird.Resources;
+using MessageBird.Net;

 namespace MessageBird
 {
     public class Client
     {
+        private IRestClient restClient;
+        private Client(IRestClient restClient)
+        {
+            this.restClient = restClient;
+        }
+
+        public static Client Create(IRestClient restClient)
+        {
+            return new Client(restClient);
+        }
+
+        public static Client CreateDefault(string accessKey)
+        {
+            return new Client(new RestClient(accessKey));
+        }
+
+        public Message SendMessage(Message message)
+        {
+            Messages messageToSend = new Messages(message);
+            Messages result = (Messages)restClient.Create(messageToSend);
+
+            return result.Message;
+        }
+
+        public Message ViewMessage(string id)
+        {
+            Messages messageToView = new Messages(id);
+            Messages result = (Messages)restClient.Retrieve(messageToView);
+
+            return result.Message;
+        }
     }
-}
+}


Fixed MimeParser to never attempt another stream.Read() once it returns 0

This didn't seem to cause any problems, but it was non-optimal at the
very least. Depending on the source stream, it is possible that reading
from a stream after it has returned 0 (indicating end-of-stream) from a
previous attempt may throw an exception, which we want to avoid.

FileStream doesn't seem to have this issue, but some other stream might.

--- MimeKit/MimeParser.cs
+++ MimeKit/MimeParser.cs
@@ -129,6 +129,7 @@
 		MimeParserState state;
 		MimeFormat format;
 		bool persistent;
+		bool eos;

 		CancellationToken token = CancellationToken.None;
 		ParserOptions options;
@@ -360,6 +361,7 @@
 			headers.Clear ();
 			headerOffset = 0;
 			headerIndex = 0;
+			eos = false;

 			bounds.Clear ();
 			if (format == MimeFormat.Mbox) {
@@ -534,7 +536,7 @@
 		{
 			int left = inputEnd - inputIndex;

-			if (left >= atleast)
+			if (left >= atleast || eos)
 				return left;

 			int index = inputIndex - save;
@@ -576,6 +578,8 @@
 			if ((nread = stream.Read (input, start, end - start)) > 0) {
 				inputEnd += nread;
 				offset += nread;
+			} else {
+				eos = true;
 			}

 			return inputEnd - inputIndex;


Make sure not to hang if the last header line is truncated before CRLF

--- MimeKit/MimeParser.cs
+++ MimeKit/MimeParser.cs
@@ -761,8 +761,17 @@

 						if (inptr == inend) {
 							// we don't have enough input data
-							left = (int) (inend - start);
+							int available = (int) (inend - start);
+
 							inputIndex = (int) (start - inbuf);
+
+							if (left == available) {
+								state = MimeParserState.Error;
+								headerIndex = 0;
+								return false;
+							}
+
+							left = available;
 							needInput = true;
 							break;
 						}


Add RenderToString methods, remove some debug code.

--- template/minge/api.cs
+++ template/minge/api.cs
@@ -30,6 +30,24 @@
 			}
 		}

+		public static string RenderToSting (string path)
+		{
+			return RenderToString (path, new Dictionary<string,object> ());
+		}
+
+		public static string RenderToString (string path, Dictionary<string,object> the_args)
+		{
+			MemoryStream stream = new MemoryStream ();
+			StreamWriter writer = new StreamWriter (stream);
+
+			RenderToStream (path, writer, the_args);
+			writer.Flush ();
+
+			stream.Seek (0, SeekOrigin.Begin);
+			StreamReader reader = new StreamReader (stream);
+			return reader.ReadToEnd ();
+		}
+
 		public static void RenderToStream (string path, TextWriter writer)
 		{
 			context.RenderToStream (path, writer);
@@ -117,7 +135,6 @@

 		internal Page ParsePage (string path)
 		{
-			Console.WriteLine ("parsing path:  {0}", path);
 			MingeParser p = new MingeParser (Environment, Application);
 			string full_path = FindFullPath (path);

@@ -161,7 +178,6 @@
 				if (!Environment.AllowedExtensions.Contains (Path.GetExtension (file)))
 					continue;
 				using (TextReader tr = new StreamReader (File.OpenRead (file))) {
-					Console.WriteLine ("root: {0}   file:  {1}   name:  {2}", root_dir, file, file.Substring (root_dir.Length + 1));
 					parser.ParsePage (file.Substring (root_dir.Length + 1), tr);
 				}
 			}
@@ -181,15 +197,11 @@

 		private bool CheckFiles (DateTime ct, string [] files)
 		{
-			foreach (string file in files) {
-				Console.WriteLine ("CT: {0} -- {1}", ct, File.GetLastWriteTime (file));
-			}
 			return files.Count (f => File.GetLastWriteTime (f) > ct) > 0;
 		}

 		private void CompileDirectories ()
 		{
-
 		}
 	}

@@ -200,18 +212,8 @@

 		public void RenderToStream (string type_name, string assembly_path, TextWriter writer, Dictionary<string,object> the_args)
 		{
-			Console.WriteLine ("USING ASSEMBLY PATH:  {0}", assembly_path);
-
-
-			try {
-				Console.WriteLine ("CREATING THE PAGE");
-				IMingePage page = (IMingePage) Activator.CreateInstanceFrom (assembly_path, type_name, false, BINDING_FLAGS, null, null, null, null, null).Unwrap ();
-				Console.WriteLine ("RENDERING THE PAGE");
-				page.RenderToStream (writer, the_args);
-				Console.WriteLine ("DONE");
-			} catch (Exception e) {
-				Console.WriteLine ("EXCEPTION WHILE RENDERING:  {0}", e);
-			}
+			IMingePage page = (IMingePage) Activator.CreateInstanceFrom (assembly_path, type_name, false, BINDING_FLAGS, null, null, null, null, null).Unwrap ();
+			page.RenderToStream (writer, the_args);
 		}
 	}
 }


Avoid ODE in tests with Server logging (#2742) (#2907)

--- test/Microsoft.AspNetCore.SignalR.Tests.Utils/ServerLogScope.cs
+++ test/Microsoft.AspNetCore.SignalR.Tests.Utils/ServerLogScope.cs
@@ -15,6 +15,7 @@
         private readonly ConcurrentDictionary<string, ILogger> _serverLoggers;
         private readonly ILogger _scopeLogger;
         private readonly object _lock;
+        private bool _disposed;

         public ServerLogScope(ServerFixture serverFixture, ILoggerFactory loggerFactory, IDisposable wrappedDisposable)
         {
@@ -45,11 +46,15 @@

             ILogger logger;

-            // There maybe thready safety issues in logging when creating multiple loggers at the same time
-            // https://github.com/aspnet/Logging/issues/810
             lock (_lock)
             {
+                if (_disposed)
+                {
+                    return;
+                }
+
                 // Create (or get) a logger with the same name as the server logger
+                // Call in the lock to avoid ODE where LoggerFactory could be disposed by the wrapped disposable
                 logger = _serverLoggers.GetOrAdd(write.LoggerName, loggerName => _loggerFactory.CreateLogger(loggerName));
             }

@@ -62,7 +67,11 @@

             _scopeLogger.LogInformation("Server log scope stopped.");

-            _wrappedDisposable?.Dispose();
+            lock (_lock)
+            {
+                _wrappedDisposable?.Dispose();
+                _disposed = true;
+            }
         }
     }
 }


Removed Compression for now

Removed Compression for now

--- Grafika.Web/Startup.cs
+++ Grafika.Web/Startup.cs
@@ -31,7 +31,7 @@
         {
             services.AddGrafikaMvc();
             services.AddMemoryCache();
-            services.AddResponseCompression();
+            //services.AddResponseCompression();
             services.AddResponseCaching();
             services.ConfigureGrafikaMvc(Configuration);
         }
@@ -58,7 +58,7 @@
             );

             app.UseResponseCaching();
-            app.UseResponseCompression();
+            //app.UseResponseCompression();
             app.UseStaticFiles(new StaticFileOptions
             {
                 OnPrepareResponse = (context) =>


test fix after recent changes, #249

test fix after recent changes, #249

--- tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs
+++ tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs
@@ -21,12 +21,10 @@
             var switcher = new BenchmarkSwitcher(types);

             // BenchmarkSwitcher only picks up config values via the args passed in, not via class annotations (e.g "[DryConfig]")
-            var results = switcher.Run(new[] { "job=Dry", "class=ClassA,ClassC", "methods=Method4" });
-            Assert.Equal(2, results.Count());
-            Assert.Equal(3, results.SelectMany(r => r.Benchmarks).Count());
-            Assert.True(results.Any(r => r.Benchmarks.Any(b => b.Target.Type.Name == "ClassA" && b.Target.Method.Name == "Method1")));
-            Assert.True(results.Any(r => r.Benchmarks.Any(b => b.Target.Type.Name == "ClassA" && b.Target.Method.Name == "Method2")));
-            Assert.True(results.Any(r => r.Benchmarks.Any(b => b.Target.Type.Name == "ClassB" && b.Target.Method.Name == "Method4")));
+            var results = switcher.Run(new[] { "job=Dry", "class=ClassA,ClassC,ClassB", "methods=Method4" });
+            Assert.Equal(1, results.Count());
+            Assert.Equal(1, results.SelectMany(r => r.Benchmarks).Count());
+            Assert.True(results.All(r => r.Benchmarks.All(b => b.Target.Type.Name == "ClassB" && b.Target.Method.Name == "Method4")));
         }

         [Fact]


Replace fubar namespace

Replace fubar namespace

--- tests/fixtures/TagLib.Tests.Collections/StringCollectionTest.cs
+++ tests/fixtures/TagLib.Tests.Collections/StringCollectionTest.cs
@@ -2,7 +2,7 @@
 using NUnit.Framework;
 using TagLib;

-namespace TagLib.TagLib.Tests.Collections
+namespace TagLib.Tests.Collections
 {
     [TestFixture]
     public class StringCollectionTest


fix KeepWarmCLI if no console is available

--- KeepWarmCLI/Program.cs
+++ KeepWarmCLI/Program.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Threading;
 using PrinterHealth;
 using RavuAlHemio.CentralizedLog;

@@ -17,29 +18,40 @@
             // start the health monitor
             var healthMonitor = new HealthMonitor(config);
             // (starts automatically)
+            healthMonitor.StartKeepingWarm();

-            Console.WriteLine("Press Enter to trigger a warmup and Escape to exit.");
-            for (;;)
+            if (!Console.IsInputRedirected)
             {
-                var key = Console.ReadKey(true);
-                if (key.Key == ConsoleKey.Escape)
+                Console.WriteLine("Press Enter to trigger a warmup and Escape to exit.");
+                for (;;)
                 {
-                    break;
-                }
-                if (key.Key == ConsoleKey.Enter)
-                {
-                    try
+                    var key = Console.ReadKey(true);
+                    if (key.Key == ConsoleKey.Escape)
                     {
-                        healthMonitor.KeepWarmActuallyPerform();
+                        break;
                     }
-                    catch (Exception exc)
+                    if (key.Key == ConsoleKey.Enter)
                     {
-                        Console.WriteLine("Exception!");
-                        Console.WriteLine(exc);
+                        try
+                        {
+                            healthMonitor.KeepWarmActuallyPerform();
+                        }
+                        catch (Exception exc)
+                        {
+                            Console.WriteLine("Exception!");
+                            Console.WriteLine(exc);
+                        }
                     }
                 }
             }
-
+            else
+            {
+                for (;;)
+                {
+                    Thread.Sleep(Timeout.InfiniteTimeSpan);
+                }
+            }
+
             healthMonitor.Dispose();
         }
     }


fix compile bug

fix compile bug

--- LiveData/Connection.cs
+++ LiveData/Connection.cs
@@ -18,7 +18,7 @@

 		static IEnumerator ReconnectCoroutine() {
 			// Resubscribe to all subscriptions
-
+			yield break;
 		}
 	}
 }


Changed CommunicationClient interface implementation to explicit to hide details from client code

--- ServiceFabric.HttpClient/HttpCommunicationClient.cs
+++ ServiceFabric.HttpClient/HttpCommunicationClient.cs
@@ -24,8 +24,10 @@
         /// </summary>
         public IDictionary<string, object> Properties { get; }

-        public ResolvedServicePartition ResolvedServicePartition { get; set; }
-        public string ListenerName { get; set; }
-        public ResolvedServiceEndpoint Endpoint { get; set; }
+        ResolvedServiceEndpoint ICommunicationClient.Endpoint { get;set; }
+
+        string ICommunicationClient.ListenerName { get; set; }
+
+        ResolvedServicePartition ICommunicationClient.ResolvedServicePartition { get; set; }
     }
 }


Debug build fix (#68)

Debug build fix (#68)

--- src/Adaptive.Agrona/Concurrent/UnsafeBuffer.cs
+++ src/Adaptive.Agrona/Concurrent/UnsafeBuffer.cs
@@ -288,12 +288,11 @@
             [MethodImpl(MethodImplOptions.AggressiveInlining)]
             get { return new IntPtr(_pBuffer); }
         }
+#endif

         public byte[] ByteArray { get; private set; }

         public ByteBuffer ByteBuffer { get; private set; }
-
-#endif

 #if DEBUG
         public virtual int Capacity { get; private set; }


update exception messages

update exception messages

--- src/AngleSharp.Css/Values/Primitives/Length.cs
+++ src/AngleSharp.Css/Values/Primitives/Length.cs
@@ -317,7 +317,7 @@
                     CheckForValidRenderDimensions(renderDimensions, RenderMode.Vertical);
                     return _value * 0.01 * Math.Min(renderDimensions.RenderHeight, renderDimensions.RenderWidth);
                 default:
-                    throw new InvalidOperationException("Unsupported Unit cant be converted.");
+                    throw new InvalidOperationException("Unsupported unit cannot be converted.");
             }
         }

@@ -373,7 +373,7 @@
                     CheckForValidRenderDimensions(renderDimensions, RenderMode.Horizontal);
                     return value / ( 0.01 * Math.Min(renderDimensions.RenderHeight, renderDimensions.RenderWidth));
                 default:
-                    throw new InvalidOperationException("Unsupported Unit cant be converted.");
+                    throw new InvalidOperationException("Unsupported unit cannot be converted.");
             }
         }


Task monad join and group by

Task monad join and group by

--- LanguageExt.Core/Task.cs
+++ LanguageExt.Core/Task.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using System.Diagnostics.Contracts;
 using System.Linq;
 using System.Reactive.Linq;
@@ -31,7 +32,7 @@
             var res = pred(resT);
             if(!res)
             {
-                throw new BottomException();
+                throw new OperationCanceledException();
             }
             return resT;
         }
@@ -165,5 +166,37 @@
             self.Wait();
             return self.Result;
         }
+
+        public static async Task<V> Join<T, U, K, V>(
+            this Task<T> source,
+            Task<U> inner,
+            Func<T, K> outerKeyMap,
+            Func<U, K> innerKeyMap,
+            Func<T, U, V> project)
+        {
+            await Task.WhenAll(source, inner);
+            if (!EqualityComparer<K>.Default.Equals(outerKeyMap(source.Result), innerKeyMap(inner.Result)))
+            {
+                throw new OperationCanceledException();
+            }
+            return project(source.Result, inner.Result);
+        }
+
+        public static async Task<V> GroupJoin<T, U, K, V>(
+            this Task<T> source,
+            Task<U> inner,
+            Func<T, K> outerKeyMap,
+            Func<U, K> innerKeyMap,
+            Func<T, Task<U>, V> project)
+        {
+            T t = await source;
+            return project(t,inner.Where(u => EqualityComparer<K>.Default.Equals(outerKeyMap(t), innerKeyMap(u))));
+        }
+
+        public static async Task<T> Cast<T>(this Task source)
+        {
+            await source;
+            return (T)((dynamic)source).Result;
+        }
     }
 }


Refix this

Refix this

--- TGControlPanel/ServerPage.cs
+++ TGControlPanel/ServerPage.cs
@@ -130,6 +130,7 @@
 			ResetTestmerge.Visible = RepoExists;
 			WorldAnnounceField.Visible = RepoExists;
 			WorldAnnounceButton.Visible = RepoExists;
+			WorldAnnounceLabel.Visible = RepoExists;

 			var DM = Server.GetComponent<ITGCompiler>();
 			var DD = Server.GetComponent<ITGDreamDaemon>();


Updated test

Updated test

--- src/Arkivverket.Arkade.Test/Util/AssertTest.cs
+++ src/Arkivverket.Arkade.Test/Util/AssertTest.cs
@@ -16,7 +16,7 @@
         public void AssertNotNullShouldThrowExeptionWhenParamenterIsNull()
         {
             var exception = Assert.Throws<ArkadeException>(() => Arkade.Util.Assert.AssertNotNull("variable", null));
-            Assert.Equal("Finner ingen referanse til variable. Denne må være definert.", exception.Message);
+            Assert.Equal("Finner ingen referanse til variable. Dette må være definert.", exception.Message);
         }

         [Fact]


Simply removing the 'dot' after the resetPasswordToken in the e-mail to make it more usable (easier copy&paste) #965

--- web/en-US/EmailCommunications/Admin/ToUser/ResetPassword.cshtml
+++ web/en-US/EmailCommunications/Admin/ToUser/ResetPassword.cshtml
@@ -62,7 +62,7 @@
                                 Hi, @(info.user.firstName),

-                                It looks like you’ve misplaced the key to your kingdom. Er, password to your Loconomics account. If this is true and you requested a new password, please click the link below or paste this code into the "Reset code" field: @(info.passwordResetToken).
+                                It looks like you’ve misplaced the key to your kingdom. Er, password to your Loconomics account. If this is true and you requested a new password, please click the link below or paste this code into the "Reset code" field: @(info.passwordResetToken)

                                 At your service,

The Loconomics team


Fix GetSearcher in LuceneSearcherManager.

--- src/CK.Glouton.Lucene/LuceneSearcherManager.cs
+++ src/CK.Glouton.Lucene/LuceneSearcherManager.cs
@@ -46,7 +46,7 @@
             var readers = new List<IndexReader>();
             foreach( var appName in appNames )
             {
-                if( IndexExists( appName ) )
+                if( !IndexExists( appName ) )
                     continue;
                 var reader = GetReader( appName );
                 if( reader != null )


(GH-19) Corrected spelling mistake

(GH-19) Corrected spelling mistake

--- src/Cake.HockeyApp/Internal/HockeyAppClient.cs
+++ src/Cake.HockeyApp/Internal/HockeyAppClient.cs
@@ -24,7 +24,7 @@
         {
             if (string.IsNullOrEmpty(settings.ApiToken))
                 throw new ArgumentNullException("settings.ApiToken",
-                    $"You have to ether specify an ApiToken or define the {HockeyAppAliases.TokenVariable} environment variable.");
+                    $"You have to either specify an ApiToken or define the {HockeyAppAliases.TokenVariable} environment variable.");

             _log.Information("Uploading file to HockeyApp. This can take several minutes....");

@@ -66,7 +66,7 @@
                     settings.Tags == null ? null : string.Join(",", settings.Tags),
                     settings.Teams == null ? null : string.Join(",", settings.Teams),
                     settings.Users == null ? null : string.Join(",", settings.Users),
-                    ((int?) settings.Mandatory).ToString(), settings?.CommitSha,
+                    ((int?) settings.Mandatory).ToString(), settings?.CommitSha,
                     settings?.BuildServerUrl, settings?.RepositoryUrl, file?.FullPath, symbolFile?.FullPath);

             if (!response.Success)
@@ -116,21 +116,21 @@

             var response = await _client.UploadFileAsync(
                 apiToken: settings.ApiToken,
-                filePath: file?.FullPath,
+                filePath: file?.FullPath,
                 symbolPath: symbolFile?.FullPath,
                 notes: settings.Notes,
                 notesType: ((int?) settings.NoteType).ToString(),
                 notify: ((int?) settings.Notify).ToString(),
                 status: ((int?) settings.Status).ToString(),
                 tags: settings.Tags == null ? null : string.Join(",", settings.Tags),
-                teams: settings.Teams == null ? null : string.Join(",", settings.Teams),
+                teams: settings.Teams == null ? null : string.Join(",", settings.Teams),
                 users: settings.Users == null ? null : string.Join(",", settings.Users),
-                mandatory: ((int?) settings.Mandatory).ToString(),
+                mandatory: ((int?) settings.Mandatory).ToString(),
                 releaseType: ((int?)settings.ReleaseType).ToString(),
                 @private: (settings.Private).ToString(),
                 ownerId: settings.OwnerId,
                 commitSha: settings?.CommitSha,
-                buildServerUrl: settings?.BuildServerUrl,
+                buildServerUrl: settings?.BuildServerUrl,
                 repositoryUrl: settings?.RepositoryUrl);

             if (!response.Success)


Simplify internal property.

Simplify internal property.

--- src/Cassette/Configuration/CassetteSettings.cs
+++ src/Cassette/Configuration/CassetteSettings.cs
@@ -15,15 +15,16 @@
     /// </summary>
     public class CassetteSettings
     {
-        readonly Lazy<ICassetteManifestCache> bundleCache;
-        ICassetteManifestCache customCassetteManifestCache;
+        readonly Lazy<ICassetteManifestCache> cassetteManifestCache;

         public CassetteSettings(string cacheVersion)
         {
             Version = cacheVersion;
             DefaultFileSearches = CreateDefaultFileSearches();
             BundleFactories = CreateBundleFactories();
-            bundleCache = new Lazy<ICassetteManifestCache>(() => new CassetteManifestCache(CacheDirectory.GetFile("cassette.xml")));
+            cassetteManifestCache = new Lazy<ICassetteManifestCache>(
+                () => new CassetteManifestCache(CacheDirectory.GetFile("cassette.xml"))
+            );
         }

         /// <summary>
@@ -116,8 +117,7 @@

         internal ICassetteManifestCache CassetteManifestCache
         {
-            get { return customCassetteManifestCache ?? bundleCache.Value; }
-            set { customCassetteManifestCache = value; }
+            get { return cassetteManifestCache.Value; }
         }

         internal IBundleContainerFactory GetBundleContainerFactory(IEnumerable<ICassetteConfiguration> cassetteConfigurations)


Update behaviors of new TextWriter StringBuilder overloads (#18578)

Two issues addressed:
- CancellationToken was being ignored; the overloads should check whether cancellation was requested.  This applies to the existing Write{Line}Async overloads that were added in 2.1.
- The other overloads support inputs (string, char[], etc.) being null, and just treat that the same as an empty string.  We should do the same for StringBuilder rather than throwing.

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

--- src/Common/src/CoreLib/System/IO/TextWriter.cs
+++ src/Common/src/CoreLib/System/IO/TextWriter.cs
@@ -559,18 +559,17 @@
         /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
         public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
         {
-            // Do the argument checking before 'going async' so you get it early
-            if (value == null)
-            {
-                throw new ArgumentNullException(nameof(value));
-            }
-            // Then do the rest which may be deferred (done in the returned Task)
-            return WriteAsyncCore(value, cancellationToken);
+            return
+                cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
+                value == null ? Task.CompletedTask :
+                WriteAsyncCore(value, cancellationToken);

             async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct)
             {
                 foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
+                {
                     await WriteAsync(chunk, ct).ConfigureAwait(false);
+                }
             }
         }

@@ -596,6 +595,7 @@
         }

         public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
+            cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
             MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
                 WriteAsync(array.Array, array.Offset, array.Count) :
                 Task.Factory.StartNew(state =>
@@ -631,10 +631,21 @@
         /// StringBuilder.GetChunks() method to avoid creating the intermediate string
         /// </summary>
         /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
-        public async virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
-        {
-            await WriteAsync(value, cancellationToken).ConfigureAwait(false);
-            await WriteAsync(CoreNewLine, cancellationToken).ConfigureAwait(false);
+        public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
+        {
+            return
+                cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
+                value == null ? WriteAsync(CoreNewLine, cancellationToken) :
+                WriteLineAsyncCore(value, cancellationToken);
+
+            async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct)
+            {
+                foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
+                {
+                    await WriteAsync(chunk, ct).ConfigureAwait(false);
+                }
+                await WriteAsync(CoreNewLine, ct).ConfigureAwait(false);
+            }
         }

         public Task WriteLineAsync(char[] buffer)
@@ -659,6 +670,7 @@
         }

         public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
+            cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
             MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
                 WriteLineAsync(array.Array, array.Offset, array.Count) :
                 Task.Factory.StartNew(state =>


Correct the XML tags for the list of exceptions

Fixes dotnet/docs#6228

The text inside of the `<item>` is removed from the docs site because the `<item>` tag does not contain a child `<description>` element.

--- src/Compilers/Core/Portable/Symbols/ISymbol.cs
+++ src/Compilers/Core/Portable/Symbols/ISymbol.cs
@@ -39,12 +39,18 @@
         /// Gets the name of a symbol as it appears in metadata. Most of the time, this
         /// is the same as the Name property, with the following exceptions:
         /// <list type="number">
-        /// <item> The metadata name of generic types includes the "`1", "`2" etc. suffix that
+        /// <item>
+        /// <description>The metadata name of generic types includes the "`1", "`2" etc. suffix that
         /// indicates the number of type parameters (it does not include, however, names of
-        /// containing types or namespaces). </item>
-        /// <item> The metadata name of explicit interface names have spaces removed, compared to
-        /// the name property. </item>
-        /// <item> The length of names is limited to not exceed metadata restrictions. </item>
+        /// containing types or namespaces). </description>
+        /// </item>
+        /// <item>
+        /// <description>The metadata name of explicit interface names have spaces removed, compared to
+        /// the name property.</description>
+        /// </item>
+        /// <item>
+        /// <description>The length of names is limited to not exceed metadata restrictions.</description>
+        /// </item>
         /// </list>
         /// </summary>
         string MetadataName { get; }


Adding first version of proper cleanup to GlowWindowBehavior

--- src/ControlzEx/Behaviors/GlowWindowBehavior.cs
+++ src/ControlzEx/Behaviors/GlowWindowBehavior.cs
@@ -1,6 +1,7 @@
 namespace ControlzEx.Behaviors
 {
     using System;
+    using System.ComponentModel;
     using System.Linq;
     using System.Runtime.InteropServices;
     using System.Windows;
@@ -82,14 +83,36 @@
         {
             base.OnAttached();

-            this.AssociatedObject.SourceInitialized += (o, args) =>
-                {
-                    this.handle = new WindowInteropHelper(this.AssociatedObject).Handle;
-                    this.hwndSource = HwndSource.FromHwnd(this.handle);
-                    this.hwndSource?.AddHook(this.AssociatedObjectWindowProc);
-                };
+            this.AssociatedObject.SourceInitialized += this.AssociatedObjectSourceInitialized;
             this.AssociatedObject.Loaded += this.AssociatedObjectOnLoaded;
             this.AssociatedObject.Unloaded += this.AssociatedObjectUnloaded;
+        }
+
+        /// <inheritdoc />
+        protected override void OnDetaching()
+        {
+            this.AssociatedObject.SourceInitialized -= this.AssociatedObjectSourceInitialized;
+            this.AssociatedObject.Loaded -= this.AssociatedObjectOnLoaded;
+            this.AssociatedObject.Unloaded -= this.AssociatedObjectUnloaded;
+
+            this.hwndSource?.RemoveHook(this.AssociatedObjectWindowProc);
+
+            this.AssociatedObject.StateChanged -= this.AssociatedObjectStateChanged;
+            this.AssociatedObject.IsVisibleChanged -= this.AssociatedObjectIsVisibleChanged;
+            this.AssociatedObject.Closing -= this.AssociatedObjectOnClosing;
+
+            this.DestroyGlowVisibleTimer();
+
+            this.Close();
+
+            base.OnDetaching();
+        }
+
+        private void AssociatedObjectSourceInitialized(object sender, EventArgs e)
+        {
+            this.handle = new WindowInteropHelper(this.AssociatedObject).Handle;
+            this.hwndSource = HwndSource.FromHwnd(this.handle);
+            this.hwndSource?.AddHook(this.AssociatedObjectWindowProc);
         }

         private void AssociatedObjectStateChanged(object sender, EventArgs e)
@@ -116,6 +139,11 @@

         private void AssociatedObjectUnloaded(object sender, RoutedEventArgs e)
         {
+            this.DestroyGlowVisibleTimer();
+        }
+
+        private void DestroyGlowVisibleTimer()
+        {
             if (this.makeGlowVisibleTimer is null)
             {
                 return;
@@ -189,13 +217,15 @@
                 // hide the glows if window get invisible state
                 this.AssociatedObject.IsVisibleChanged += this.AssociatedObjectIsVisibleChanged;
                 // closing always handled
-                this.AssociatedObject.Closing += (o, args) =>
-                {
-                    if (!args.Cancel)
-                    {
-                        this.AssociatedObject.IsVisibleChanged -= this.AssociatedObjectIsVisibleChanged;
-                    }
-                };
+                this.AssociatedObject.Closing += this.AssociatedObjectOnClosing;
+            }
+        }
+
+        private void AssociatedObjectOnClosing(object o, CancelEventArgs args)
+        {
+            if (!args.Cancel)
+            {
+                this.AssociatedObject.IsVisibleChanged -= this.AssociatedObjectIsVisibleChanged;
             }
         }

@@ -317,5 +347,16 @@
             this.top?.Show();
             this.bottom?.Show();
         }
+
+        /// <summary>
+        /// Closes all glow windows
+        /// </summary>
+        private void Close()
+        {
+            this.left?.Close();
+            this.right?.Close();
+            this.top?.Close();
+            this.bottom?.Close();
+        }
     }
-}
+}


Making date scrubber more flexible

Making date scrubber more flexible

--- src/DbUp.Tests/TestInfrastructure/Scrubbers.cs
+++ src/DbUp.Tests/TestInfrastructure/Scrubbers.cs
@@ -7,7 +7,7 @@
     {
         public static string ScrubDates(string arg)
         {
-            return Regex.Replace(arg, @"\d\d/\d\d/\d\d\d\d \d?\d:\d\d:\d\d ..", "<date>");
+            return Regex.Replace(arg, @"\d?\d/\d?\d/\d?\d?\d\d \d?\d:\d\d:\d\d ..", "<date>");
         }
     }
 }


Fixed the bug in passing include_cover_page flag for async export call

--- src/Draftable.CompareAPI.Client/Comparisons.cs
+++ src/Draftable.CompareAPI.Client/Comparisons.cs
@@ -1111,11 +1111,11 @@
         /// <param name="kind">
         ///     Export kind. Supported values: single_page, combined, left, right.
         /// </param>
+        /// <param name="cancellationToken">
+        ///     A <see cref="CancellationToken" /> for cancelling the operation.
+        /// </param>
         /// <param name="includeCoverPage">
         ///     Relevant only for combined comparison, indicates whether it should include a cover page
-        /// </param>
-        /// <param name="cancellationToken">
-        ///     A <see cref="CancellationToken" /> for cancelling the operation.
         /// </param>
         /// <returns>
         ///     An <see cref="Export" /> object giving metadata about the newly created export.
@@ -1134,8 +1134,8 @@
         [NotNull]
         public async Task<Export> RunExportAsync([NotNull] string comparisonIdentifier,
                                                  ExportKind kind,
-                                                 bool includeCoverPage,
-                                                 CancellationToken cancellationToken)
+                                                 CancellationToken cancellationToken,
+                                                 bool includeCoverPage = true)
         {
             ValidateIdentifier(comparisonIdentifier ?? throw new ArgumentNullException(nameof(comparisonIdentifier)));

@@ -1145,7 +1145,7 @@
                 {
                     {"comparison", comparisonIdentifier},
                     {"kind", ExportKindStrings.Resolve(kind)},
-                    {"includeCoverPage", includeCoverPage.ToString()}
+                    {"include_cover_page", includeCoverPage.ToString()}
                 };

                 var exportJson =


Update SkiaShapeRenderer.cs

Update SkiaShapeRenderer.cs

--- src/Draw2D.Skia/Renderers/SkiaShapeRenderer.cs
+++ src/Draw2D.Skia/Renderers/SkiaShapeRenderer.cs
@@ -576,7 +576,13 @@
             {
                 var rect = SkiaHelper.ToSKRect(image.StartPoint, image.Point, dx, dy);
                 GetSKPicture(image.Path, out var picture);
+                int count = canvas.Save();
+                canvas.Translate(rect.Left, rect.Top);
+                float sx = rect.Width / picture.CullRect.Width;
+                float sy = rect.Height / picture.CullRect.Height;
+                canvas.Scale(sx, sy);
                 canvas.DrawPicture(picture);
+                canvas.RestoreToCount(count);
             }
             var style = _context?.StyleLibrary?.Get(styleId);
             if (style != null)


WeakMessageBus on Func<T, Task> fixed

WeakMessageBus on Func<T, Task> fixed

--- src/GeekyTool.Core/Messaging/WeakMessageBus.cs
+++ src/GeekyTool.Core/Messaging/WeakMessageBus.cs
@@ -209,7 +209,7 @@

                 if (method.ReturnType == typeof (Task))
                 {
-                    var callback = (Func<T, Task>)item.CreateDelegate<Action<T, Task>>();
+                    var callback = (Func<T, Task>)item.CreateDelegate<Func<T, Task>>();
                     callback(message);
                 }
                 else if (item.IsExecutable)


Check for the type map of the template type itself.

--- src/Generator/Generators/CLI/CLITypePrinter.cs
+++ src/Generator/Generators/CLI/CLITypePrinter.cs
@@ -164,7 +164,7 @@
             var decl = template.Template.TemplatedDecl;

             TypeMap typeMap = null;
-            if (TypeMapDatabase.FindTypeMap(decl, out typeMap))
+            if (TypeMapDatabase.FindTypeMap(template, out typeMap))
             {
                 typeMap.Declaration = decl;
                 typeMap.Type = template;


- uneeded using

- uneeded using

--- tweetingest-azurefunction/run.csx
+++ tweetingest-azurefunction/run.csx
@@ -2,9 +2,6 @@
 using System;
 using System.IO;
 using System.Net;
-using System.Net.Http;
-using System.Net.Requests;
-using System.Web;

 public static void Run(TimerInfo myTimer, TraceWriter log)
 {


fixes in the Linq provider due to Group By moved to Utilities now

(TFS CS 2888)

--- Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs
+++ Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs
@@ -227,11 +227,11 @@

         private ProjectionExpression AsProjection(Expression result)
         {
-            if (result.NodeType == ExpressionType.Call)
-            {
-                MethodCallExpression mca = (MethodCallExpression)result;
-                if (mca.Method.Name == "New" && mca.Method.ReturnType.IsInstantiationOf(typeof(IGrouping<,>)))
-                    return (ProjectionExpression)mca.Arguments[1];
+            if (result.NodeType == ExpressionType.New)
+            {
+                NewExpression nex = (NewExpression)result;
+                if (nex.Type.IsInstantiationOf(typeof(Grouping<,>)))
+                    return (ProjectionExpression)nex.Arguments[1];
             }
             else if (result.NodeType == (ExpressionType)DbExpressionType.MList)
             {
@@ -713,14 +713,10 @@
                         .Single(a => ReflectionTools.MemeberEquals(a.Member, m.Member)).Expression;
                 case ExpressionType.New:
                     NewExpression nex = (NewExpression)source;
+                    if (nex.Type.IsInstantiationOf(typeof(Grouping<,>)) && m.Member.Name == "Key")
+                        return nex.Arguments[0];
                     MethodInfo mi = ((PropertyInfo)m.Member).GetGetMethod();
                     return nex.Members.Zip(nex.Arguments).Single(p => ReflectionTools.MethodEqual((MethodInfo)p.First, mi)).Second;
-                case ExpressionType.Call:
-                    MethodCallExpression mca = (MethodCallExpression)source;
-                    if (mca.Method.DeclaringType.IsInstantiationOf(typeof(Grouping<,>)) &&
-                       mca.Method.Name == "New" && m.Member.Name == "Key")
-                        return mca.Arguments[0];
-                    break;
                 case (ExpressionType)DbExpressionType.FieldInit:
                     FieldInitExpression fie = (FieldInitExpression)source;
                     FieldInfo fi = m.Member as FieldInfo ?? Reflector.FindFieldInfo((PropertyInfo)m.Member);


Add IsMatchingSignature from Mono.Linker for base method check

--- MonoMod/MonoModExt.cs
+++ MonoMod/MonoModExt.cs
@@ -809,7 +809,7 @@
                             format.Append(" *(");
                             if (fpt.HasParameters)
                                 for (int i = 0; i < fpt.Parameters.Count; i++) {
-                                    var parameter = fpt.Parameters[i];
+                                    ParameterDefinition parameter = fpt.Parameters[i];
                                     if (i > 0)
                                         format.Append(",");

@@ -847,7 +847,10 @@
             MethodReference called = instr.Operand as MethodReference;
             if (called == null)
                 return false;
-            string calledTypeName = called.DeclaringType.GetPatchFullName();
+            TypeReference calledType = called.DeclaringType;
+            while (calledType is TypeSpecification)
+                calledType = ((TypeSpecification) calledType).ElementType;
+            string calledTypeName = calledType.GetPatchFullName();

             bool callingBaseType = false;
             try {
@@ -863,7 +866,206 @@
             if (!callingBaseType)
                 return false;

-            return caller.GetFindableID(withType: false) == called.GetFindableID(withType: false);
+            return caller.IsMatchingSignature(called);
+        }
+
+        // IsMatchingSignature and related methods taken and adapted from the Mono.Linker:
+        // https://github.com/mono/linker/blob/e4dfcf006b0705aba6b204aab2d603b781c5fc44/linker/Mono.Linker.Steps/TypeMapStep.cs
+
+        public static bool IsMatchingSignature(this MethodDefinition method, MethodReference candidate) {
+            if (method.Parameters.Count != candidate.Parameters.Count)
+                return false;
+
+            if (method.Name != candidate.Name)
+                return false;
+
+            if (!method.ReturnType._InflateGenericType(method).IsMatchingSignature(
+                    candidate.ReturnType._InflateGenericType(candidate)
+                ))
+                return false;
+
+            if (method.GenericParameters.Count != candidate.GenericParameters.Count)
+                return false;
+
+            if (method.HasParameters) {
+                for (int i = 0; i < method.Parameters.Count; i++)
+                    if (!method.Parameters[i].ParameterType._InflateGenericType(method).IsMatchingSignature(
+                        candidate.Parameters[i].ParameterType._InflateGenericType(candidate)
+                    ))
+                        return false;
+            }
+
+            if (!candidate.Resolve()?.IsVirtual ?? false)
+                return false;
+
+            return true;
+        }
+
+        public static bool IsMatchingSignature(this IModifierType a, IModifierType b) {
+            if (!a.ModifierType.IsMatchingSignature(b.ModifierType))
+                return false;
+
+            return a.ElementType.IsMatchingSignature(b.ElementType);
+        }
+
+        public static bool IsMatchingSignature(this TypeSpecification a, TypeSpecification b) {
+            if (a.GetType() != b.GetType())
+                return false;
+
+            GenericInstanceType gita = a as GenericInstanceType;
+            if (gita != null)
+                return gita.IsMatchingSignature((GenericInstanceType) b);
+
+            IModifierType mta = a as IModifierType;
+            if (mta != null)
+                return mta.IsMatchingSignature((IModifierType) b);
+
+            return IsMatchingSignature(a.ElementType, b.ElementType);
+        }
+
+        public static bool IsMatchingSignature(this GenericInstanceType a, GenericInstanceType b) {
+            if (!a.ElementType.IsMatchingSignature(b.ElementType))
+                return false;
+
+            if (a.HasGenericArguments != b.HasGenericArguments)
+                return false;
+
+            if (!a.HasGenericArguments)
+                return true;
+
+            if (a.GenericArguments.Count != b.GenericArguments.Count)
+                return false;
+
+            for (int i = 0; i < a.GenericArguments.Count; i++) {
+                if (!a.GenericArguments[i].IsMatchingSignature(b.GenericArguments[i]))
+                    return false;
+            }
+
+            return true;
+        }
+
+        public static bool IsMatchingSignature(this GenericParameter a, GenericParameter b) {
+            if (a.Position != b.Position)
+                return false;
+
+            if (a.Type != b.Type)
+                return false;
+
+            return true;
+        }
+
+        public static bool IsMatchingSignature(this TypeReference a, TypeReference b) {
+            if (a is TypeSpecification || b is TypeSpecification)
+                return
+                    (a is TypeSpecification && b is TypeSpecification) &&
+                    ((TypeSpecification) a).IsMatchingSignature((TypeSpecification) b);
+
+            if (a is GenericParameter && b is GenericParameter)
+                return ((GenericParameter) a).IsMatchingSignature((GenericParameter) b);
+
+            return a.FullName == b.FullName;
+        }
+
+        private static TypeReference _InflateGenericType(this TypeReference type, MethodReference method) {
+            if (!(method.DeclaringType is GenericInstanceType))
+                return type;
+            return _InflateGenericType(method.DeclaringType as GenericInstanceType, type);
+        }
+
+        private static TypeReference _InflateGenericType(GenericInstanceType genericInstanceProvider, TypeReference typeToInflate) {
+            ArrayType arrayType = typeToInflate as ArrayType;
+            if (arrayType != null) {
+                TypeReference inflatedElementType = _InflateGenericType(genericInstanceProvider, arrayType.ElementType);
+
+                if (inflatedElementType != arrayType.ElementType)
+                    return new ArrayType(inflatedElementType, arrayType.Rank);
+
+                return arrayType;
+            }
+
+            GenericInstanceType genericInst = typeToInflate as GenericInstanceType;
+            if (genericInst != null) {
+                GenericInstanceType result = new GenericInstanceType(genericInst.ElementType);
+
+                for (int i = 0; i < genericInst.GenericArguments.Count; ++i)
+                    result.GenericArguments.Add(_InflateGenericType(genericInstanceProvider, genericInst.GenericArguments[i]));
+
+                return result;
+            }
+
+            GenericParameter genericParameter = typeToInflate as GenericParameter;
+            if (genericParameter != null) {
+                if (genericParameter.Owner is MethodReference)
+                    return genericParameter;
+
+                TypeDefinition elementType = genericInstanceProvider.ElementType.Resolve();
+                GenericParameter parameter = elementType.GetGenericParameter(genericParameter.Name);
+                return genericInstanceProvider.GenericArguments[parameter.Position];
+            }
+
+            FunctionPointerType functionPointerType = typeToInflate as FunctionPointerType;
+            if (functionPointerType != null) {
+                FunctionPointerType result = new FunctionPointerType();
+                result.ReturnType = _InflateGenericType(genericInstanceProvider, functionPointerType.ReturnType);
+
+                for (int i = 0; i < functionPointerType.Parameters.Count; i++)
+                    result.Parameters.Add(new ParameterDefinition(_InflateGenericType(genericInstanceProvider, functionPointerType.Parameters[i].ParameterType)));
+
+                return result;
+            }
+
+            IModifierType modifierType = typeToInflate as IModifierType;
+            if (modifierType != null) {
+                TypeReference modifier = _InflateGenericType(genericInstanceProvider, modifierType.ModifierType);
+                TypeReference elementType = _InflateGenericType(genericInstanceProvider, modifierType.ElementType);
+
+                if (modifierType is OptionalModifierType)
+                    return new OptionalModifierType(modifier, elementType);
+
+                return new RequiredModifierType(modifier, elementType);
+            }
+
+            PinnedType pinnedType = typeToInflate as PinnedType;
+            if (pinnedType != null) {
+                TypeReference elementType = _InflateGenericType(genericInstanceProvider, pinnedType.ElementType);
+
+                if (elementType != pinnedType.ElementType)
+                    return new PinnedType(elementType);
+
+                return pinnedType;
+            }
+
+            PointerType pointerType = typeToInflate as PointerType;
+            if (pointerType != null) {
+                TypeReference elementType = _InflateGenericType(genericInstanceProvider, pointerType.ElementType);
+
+                if (elementType != pointerType.ElementType)
+                    return new PointerType(elementType);
+
+                return pointerType;
+            }
+
+            ByReferenceType byReferenceType = typeToInflate as ByReferenceType;
+            if (byReferenceType != null) {
+                TypeReference elementType = _InflateGenericType(genericInstanceProvider, byReferenceType.ElementType);
+
+                if (elementType != byReferenceType.ElementType)
+                    return new ByReferenceType(elementType);
+
+                return byReferenceType;
+            }
+
+            SentinelType sentinelType = typeToInflate as SentinelType;
+            if (sentinelType != null) {
+                TypeReference elementType = _InflateGenericType(genericInstanceProvider, sentinelType.ElementType);
+
+                if (elementType != sentinelType.ElementType)
+                    return new SentinelType(elementType);
+
+                return sentinelType;
+            }
+
+            return typeToInflate;
         }

     }


add VisitEmbeddedEntity in AssignAdapterExpander

--- Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs
+++ Signum.Engine/Linq/ExpressionVisitor/QueryBinder.cs
@@ -3079,6 +3079,14 @@
             return ee;
         }

+        protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee)
+        {
+            if (colExpression is EmbeddedEntityExpression)
+                return eee;
+
+            throw new NotImplementedException();
+        }
+
         protected internal override Expression VisitImplementedBy(ImplementedByExpression ib)
         {
             if (colExpression is ImplementedByAllExpression)


fix AuthServer.OnRulesChanged

fix AuthServer.OnRulesChanged

--- Signum.React.Extensions/Authorization/AuthServer.cs
+++ Signum.React.Extensions/Authorization/AuthServer.cs
@@ -42,7 +42,7 @@
                 Role = UserEntity.Current == null ? null : RoleEntity.Current,
             };

-            AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear();
+            AuthLogic.OnRulesChanged += ReflectionServer.InvalidateCache;

             if (TypeAuthLogic.IsStarted)
             {


Corrected some final things before test

Corrected some final things before test

--- NetInject/Purifier.cs
+++ NetInject/Purifier.cs
@@ -102,7 +102,7 @@
                     PurifyCalls(methods.Select(m => m.Item2), platGet, iplat);
                     log.InfoFormat("   added '{0}'!", CopyTypeRef(apiCSAss, opts.WorkDir));
                     log.InfoFormat("   added '{0}'!", CopyTypeRef(implCSAss, opts.WorkDir));
-                    // ass.Write(file, wparam);
+                    ass.Write(file, wparam);
                 }
             return 0;
         }
@@ -138,7 +138,7 @@
             meth.Modifiers.Clear();
             meth.Modifiers.Add("public");
             meth.Modifiers.Add("static");
-            meth.Body = "if (Environment.OSVersion.Platform != PlatformID.Win32NT) return new Win32Platform(); return new MonoPlatform();";
+            meth.Body = "if (Environment.OSVersion.Platform == PlatformID.Win32NT) return new Win32Platform(); return new MonoPlatform();";
             return meth;
         }

@@ -147,8 +147,12 @@
             var meth = new CSharpMethod(externMeth.Name);
             meth.Modifiers.Clear();
             meth.Modifiers.Add("public");
-            meth.Body = $"throw new NotImplementedException(\"Sorry!\");";
             meth.ReturnType = externMeth.ReturnType;
+            // meth.Body = $"throw new NotImplementedException(\"Sorry!\");";
+            if (meth.ReturnType.ToLowerInvariant() == "void")
+                meth.Body = "return;";
+            else
+                meth.Body = $"return default({meth.ReturnType});";
             foreach (var parm in externMeth.Parameters)
                 meth.Parameters.Add(parm);
             yield return meth;
@@ -201,13 +205,18 @@
                         methodSigs.Add(key);
                         if (Type.GetType(meth.ReturnType.FullName) == null)
                             continue;
+                        if (meth.Parameters.Any(p => Type.GetType(p.ParameterType.FullName) == null))
+                            continue;
                         yield return Tuple.Create(gen, meth);
                     }
         }

         static void AddParam(ParameterDefinition parm, CSharpMethod gen)
         {
-            var par = new CSharpParameter(Simplify(parm.ParameterType.Name), parm.Name)
+            var name = parm.Name;
+            if (!Enumerable.Range('A', 26).Contains(name.FirstOrDefault()))
+                name = "p" + gen.Parameters.Count;
+            var par = new CSharpParameter(Simplify(parm.ParameterType.Name), name)
             { IsRef = parm.ParameterType.IsByReference };
             gen.Parameters.Add(par);
         }


Enable ScrollBar when visible

Enable ScrollBar when visible

--- Signum.Windows/Controls/AutoCompleteTextBox.xaml.cs
+++ Signum.Windows/Controls/AutoCompleteTextBox.xaml.cs
@@ -330,8 +330,12 @@
             }
             else if (pop.IsMouseOver)
             {
-                ReleaseMouseCapture();
-                Commit(CloseReason.ClickList);
+                var sb = lstBox.Child<ScrollBar>(WhereFlags.VisualTree);
+                if (!sb.IsMouseOver)
+                {
+                    ReleaseMouseCapture();
+                    Commit(CloseReason.ClickList);
+                }
             }

         }
@@ -436,4 +440,5 @@
     }

     public delegate void ClosedEventHandler(object sender, CloseEventArgs e);
+
 }


adding support for more fellowship spell types (#2855)

* adding support for more fellowship spell types

* adding support for fellowship spells from non-player sources

* cleanup

--- Source/ACE.Server/WorldObjects/WorldObject_Magic.cs
+++ Source/ACE.Server/WorldObjects/WorldObject_Magic.cs
@@ -35,21 +35,29 @@
             // verify spell exists in database
             if (spell._spell == null)
             {
+                if (target is Player targetPlayer)
+                    targetPlayer.Session.Network.EnqueueSend(new GameMessageSystemChat($"{spell.Name} spell not implemented, yet!", ChatMessageType.System));
+
+                return;
+            }
+
+            if (spell.Flags.HasFlag(SpellFlags.FellowshipSpell))
+            {
                 var targetPlayer = target as Player;
-                if (targetPlayer != null)
-                    targetPlayer.Session.Network.EnqueueSend(new GameMessageSystemChat($"{spell.Name} spell not implemented, yet!", ChatMessageType.System));
-
-                return;
-            }
-
-            //if (!spell.IsSelfTargeted && target == null && spell.School != MagicSchool.WarMagic)
-                //return;
-
-            // spells only castable on creatures?
-            /*var targetCreature = target as Creature;
-            if (targetCreature == null)
-                return;*/
-
+                if (targetPlayer == null || targetPlayer.Fellowship == null)
+                    return;
+
+                var fellows = targetPlayer.Fellowship.GetFellowshipMembers();
+
+                foreach (var fellow in fellows.Values)
+                    TryCastSpell_Inner(spell, fellow, caster, tryResist, showMsg);
+            }
+            else
+                TryCastSpell_Inner(spell, target, caster, tryResist, showMsg);
+        }
+
+        public void TryCastSpell_Inner(Spell spell, WorldObject target, WorldObject caster = null, bool tryResist = true, bool showMsg = true)
+        {
             // verify before resist, still consumes source item
             if (spell.MetaSpellType == SpellType.Dispel && !VerifyDispelPKStatus(caster, target))
                 return;
@@ -66,6 +74,7 @@
                 case MagicSchool.WarMagic:
                     WarMagic(target, spell, this);
                     break;
+
                 case MagicSchool.LifeMagic:
                     var targetDeath = LifeMagic(spell, out uint damage, out bool critical, out status, target, caster);
                     if (targetDeath && target is Creature targetCreature)
@@ -74,23 +83,28 @@
                         targetCreature.Die();
                     }
                     break;
+
                 case MagicSchool.CreatureEnchantment:
                     status = CreatureMagic(target, spell, caster);
                     break;
+
                 case MagicSchool.ItemEnchantment:
                     status = ItemMagic(target, spell, caster);
                     break;
+
                 case MagicSchool.VoidMagic:
                     VoidMagic(target, spell, this);
                     break;
             }

             // send message to player, if applicable
-            var player = this as Player;
-            if (player != null && status.Message != null && !status.Broadcast && showMsg)
-                player.Session.Network.EnqueueSend(status.Message);
-            else if (player != null && status.Message != null && status.Broadcast && showMsg)
-                player.EnqueueBroadcast(status.Message, LocalBroadcastRange, ChatMessageType.Magic);
+            if (this is Player player && status.Message != null && showMsg)
+            {
+                if (status.Broadcast)
+                    player.EnqueueBroadcast(status.Message, LocalBroadcastRange, ChatMessageType.Magic);
+                else
+                    player.Session.Network.EnqueueSend(status.Message);
+            }

             // for invisible spell traps,
             // their effects won't be seen if they broadcast from themselves
@@ -365,6 +379,7 @@
             switch (spell.MetaSpellType)
             {
                 case SpellType.Boost:
+                case SpellType.FellowBoost:

                     // handle negatives?
                     int minBoostValue = Math.Min(spell.Boost, spell.MaxBoost);
@@ -666,6 +681,7 @@
                     break;

                 case SpellType.Dispel:
+                case SpellType.FellowDispel:

                     var removeSpells = target.EnchantmentManager.SelectDispel(spell);

@@ -694,6 +710,8 @@
                     break;

                 case SpellType.Enchantment:
+                case SpellType.FellowEnchantment:
+
                     damage = 0;
                     if (itemCaster != null)
                         enchantmentStatus = CreateEnchantment(target, itemCaster, spell, equip);


Action instead of PollDelegate

Action instead of PollDelegate

--- PalMon/PalMonAgent.cs
+++ PalMon/PalMonAgent.cs
@@ -18,8 +18,6 @@

 namespace PalMon
 {
-    using PollDelegate = Action;
-
     /// <summary>
     /// A timer-based performance monitoring agent.  Loads a set of counters from a config file and polls them periodically, passing the results to a writer object.
     /// </summary>
@@ -216,7 +214,7 @@
         /// Checks whether polling is in progress at the moment for a given poll method.
         /// If not, it executes the poll.
         /// </summary>
-        private bool tryStartIndividualPoll(object pollTypeLock, int timeout, PollDelegate pollDelegate)
+        private bool tryStartIndividualPoll(object pollTypeLock, int timeout, Action pollDelegate)
         {
             if (!Monitor.TryEnter(pollTypeLock, timeout))
             {


string parser

string parser

--- Parsing/LangParser.cs
+++ Parsing/LangParser.cs
@@ -66,23 +66,23 @@
                 DecimalNumber,
                 WholeNumber );

-        private static Parser<NString> SingleLineString =
+        private static Parser<NString> NormalString =
             ParserUtil.Bind( ParserUtil.Match( "\"" ), () =>
             ParserUtil.Bind( ParserUtil.ParseUntil( ParserUtil.Match( "\"" ).Map( v => new Empty() ) ), str =>
             ParserUtil.Unit( new NString( str ) ) ) );

-        public static Parser<NString> MultiLineString =
+        private static Parser<NString> RawString =
             ParserUtil.Bind( ParserUtil.Match( "[" ), () =>
             ParserUtil.Bind( ParserUtil.Match( "=" )
                                 .ZeroOrMore()
-                                .Map( value => value.Aggregate( "", (a, b) => a + b  ) ), equals =>
+                                .Map( value => value.Aggregate( "", (a, b) => a + b  ) ), equals =>
             ParserUtil.Bind( ParserUtil.Match( "[" ), () =>
             ParserUtil.Bind( ParserUtil.ParseUntil( ParserUtil.Match( "]" + equals + "]" ).Map( v => new Empty() ) ), str =>
             ParserUtil.Unit( new NString( str ) ) ) ) ) );

-        /*private static Parser<NString> NString =
+        public static Parser<NString> NString =
             ParserUtil.Alternate(
-                SingleLineString,
-                MultiLineString );*/
+                NormalString,
+                RawString );
     }
 }


removed unused method

removed unused method

--- classes/Application_Handler.cs
+++ classes/Application_Handler.cs
@@ -310,41 +310,6 @@
         public static double MovingSumX = 0;
         public static double MovingSumY = 0;

-        //Decides whether to use skeletal tracking for hands or use depth analysis
-        public static int ChooseHand(float[] coordinates, int depth)
-        {
-            int realHand = 0;
-
-            double minDepth = Convert.ToDouble(depth)/1000;
-
-            if (((coordinates[19] - 0.1) > minDepth) &&
-                ((coordinates[19] > coordinates[14]) | (coordinates[19] > coordinates[15])))
-            {
-                //left hand closer than right hand
-                if (coordinates[14] < coordinates[15])
-                {
-                    realHand = 1;
-                }
-                else
-                {
-                    realHand = 1;
-                }
-            }
-            else
-            {
-                if (coordinates[14] < coordinates[15])
-                {
-                    realHand = 3;
-                }
-                else
-                {
-                    realHand = 4;
-                }
-            }
-
-            return realHand;
-        }
-
         public static void ConfigureCalibrationByConfig()
         {
             //read calibration values from CMS if calibration app has not been set to run


Changes from pull request comments

Changes from pull request comments

--- src/BloomExe/web/ServerBase.cs
+++ src/BloomExe/web/ServerBase.cs
@@ -26,7 +26,8 @@

 		protected ServerBase()
 		{
-			_workers = new Thread[4];
+			// limit the number of worker threads to the number of processor cores
+			_workers = new Thread[Environment.ProcessorCount];
 			_queue = new Queue<HttpListenerContext>();
 			_stop = new ManualResetEvent(false);
 			_ready = new ManualResetEvent(false);
@@ -87,7 +88,7 @@

 			for (var i = 0; i < _workers.Length; i++)
 			{
-				_workers[i] = new Thread(Worker);
+				_workers[i] = new Thread(WaitForRequests);
 				_workers[i].Start();
 			}

@@ -107,21 +108,27 @@

 		private void ContextReady(IAsyncResult ar)
 		{
-			try
-			{
-				lock (_queue)
-				{
-					_queue.Enqueue(_listener.EndGetContext(ar));
-					_ready.Set();
-				}
-			}
-			catch { }
-		}
-
-		private void Worker()
-		{
+			// this can happen when shutting down
+			if (!_listenerThread.IsAlive) return;
+
+			lock (_queue)
+			{
+				_queue.Enqueue(_listener.EndGetContext(ar));
+				_ready.Set();
+			}
+		}
+
+		/// <summary>
+		/// The worker threads run this function
+		/// </summary>
+		private void WaitForRequests()
+		{
+			// _ready: indicates that there are requests in the queue that should be processed.
+			// _stop:  indicates that the class is being disposed and the thread should terminate.
 			WaitHandle[] wait = { _ready, _stop };
-			while (0 == WaitHandle.WaitAny(wait))
+
+			// WaitHandle.WaitAny(wait) returns the array index of the handle that satisfied the wait.
+			while (WaitHandle.WaitAny(wait) == 0)
 			{
 				HttpListenerContext context;
 				lock (_queue)
@@ -134,9 +141,6 @@
 						continue;
 					}
 				}
-
-				if (_isDisposing || _listener == null || !_listener.IsListening)
-					return; //strangely, this callback is fired when we close down the listener

 				var rawurl = "unknown";
 				try
@@ -245,18 +249,14 @@
 				string.Format("We need to do one more thing before Bloom is ready. Bloom needs temporary administrator privileges to set up part of its communication with the embedded web browser.{0}{0}After you click 'OK', you may be asked to authorize this step.", Environment.NewLine),
 					@"Almost there!", MessageBoxButtons.OK);

-			var startInfo = new ProcessStartInfo { UseShellExecute = true, Verb = "runas" };
-
-			if (Environment.OSVersion.Version.Major == 5 /*win xp*/)
-			{
-				startInfo.FileName = "httpcfg";
-				startInfo.Arguments = string.Format("set urlacl -u {0} /a \"D:(A;;GX;;;WD)\"", PathEndingInSlash);
-			}
-			else
-			{
-				startInfo.FileName = "netsh";
-				startInfo.Arguments = string.Format("http add urlacl url={0} user=everyone", PathEndingInSlash.TrimEnd('/'));
-			}
+			var startInfo = new ProcessStartInfo
+			{
+				UseShellExecute = true,
+				Verb = "runas",
+				FileName = "netsh",
+				Arguments = string.Format("http add urlacl url={0} user=everyone", PathEndingInSlash.TrimEnd('/'))
+			};
+
 			Process.Start(startInfo);
 		}

@@ -331,5 +331,4 @@

 		#endregion
 	}
-
 }


fixed constructor

fixed constructor

--- src/CacheMagic/CachedObject.cs
+++ src/CacheMagic/CachedObject.cs
@@ -9,7 +9,7 @@
     {
     	public T Value { get; private set; }

-    	public CachedObject<T>(T value)
+    	public CachedObject(T value)
     	{
     		Value = value;
     	}


Ejemplo de login con eco suprimido

Ejemplo de login con eco suprimido


Cleaning up duplicate storyboard creating code

--- src/Kliva/Extensions/ScrollViewerExtensions.cs
+++ src/Kliva/Extensions/ScrollViewerExtensions.cs
@@ -532,65 +532,35 @@

         #endregion

-        #region ScrollToHorizontalOffsetWithAnimation()
-        internal void ScrollToHorizontalOffsetWithAnimation(
-            double offset,
-            TimeSpan duration,
-            EasingFunctionBase easingFunction)
-        {
-            var sb = new Storyboard();
-            var da = new DoubleAnimation();
-            da.EnableDependentAnimation = true;
-            da.From = _scrollViewer.HorizontalOffset;
-            da.To = offset;
-            da.EasingFunction = easingFunction;
-            da.Duration = duration;
-            sb.Children.Add(da);
-            Storyboard.SetTarget(sb, _sliderHorizontal);
-            Storyboard.SetTargetProperty(da, "Value");
-            sb.Begin();
-        }
-        #endregion
-
-        #region ScrollToVerticalOffsetWithAnimation()
-        internal void ScrollToVerticalOffsetWithAnimation(
-            double offset,
-            TimeSpan duration,
-            EasingFunctionBase easingFunction)
-        {
-            var sb = new Storyboard();
-            var da = new DoubleAnimation();
-            da.EnableDependentAnimation = true;
-            da.From = _scrollViewer.VerticalOffset;
-            da.To = offset;
-            da.EasingFunction = easingFunction;
-            da.Duration = duration;
-            sb.Children.Add(da);
-            Storyboard.SetTarget(sb, _sliderVertical);
-            Storyboard.SetTargetProperty(da, "Value");
-            sb.Begin();
-        }
-        #endregion
-
-        #region ZoomToFactorWithAnimation()
-        internal void ZoomToFactorWithAnimation(
-            double factor,
-            TimeSpan duration,
-            EasingFunctionBase easingFunction)
-        {
-            var sb = new Storyboard();
-            var da = new DoubleAnimation();
-            da.EnableDependentAnimation = true;
-            da.From = _scrollViewer.ZoomFactor;
-            da.To = factor;
-            da.EasingFunction = easingFunction;
-            da.Duration = duration;
-            sb.Children.Add(da);
-            Storyboard.SetTarget(sb, _sliderZoom);
-            Storyboard.SetTargetProperty(da, "Value");
-            sb.Begin();
-        }
-        #endregion
+        internal void ScrollToHorizontalOffsetWithAnimation(double offset, TimeSpan duration, EasingFunctionBase easingFunction)
+        {
+            CreateAndStartStoryBoard(_sliderHorizontal, duration, easingFunction, _scrollViewer.HorizontalOffset, offset);
+        }
+
+        internal void ScrollToVerticalOffsetWithAnimation(double offset, TimeSpan duration, EasingFunctionBase easingFunction)
+        {
+            CreateAndStartStoryBoard(_sliderVertical, duration, easingFunction, _scrollViewer.VerticalOffset, offset);
+        }
+
+        internal void ZoomToFactorWithAnimation(double factor, TimeSpan duration, EasingFunctionBase easingFunction)
+        {
+            CreateAndStartStoryBoard(_sliderZoom, duration, easingFunction, _scrollViewer.ZoomFactor, factor);
+        }
+
+        private void CreateAndStartStoryBoard(DependencyObject dependencyObject, TimeSpan duration, EasingFunctionBase easingFunction,
+            double from, double to)
+        {
+            var storyboard = new Storyboard();
+            var doubleAnimation = new DoubleAnimation();
+            doubleAnimation.EnableDependentAnimation = true;
+            doubleAnimation.From = from;
+            doubleAnimation.To = to;
+            doubleAnimation.EasingFunction = easingFunction;
+            doubleAnimation.Duration = duration;
+            storyboard.Children.Add(doubleAnimation);
+            Storyboard.SetTarget(storyboard, dependencyObject);
+            Storyboard.SetTargetProperty(doubleAnimation, "Value");
+            storyboard.Begin();
+        }
     }
-
 }


Made TryGetHtmlBody() more generic to reuse it in MimeMessage.TextBody

--- MimeKit/MimeMessage.cs
+++ MimeKit/MimeMessage.cs
@@ -655,31 +655,7 @@
 			get; set;
 		}

-		/// <summary>
-		/// Gets the text body of the message if it exists.
-		/// </summary>
-		/// <remarks>
-		/// <para>Gets the text content of the first text/plain body part that is found (in depth-first
-		/// search order) which is not an attachment.</para>
-		/// </remarks>
-		/// <value>The text body if it exists; otherwise, <c>null</c>.</value>
-		public string TextBody {
-			get {
-				if (Body == null)
-					return null;
-
-				foreach (var part in BodyParts) {
-					var text = part as TextPart;
-
-					if (text != null && !text.IsAttachment && text.IsPlain)
-						return text.Text;
-				}
-
-				return null;
-			}
-		}
-
-		static bool TryGetHtmlBody (Multipart multipart, out string html)
+		static bool TryGetMessageBody (Multipart multipart, bool html, out string body)
 		{
 			var related = multipart as MultipartRelated;
 			TextPart part;
@@ -689,15 +665,15 @@
 				part = related.Root as TextPart;

 				if (part != null) {
-					html = part.IsHtml ? part.Text : null;
-					return html != null;
+					body = (html ? part.IsHtml : part.IsPlain) ? part.Text : null;
+					return body != null;
 				}

 				// maybe the root is another multipart (like multipart/alternative)?
 				var root = related.Root as Multipart;

-				if (root == null)
-					return TryGetHtmlBody (root, out html);
+				if (root != null)
+					return TryGetMessageBody (root, html, out body);
 			} else if (multipart.ContentType.Matches ("multipart", "alternative")) {
 				// walk the multipart/alternative children backwards from greatest level of faithfulness to the least faithful
 				for (int i = multipart.Count - 1; i >= 0; i--) {
@@ -709,8 +685,8 @@
 						part = multipart[i] as TextPart;
 					}

-					if (part != null && part.IsHtml) {
-						html = part.Text;
+					if (part != null && (html ? part.IsHtml : part.IsPlain)) {
+						body = part.Text;
 						return true;
 					}
 				}
@@ -720,22 +696,50 @@
 					var multi = multipart[i] as Multipart;

 					if (multi != null) {
-						if (TryGetHtmlBody (multi, out html))
+						if (TryGetMessageBody (multi, html, out body))
 							return true;
 					} else {
 						part = multipart[i] as TextPart;

-						if (part != null && part.IsHtml) {
-							html = part.Text;
+						if (part != null && (html ? part.IsHtml : part.IsPlain)) {
+							body = part.Text;
 							return true;
 						}
 					}
 				}
 			}

-			html = null;
+			body = null;

 			return false;
+		}
+
+		/// <summary>
+		/// Gets the text body of the message if it exists.
+		/// </summary>
+		/// <remarks>
+		/// <para>Gets the text content of the first text/plain body part that is found (in depth-first
+		/// search order) which is not an attachment.</para>
+		/// </remarks>
+		/// <value>The text body if it exists; otherwise, <c>null</c>.</value>
+		public string TextBody {
+			get {
+				var multipart = Body as Multipart;
+
+				if (multipart != null) {
+					string plain;
+
+					if (TryGetMessageBody (multipart, false, out plain))
+						return plain;
+				} else {
+					var part = Body as TextPart;
+
+					if (part != null && part.IsPlain)
+						return part.Text;
+				}
+
+				return null;
+			}
 		}

 		/// <summary>
@@ -752,7 +756,7 @@
 				if (multipart != null) {
 					string html;

-					if (TryGetHtmlBody (multipart, out html))
+					if (TryGetMessageBody (multipart, true, out html))
 						return html;
 				} else {
 					var part = Body as TextPart;


Dispatch command with commandline arguments

--- src/AppHarbor/Program.cs
+++ src/AppHarbor/Program.cs
@@ -14,6 +14,8 @@
 				.Install(new AppHarborInstaller());

 			var commandDispatcher = container.Resolve<CommandDispatcher>();
+
+			commandDispatcher.Dispatch(args);
 		}
 	}
 }