Ensured ComboBox is not closed when scrolling

Resolves issue #471

--- MaterialDesignThemes.Wpf/PopupBox.cs
+++ MaterialDesignThemes.Wpf/PopupBox.cs
@@ -659,6 +659,9 @@
                 {
                     if (popupBox.StaysOpen && popupBox.IsPopupOpen)
                     {
+            	        // Fix for ComboBox scrolling
+			if (GetCapture() != IntPtr.Zero) return;
+
                         // Take capture back because click happend outside of control
                         Mouse.Capture(popupBox, CaptureMode.SubTree);
                         e.Handled = true;


Undo breaking changes

Undo breaking changes

Undo breaking changes

--- Mindscape.Raygun4Net/RaygunClient.cs
+++ Mindscape.Raygun4Net/RaygunClient.cs
@@ -377,7 +377,7 @@

     private void Send(string message)
     {
-      if (HasValidApiKey())
+      if (ValidateApiKey())
       {
         RaygunLogger.Instance.Verbose("Sending Payload --------------");
         RaygunLogger.Instance.Verbose(message);
@@ -482,7 +482,7 @@
         return;
       }

-      if (!HasValidApiKey())
+      if (!ValidateApiKey())
       {
         RaygunLogger.Instance.Warning("Failed to save report due to invalid API key.");
         return;
@@ -507,7 +507,7 @@

     private void SendStoredMessages()
     {
-      if (!HasValidApiKey())
+      if (!ValidateApiKey())
       {
         RaygunLogger.Instance.Warning("Failed to send offline reports due to invalid API key.");
         return;
@@ -555,7 +555,7 @@

     #endregion // Message Offline Storage

-    protected bool HasValidApiKey()
+    protected bool ValidateApiKey()
     {
       return !string.IsNullOrEmpty(_apiKey);
     }


bpp is not always 4!

bpp is not always 4!

--- source/Cosmos.HAL2/Drivers/Video/VBEDriver.cs
+++ source/Cosmos.HAL2/Drivers/Video/VBEDriver.cs
@@ -84,7 +84,7 @@

                 var ModeInfo = VBE.getModeInfo();

-                if ((ModeInfo.pitch / 4) == ModeInfo.width) //linear framebuffer detection
+                if ((ModeInfo.pitch / (bpp / 8)) == ModeInfo.width) //linear framebuffer detection
                 {
                     IO.LinearFrameBuffer = new MemoryBlock(VBE.getLfbOffset(), (uint)xres * yres * (uint)(bpp / 8));
                     lastbuffer = new ManagedMemoryBlock((uint)xres * yres * (uint)(bpp / 8));


Fix infinite loop

Fix infinite loop

--- source/Htc.Vita.Core/IO/UsbManager.Windows.cs
+++ source/Htc.Vita.Core/IO/UsbManager.Windows.cs
@@ -108,11 +108,13 @@

                         if (string.IsNullOrWhiteSpace(devicePath))
                         {
+                            deviceIndex++;
                             continue;
                         }
                         if (!devicePath.Contains("VID_") && !devicePath.Contains("vid_"))
                         {
                             Logger.GetInstance(typeof(Windows)).Error($"Can not get valid HID device path: {devicePath}");
+                            deviceIndex++;
                             continue;
                         }

@@ -620,11 +622,13 @@

                         if (string.IsNullOrWhiteSpace(devicePath))
                         {
+                            deviceIndex++;
                             continue;
                         }
                         if (!devicePath.Contains("VID_") && !devicePath.Contains("vid_"))
                         {
                             Logger.GetInstance(typeof(Windows)).Error($"Can not get valid USB device path: {devicePath}");
+                            deviceIndex++;
                             continue;
                         }


remove IAuthenticationManagerExtensions

remove IAuthenticationManagerExtensions

--- source/Core/Extensions/IAuthenticationManagerExtensions.cs
+++ source/Core/Extensions/IAuthenticationManagerExtensions.cs
@@ -1,12 +0,0 @@
-/*
- * Copyright (c) Dominick Baier, Brock Allen.  All rights reserved.
- * see license
- */
-
-namespace Thinktecture.IdentityServer.Core.Extensions
-{
-    public static class IAuthenticationManagerExtensions
-    {
-
-    }
-}


Ensure we reset stream timeouts back to normal after heartbeats

--- source/Halibut/Transport/Protocol/MessageExchangeStream.cs
+++ source/Halibut/Transport/Protocol/MessageExchangeStream.cs
@@ -28,6 +28,7 @@
             streamWriter = new StreamWriter(stream, new UTF8Encoding(false));
             streamReader = new StreamReader(stream, new UTF8Encoding(false));
             serializer = Serializer();
+            SetNormalTimeouts();
         }

         public static Func<JsonSerializer> Serializer = CreateDefault;
@@ -40,16 +41,16 @@
             streamWriter.WriteLine();
             streamWriter.WriteLine();
             streamWriter.Flush();
-
             ExpectServerIdentity();
         }

         public void SendNext()
         {
-            stream.WriteTimeout = (int)HalibutLimits.TcpClientHeartbeatSendTimeout.TotalMilliseconds;
+            SetShortTimeouts();
             streamWriter.Write("NEXT");
             streamWriter.WriteLine();
             streamWriter.Flush();
+            SetNormalTimeouts();
         }

         public void SendProceed()
@@ -76,12 +77,13 @@

         public void ExpectProceeed()
         {
-            stream.ReadTimeout = (int) HalibutLimits.TcpClientHeartbeatReceiveTimeout.TotalMilliseconds;
+            SetShortTimeouts();
             var line = ReadLine();
             if (line == null)
                 throw new AuthenticationException("XYZ");
             if (line != "PROCEED")
                 throw new ProtocolException("Expected PROCEED, got: " + line);
+            SetNormalTimeouts();
         }

         string ReadLine()
@@ -302,5 +304,17 @@
         {
             public object Message { get; set; }
         }
+
+        void SetNormalTimeouts()
+        {
+            stream.WriteTimeout = (int)HalibutLimits.TcpClientHeartbeatSendTimeout.TotalMilliseconds;
+            stream.ReadTimeout = (int)HalibutLimits.TcpClientHeartbeatReceiveTimeout.TotalMilliseconds;
+        }
+
+        void SetShortTimeouts()
+        {
+            stream.WriteTimeout = (int)HalibutLimits.TcpClientSendTimeout.TotalMilliseconds;
+            stream.ReadTimeout = (int)HalibutLimits.TcpClientReceiveTimeout.TotalMilliseconds;
+        }
     }
 }


Use FlightGlobals.Bodies, suggestion from DMagic1

--- source/SCANsat-Notebook/NotebookController.cs
+++ source/SCANsat-Notebook/NotebookController.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using SCANsat;
 using SCANsat.SCAN_Data;

@@ -7,8 +8,6 @@
 	[KSPScenario(ScenarioCreationOptions.AddToAllGames | ScenarioCreationOptions.AddToExistingGames, GameScenes.FLIGHT, GameScenes.SPACECENTER, GameScenes.TRACKSTATION)]
 	public class NotebookController : ScenarioModule
 	{
-		internal string[] body_names = new string[] { "Kerbin", "Mun", "Minmus" };
-
 		public NotebookController ()
 		{
 		}
@@ -22,19 +21,24 @@
 		{
 			NotebookUtil.NotebookLog ("OnSave called");

-			foreach (string body_name in body_names)
+			List<CelestialBody> bodies = FlightGlobals.Bodies;
+			if (bodies == null)
 			{
-				SaveBody (body_name);
+				NotebookUtil.NotebookLog ("No Celestial Bodies found...");
+			}
+			else
+			{
+				foreach (CelestialBody body in bodies)
+				{
+					NotebookUtil.NotebookLog ("  body - name: {0}", body.bodyName);
+					NotebookUtil.NotebookLog ("  body - {0}", body);
+					SaveBody (body);
+				}
 			}
 		}

-		internal void SaveBody(string name)
+		internal void SaveBody(CelestialBody body)
 		{
-			NotebookUtil.NotebookLog ("Checking {0}", name);
-
-			CelestialBody body = new CelestialBody ();
-
-			NotebookUtil.NotebookLog ("Created Celestial Body {0}", name);
 			if (body == null)
 			{
 				NotebookUtil.NotebookLog ("  -- no body for: {0}: '{1}'", new Object[] { name, body });


switch не оптимизировал case'ы, из-за чего всё падало

--- NiL.JS/Statements/SwitchStatement.cs
+++ NiL.JS/Statements/SwitchStatement.cs
@@ -1,134 +1,134 @@
-using NiL.JS.Core;
-using System;
-using System.Collections.Generic;
-
-namespace NiL.JS.Statements
-{
-    internal class SwitchStatement : Statement, IOptimizable
-    {
-        private class Case
-        {
-            public int index;
-            public Statement statement;
-        }
-
-        private FunctionStatement[] functions;
-        private int length;
-        private readonly Statement[] body;
-        private Case[] cases;
-
-        public SwitchStatement(Statement[] body, double fictive)
-        {
-            this.body = body;
-            length = body.Length - 1;
-        }
-
-        public SwitchStatement(Statement[] body)
-        {
-            this.body = body;
-            length = body.Length - 1;
-            functions = new FunctionStatement[0];
-        }
-
-        internal static ParseResult Parse(ParsingState state, ref int index)
-        {
-            string code = state.Code;
-            int i = index;
-            if (!Parser.Validate(code, "switch (", ref i) && !Parser.Validate(code, "switch(", ref i))
-                return new ParseResult();
-            while (char.IsWhiteSpace(code[i])) i++;
-            var image = OperatorStatement.Parse(state, ref i).Statement;
-            if (code[i] != ')')
-                throw new ArgumentException("code (" + i + ")");
-            do i++; while (char.IsWhiteSpace(code[i]));
-            if (code[i] != '{')
-                throw new ArgumentException("code (" + i + ")");
-            do
-                i++;
-            while (char.IsWhiteSpace(code[i]));
-            var body = new List<Statement>();
-            var funcs = new List<FunctionStatement>();
-            var cases = new List<Case>();
-            cases.Add(null);
-            state.AllowBreak++;
-            while (code[i] != '}')
-            {
-                if (Parser.Validate(code, "case", ref i))
-                {
-                    do
-                        i++;
-                    while (char.IsWhiteSpace(code[i]));
-                    var sample = OperatorStatement.Parse(state, ref i).Statement;
-                    if (code[i] != ':')
-                        throw new ArgumentException("code (" + i + ")");
-                    i++;
-                    cases.Add(new Case() { index = body.Count, statement = new Operators.StrictEqual(image, sample) });
-                }
-                else if (Parser.Validate(code, "default", ref i))
-                {
-                    if (cases[0] != null)
-                        throw new InvalidOperationException("Duplicate default case in switch");
-                    if (code[i] != ':')
-                        throw new ArgumentException("code (" + i + ")");
-                    i++;
-                    cases[0] = new Case() { index = body.Count, statement = null };
-                }
-                if (cases.Count == 1 && cases[0] == null)
-                    throw new ArgumentException("code (" + i + ")");
-                var t = Parser.Parse(state, ref i, 0);
-                if (t == null)
-                    continue;
-                if (t is FunctionStatement)
-                    funcs.Add(t as FunctionStatement);
-                else
-                    body.Add(t);
-                while (char.IsWhiteSpace(code[i]) || (code[i] == ';')) i++;
-            };
-            state.AllowBreak--;
-            i++;
-            index = i;
-            return new ParseResult()
-            {
-                IsParsed = true,
-                Message = "",
-                Statement = new SwitchStatement(body.ToArray(), 0.0)
-                {
-                    functions = funcs.ToArray(),
-                    cases = cases.ToArray(),
-                }
-            };
-        }
-
-        public override JSObject Invoke(Context context)
-        {
-            if (functions != null)
-                throw new InvalidOperationException();
-            int i = cases[0].index;
-            for (int j = 1; j < cases.Length; j++)
-            {
-                if ((bool)cases[j].statement.Invoke(context))
-                {
-                    i = cases[j].index;
-                    break;
-                }
-            }
-            for (; i <= length; i++)
-            {
-                body[i].Invoke(context);
-                if (context.abort != AbortType.None)
-                {
-                    if (context.abort == AbortType.Break)
-                        context.abort = AbortType.None;
-                    return context.abortInfo;
-                }
-            }
-            return null;
-        }
-
+using NiL.JS.Core;
+using System;
+using System.Collections.Generic;
+
+namespace NiL.JS.Statements
+{
+    internal class SwitchStatement : Statement, IOptimizable
+    {
+        private class Case
+        {
+            public int index;
+            public Statement statement;
+        }
+
+        private FunctionStatement[] functions;
+        private int length;
+        private readonly Statement[] body;
+        private Case[] cases;
+
+        public SwitchStatement(Statement[] body, double fictive)
+        {
+            this.body = body;
+            length = body.Length - 1;
+        }
+
+        public SwitchStatement(Statement[] body)
+        {
+            this.body = body;
+            length = body.Length - 1;
+            functions = new FunctionStatement[0];
+        }
+
+        internal static ParseResult Parse(ParsingState state, ref int index)
+        {
+            string code = state.Code;
+            int i = index;
+            if (!Parser.Validate(code, "switch (", ref i) && !Parser.Validate(code, "switch(", ref i))
+                return new ParseResult();
+            while (char.IsWhiteSpace(code[i])) i++;
+            var image = OperatorStatement.Parse(state, ref i).Statement;
+            if (code[i] != ')')
+                throw new ArgumentException("code (" + i + ")");
+            do i++; while (char.IsWhiteSpace(code[i]));
+            if (code[i] != '{')
+                throw new ArgumentException("code (" + i + ")");
+            do
+                i++;
+            while (char.IsWhiteSpace(code[i]));
+            var body = new List<Statement>();
+            var funcs = new List<FunctionStatement>();
+            var cases = new List<Case>();
+            cases.Add(null);
+            state.AllowBreak++;
+            while (code[i] != '}')
+            {
+                if (Parser.Validate(code, "case", ref i))
+                {
+                    do
+                        i++;
+                    while (char.IsWhiteSpace(code[i]));
+                    var sample = OperatorStatement.Parse(state, ref i).Statement;
+                    if (code[i] != ':')
+                        throw new ArgumentException("code (" + i + ")");
+                    i++;
+                    cases.Add(new Case() { index = body.Count, statement = new Operators.StrictEqual(image, sample) });
+                }
+                else if (Parser.Validate(code, "default", ref i))
+                {
+                    if (cases[0] != null)
+                        throw new InvalidOperationException("Duplicate default case in switch");
+                    if (code[i] != ':')
+                        throw new ArgumentException("code (" + i + ")");
+                    i++;
+                    cases[0] = new Case() { index = body.Count, statement = null };
+                }
+                if (cases.Count == 1 && cases[0] == null)
+                    throw new ArgumentException("code (" + i + ")");
+                var t = Parser.Parse(state, ref i, 0);
+                if (t == null)
+                    continue;
+                if (t is FunctionStatement)
+                    funcs.Add(t as FunctionStatement);
+                else
+                    body.Add(t);
+                while (char.IsWhiteSpace(code[i]) || (code[i] == ';')) i++;
+            };
+            state.AllowBreak--;
+            i++;
+            index = i;
+            return new ParseResult()
+            {
+                IsParsed = true,
+                Message = "",
+                Statement = new SwitchStatement(body.ToArray(), 0.0)
+                {
+                    functions = funcs.ToArray(),
+                    cases = cases.ToArray(),
+                }
+            };
+        }
+
+        public override JSObject Invoke(Context context)
+        {
+            if (functions != null)
+                throw new InvalidOperationException();
+            int i = cases[0].index;
+            for (int j = 1; j < cases.Length; j++)
+            {
+                if ((bool)cases[j].statement.Invoke(context))
+                {
+                    i = cases[j].index;
+                    break;
+                }
+            }
+            for (; i <= length; i++)
+            {
+                body[i].Invoke(context);
+                if (context.abort != AbortType.None)
+                {
+                    if (context.abort == AbortType.Break)
+                        context.abort = AbortType.None;
+                    return context.abortInfo;
+                }
+            }
+            return null;
+        }
+
         public bool Optimize(ref Statement _this, int depth, System.Collections.Generic.Dictionary<string, Statement> varibles)
         {
             if (depth < 1)
-                throw new InvalidOperationException();
+                throw new InvalidOperationException();
             for (int i = 0; i < body.Length; i++)
                 Parser.Optimize(ref body[i], 1, varibles);
             for (int i = 0; i < functions.Length; i++)
@@ -138,8 +138,10 @@
                 varibles[functions[i].Name] = stat;
                 functions[i] = null;
             }
-            functions = null;
-            return false;
-        }
-    }
+            functions = null;
+            for (int i = 1; i < cases.Length; i++)
+                Parser.Optimize(ref cases[i].statement, 2, varibles);
+            return false;
+        }
+    }
 }


Normalize more efficiently

Normalize more efficiently

--- NtImageProcessor/HistogramCreator.cs
+++ NtImageProcessor/HistogramCreator.cs
@@ -19,7 +19,6 @@
             Resolution_32,
         };

-        public int MaxFrequency { get; set; }
         public int Resolution { get; set; }
         private HistogramResolution histogramResolution;

@@ -31,9 +30,8 @@
             set;
         }

-        public HistogramCreator(HistogramResolution resolution, int maxFrequency)
+        public HistogramCreator(HistogramResolution resolution)
         {
-            MaxFrequency = maxFrequency;
             histogramResolution = resolution;
             switch (resolution)
             {
@@ -99,9 +97,10 @@
         private void CalculateHistogram(WriteableBitmap writableBitmap)
         {

-            foreach (int v in writableBitmap.Pixels)
+            //foreach (int v in writableBitmap.Pixels)
+            for (int i = 0; i < writableBitmap.Pixels.Length; i += 13)
             {
-                int value = v;
+                int value = writableBitmap.Pixels[i];

                 int b = (value & 0xFF);
                 value = value >> 8;
@@ -120,18 +119,16 @@
                 green[g]++;
                 blue[b]++;
             }
-
+
             // normalize values.
-            double scaleFactor = (double)MaxFrequency / (double)writableBitmap.Pixels.Length;
-            // Debug.WriteLine("scale: " + scaleFactor);
-
+
             for (int i = 0; i < Resolution; i++)
             {
-                red[i] = (int)((double)red[i] * scaleFactor);
-                green[i] = (int)((double)green[i] * scaleFactor);
-                blue[i] = (int)((double)blue[i] * scaleFactor);
+                red[i] = red[i] >> 2;
+                green[i] = green[i] >> 2;
+                blue[i] = blue[i] >> 2;
             }
-
+
             if (OnHistogramCreated != null)
             {
                 OnHistogramCreated(red, green, blue);


routes: add standard controller/id route

--- NuCache/App_Start/ConfigureRoutes.cs
+++ NuCache/App_Start/ConfigureRoutes.cs
@@ -56,6 +56,12 @@
 			);

 			config.Routes.MapHttpRoute(
+				name: "Standard",
+				routeTemplate: "{controller}/{id}",
+				defaults: new { id = UrlParameter.Optional }
+			);
+
+			config.Routes.MapHttpRoute(
 				name: "Error404",
 				routeTemplate: "{*url}",
 				defaults: new { controller = "Error", action = "Handle404" }


Update DummyClient.cs

Update DummyClient.cs

#1133

--- source/plugin/Assets/GoogleMobileAds/Common/DummyClient.cs
+++ source/plugin/Assets/GoogleMobileAds/Common/DummyClient.cs
@@ -73,6 +73,7 @@
         public void Initialize(Action<InitializationStatus> initCompleteAction)
         {
             Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
+            initCompleteAction();
         }

         public void SetApplicationMuted(bool muted)


Fix the two-way binding for grammar and test text.

--- Pegasus.Workbench/MainWindow.xaml.cs
+++ Pegasus.Workbench/MainWindow.xaml.cs
@@ -43,10 +43,10 @@

             this.ViewModel.PropertyChanged += (s, e) =>
             {
-                if (e.PropertyName == "Text" && !updatingGrammar)
+                if (e.PropertyName == "GrammarText" && !updatingGrammar)
                 {
                     updatingGrammar = true;
-                    this.GrammarEditor.Text = this.ViewModel.GrammarText;
+                    Dispatcher.Invoke(() => { this.GrammarEditor.Text = this.ViewModel.GrammarText; });
                     updatingGrammar = false;
                 }
             };
@@ -64,10 +64,10 @@

             this.ViewModel.PropertyChanged += (s, e) =>
             {
-                if (e.PropertyName == "Text" && !updatingTest)
+                if (e.PropertyName == "TestText" && !updatingTest)
                 {
                     updatingTest = true;
-                    this.TestEditor.Text = this.ViewModel.TestText;
+                    Dispatcher.Invoke(() => { this.TestEditor.Text = this.ViewModel.TestText; });
                     updatingTest = false;
                 }
             };


update

update

--- Plugins/Wox.Plugin.WebSearch/Main.cs
+++ Plugins/Wox.Plugin.WebSearch/Main.cs
@@ -167,4 +167,4 @@

         public event ResultUpdatedEventHandler ResultsUpdated;
     }
-}
+}


[KOE-113] Made restarter retry several times if there's an exception while removing the store. Also now logs the version on start.

--- src/AcaciaZPushPlugin/OutlookRestarter/OutlookRestarter.cs
+++ src/AcaciaZPushPlugin/OutlookRestarter/OutlookRestarter.cs
@@ -28,6 +28,9 @@
 {
     class OutlookRestarter
     {
+        private const int FINISH_WAIT_TIME = 15000;
+        private const int DELETE_RETRIES = 30;
+        private const int DELETE_WAIT_TIME = 500;

         /// <summary>
         /// Entry point.
@@ -41,7 +44,7 @@
         [STAThread]
         static void Main(string[] args)
         {
-            Logger.Instance.Debug(typeof(OutlookRestarter), "Restarting: {0}", string.Join(", ", args));
+            Logger.Instance.Debug(typeof(OutlookRestarter), "Restarting: {0}: {1}", BuildVersions.VERSION, string.Join(", ", args));

             string procPath = args[1];
             List<string> procArgs = args.Skip(2).ToList();
@@ -51,7 +54,7 @@
                 int procId = int.Parse(args[0]);
                 Process proc = Process.GetProcessById(procId);
                 Logger.Instance.Debug(typeof(OutlookRestarter), "Waiting for process to exit: {0}: {1}", procId, proc);
-                bool finished = proc.WaitForExit(15000);
+                bool finished = proc.WaitForExit(FINISH_WAIT_TIME);
                 Logger.Instance.Debug(typeof(OutlookRestarter), "Waited for process to exit: {0}: {1}", procId, finished);
             }
             finally
@@ -68,14 +71,29 @@
                         if (System.IO.Path.GetExtension(path) == ".ost")
                         {
                             Logger.Instance.Info(typeof(OutlookRestarter), "Removing store: {0}", path);
-                            // Delete it
-                            try
+
+                            for (int attempt = 0; attempt < DELETE_RETRIES; ++attempt)
                             {
-                                System.IO.File.Delete(path);
-                            }
-                            catch (Exception e)
-                            {
-                                Logger.Instance.Error(typeof(OutlookRestarter), "Exception removing store: {0}: {1}", path, e);
+                                // Delete it
+                                try
+                                {
+                                    System.IO.File.Delete(path);
+
+                                    // Success, done
+                                    break;
+                                }
+                                catch (IOException e)
+                                {
+                                    Logger.Instance.Error(typeof(OutlookRestarter), "IOException removing store: {0}: on attempt {1}: {2}", path, attempt, e);
+                                    // IO Exception. Wait a while and retry
+                                    Thread.Sleep(DELETE_WAIT_TIME);
+                                }
+                                catch (Exception e)
+                                {
+                                    Logger.Instance.Error(typeof(OutlookRestarter), "Exception removing store: {0}: {1}", path, e);
+                                    // This kind of exception will not be resolved by retrying
+                                    break;
+                                }
                             }
                         }
                     }


Pumped up the version

Pumped up the version

--- src/ActionMailerNext.Standalone/Properties/AssemblyInfo.cs
+++ src/ActionMailerNext.Standalone/Properties/AssemblyInfo.cs
@@ -38,6 +38,6 @@
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]

-[assembly: AssemblyInformationalVersion("2.1.3-rc")]
+[assembly: AssemblyInformationalVersion("2.1.4-rc")]
 [assembly: AssemblyFileVersion("2.1.0")]
 [assembly: AssemblyVersion("2.1.0")]


optimize StringLengthValidationRule

optimize StringLengthValidationRule

--- src/Caliburn.Core/Validation/StringLengthValidationRule.cs
+++ src/Caliburn.Core/Validation/StringLengthValidationRule.cs
@@ -35,12 +35,32 @@
             var length = 0;

             if (!string.IsNullOrEmpty(value))
-                length = value.Trim().Length;
-
+                length = GetTrimmedLength(value);
+
             if (length < _minimumLength || length > _maximumLength)
                 return ValidationResult.Failure(cultureInfo, _errorMessage, _minimumLength, _maximumLength, length);

             return ValidationResult.Success();
         }
+
+        private static int GetTrimmedLength(string value)
+        {
+            //end will point to the first non-trimmed character on the right
+            //start will point to the first non-trimmed character on the Left
+            var end = value.Length - 1;
+            var start = 0;
+
+            for (; start < value.Length; start++)
+            {
+                if (!char.IsWhiteSpace(value[start])) break;
+            }
+
+            for (; end >= start; end--)
+            {
+                if (!char.IsWhiteSpace(value[end])) break;
+            }
+
+            return end - start + 1;
+        }
     }
 }


Update TextDrawNode.cs

Update TextDrawNode.cs

--- src/Core2D/Modules/Renderer/Avalonia/Nodes/TextDrawNode.cs
+++ src/Core2D/Modules/Renderer/Avalonia/Nodes/TextDrawNode.cs
@@ -36,7 +36,7 @@

         if (Text.TopLeft is { } && Text.BottomRight is { })
         {
-            var rect2 = Rect2.FromPoints(Text.TopLeft.X, Text.TopLeft.Y, Text.BottomRight.X, Text.BottomRight.Y, 0, 0);
+            var rect2 = Rect2.FromPoints(Text.TopLeft.X, Text.TopLeft.Y, Text.BottomRight.X, Text.BottomRight.Y);
             Rect = new A.Rect(rect2.X, rect2.Y, rect2.Width, rect2.Height);
             Center = Rect.Center;
         }
@@ -51,15 +51,21 @@

     private void UpdateTextGeometry()
     {
-        BoundText = Text.GetProperty(nameof(TextShapeViewModel.Text)) is string boundText ? boundText : Text.Text;
+        BoundText = Text.GetProperty(nameof(TextShapeViewModel.Text)) as string ?? Text.Text;

-        if (BoundText is null)
+        if (BoundText is null || Style?.TextStyle is null)
         {
+            Origin = new A.Point();
+            FormattedText = null;
+            Geometry = null;
             return;
         }

         if (Style.TextStyle.FontSize < 0.0)
         {
+            Origin = new A.Point();
+            FormattedText = null;
+            Geometry = null;
             return;
         }

@@ -79,24 +85,30 @@
         // TODO: Cache Typeface
         // TODO: Cache FormattedText

-        Typeface = new AM.Typeface(Style.TextStyle.FontName, fontStyle, fontWeight);
-        if (Typeface is null)
+        if (string.IsNullOrEmpty(Style.TextStyle.FontName))
         {
-            Typeface = AM.Typeface.Default;
+            Typeface = null;
+        }
+        else
+        {
+            Typeface = new AM.Typeface(Style.TextStyle.FontName, fontStyle, fontWeight);
         }

-        var textAlignment = Style.TextStyle.TextHAlignment switch
-        {
-            TextHAlignment.Right => AM.TextAlignment.Right,
-            TextHAlignment.Center => AM.TextAlignment.Center,
-            _ => AM.TextAlignment.Left,
-        };
+        Typeface ??= AM.Typeface.Default;

         if (Stroke is null)
         {
             UpdateStyle();
         }
-
+
+        if (Stroke?.Brush is null)
+        {
+            Origin = new A.Point();
+            FormattedText = null;
+            Geometry = null;
+            return;
+        }
+
         FormattedText = new AM.FormattedText(
             BoundText,
             CultureInfo.InvariantCulture,
@@ -141,7 +153,7 @@
             return;
         }

-        if (Geometry is { })
+        if (Stroke?.Brush is { } && Geometry?.PlatformImpl is { })
         {
             // context.DrawGeometry(Text.IsFilled ? Fill : null, Text.IsStroked ? Stroke : null, Geometry.PlatformImpl);
             context.DrawGeometry(Stroke.Brush, null, Geometry.PlatformImpl);


Added 'poison message' protection to OCR Worker Role.

--- src/AzureCloudOCR/OCRWorkerRole/WorkerRole.cs
+++ src/AzureCloudOCR/OCRWorkerRole/WorkerRole.cs
@@ -17,6 +17,7 @@
     {
         private bool onStopCalled;
         private bool returnedFromRunMethod;
+        private const int maxSingleMessageDequeueCount = 10;

         public override void Run()
         {
@@ -38,7 +39,7 @@
                 var ocrQueueRequestOptions = new QueueRequestOptions
                 {
                     MaximumExecutionTime = TimeSpan.FromMinutes(15),
-                    RetryPolicy = new LinearRetry(TimeSpan.FromMinutes(5), 5)
+                    RetryPolicy = new LinearRetry(TimeSpan.FromMinutes(1), 5)
                 };

                 while (true)
@@ -105,6 +106,14 @@
         {
             string messageContent = queueMessage.AsString;
             Trace.TraceInformation("Processing OCR queue message: " + messageContent);
+
+            // To protect from accidental poison messages that get stuck in the queue.
+            if (queueMessage.DequeueCount > maxSingleMessageDequeueCount)
+            {
+                Trace.TraceInformation("Message max dequeue limit reached. Deleting it as a poison message.");
+                AzureQueues.OCRQueue.DeleteMessage(queueMessage);
+                return;
+            }

             string blobName;
             string recipientEmail;


Created some constants to represent the names of the batch operations so we don't pass around magic strings.

--- src/AzureCloudTable.Api/TableAccessContext.cs
+++ src/AzureCloudTable.Api/TableAccessContext.cs
@@ -7,6 +7,8 @@

 namespace AzureCloudTableContext.Api
 {
+    using System.Threading.Tasks;
+
     /// <summary>
     /// Class that provides direct interaction to the current Azure Table through commonly used techniques.
     /// Uses a generic object that implements the ITableEntity interface. This class can be used in
@@ -51,6 +53,12 @@
             _table.Execute(updateOperation);
         }

+        public async Task InsertOrMergeAsync(TAzureTableEntity tableEntity)
+        {
+            var updateOperation = TableOperation.InsertOrMerge(tableEntity);
+            await _table.ExecuteAsync(updateOperation);
+        }
+
         /// <summary>
         /// Executes a batch table operation of the same name on an array of <param name="entities"></param>. Insures that
         /// that the batch meets Azure Table requrirements for Entity Group Transactions (i.e. batch no larger than 4MB or
@@ -60,6 +68,11 @@
         public void InsertOrMerge(TAzureTableEntity[] entities)
         {
             ExecuteBatchOperation(entities, "InsertOrMerge");
+        }
+
+        public async Task InsertOrMergeAsync(TAzureTableEntity[] entities)
+        {
+            await ExecuteBatchOperationAsync(entities, "InsertOrMerge");
         }

         /// <summary>
@@ -575,10 +588,20 @@
                 case "Delete":
                     tableBatchOperation.Delete(entity);
                     break;
-                case "Replace":
+                case OperationNames.Replace:
                     tableBatchOperation.Replace(entity);
                     break;
             }
         }
     }
+
+    internal class OperationNames
+    {
+        internal const string Insert = "Insert";
+        internal const string InsertOrMerge  = "InsertOrMerge";
+        internal const string InsertOrReplace = "InsertOrReplace";
+        internal const string Merge  = "Merge";
+        internal const string Delete = "Delete";
+        internal const string Replace  = "Replace";
+    }
 }


* BOO-913: Ensures that there is a parent namespace before attempting to enter it.

git-svn-id: fcce7d6ce0ac15bf24f68871b5145d46fc068279@2787 2c1201b4-01cd-e047-a400-b836ae1fbc61

--- src/Boo.Lang.Compiler/Steps/BindNamespaces.cs
+++ src/Boo.Lang.Compiler/Steps/BindNamespaces.cs
@@ -58,8 +58,11 @@
 			IEntity entity = null;
 			try
 			{
-				NameResolutionService.EnterNamespace(NameResolutionService.CurrentNamespace.ParentNamespace);
-				entity = NameResolutionService.ResolveQualifiedName(import.Namespace);
+				if(NameResolutionService.CurrentNamespace.ParentNamespace != null)
+				{
+					NameResolutionService.EnterNamespace(NameResolutionService.CurrentNamespace.ParentNamespace);
+					entity = NameResolutionService.ResolveQualifiedName(import.Namespace);
+				}
 			}
 			finally
 			{


Fix an issue where comparing directories was falling crashing because the before iterator finished before the after iterator.

--- src/CodeDiffLib/DiffEngines/StringListDiff.cs
+++ src/CodeDiffLib/DiffEngines/StringListDiff.cs
@@ -33,7 +33,7 @@
                 // since the files are sorted, if one is greater than the other, it means the file is not there.
                 if (beforeEnumeratorStillValid && StringComparer.OrdinalIgnoreCase.Compare(beforeEnumerator.Current, afterEnumerator.Current) < 0)
                 {
-                    while (StringComparer.OrdinalIgnoreCase.Compare(beforeEnumerator.Current, afterEnumerator.Current) < 0)
+                    while (beforeEnumeratorStillValid && StringComparer.OrdinalIgnoreCase.Compare(beforeEnumerator.Current, afterEnumerator.Current) < 0)
                     {
                         yield return new Change<string>(beforeEnumerator.Current, null, ChangeType.Removed);
                         beforeEnumeratorStillValid = beforeEnumerator.MoveNext();


Use string.Create in BitConverter.ToString(byte[]) (dotnet/coreclr#15218)

Avoids unnecessary allocations and copying, and reduces the amount of unsafe code.

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

--- src/Common/src/CoreLib/System/BitConverter.cs
+++ src/Common/src/CoreLib/System/BitConverter.cs
@@ -354,17 +354,6 @@
             return Unsafe.ReadUnaligned<double>(ref value.DangerousGetPinnableReference());
         }

-        private static char GetHexValue(int i)
-        {
-            Debug.Assert(i >= 0 && i < 16, "i is out of range.");
-            if (i < 10)
-            {
-                return (char)(i + '0');
-            }
-
-            return (char)(i - 10 + 'A');
-        }
-
         // Converts an array of bytes into a String.
         public static string ToString(byte[] value, int startIndex, int length)
         {
@@ -388,41 +377,27 @@
                 throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
             }

-            int chArrayLength = length * 3;
-            const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation
-            unsafe
+            return string.Create(length * 3 - 1, (value, startIndex, length), (dst, state) =>
             {
-                if (chArrayLength < StackLimit)
+                const string HexValues = "0123456789ABCDEF";
+
+                var src = new ReadOnlySpan<byte>(state.value, state.startIndex, state.length);
+
+                int i = 0;
+                int j = 0;
+
+                byte b = src[i++];
+                dst[j++] = HexValues[b >> 4];
+                dst[j++] = HexValues[b & 0xF];
+
+                while (i < src.Length)
                 {
-                    char* chArrayPtr = stackalloc char[chArrayLength];
-                    return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
+                    b = src[i++];
+                    dst[j++] = '-';
+                    dst[j++] = HexValues[b >> 4];
+                    dst[j++] = HexValues[b & 0xF];
                 }
-                else
-                {
-                    char[] chArray = new char[chArrayLength];
-                    fixed (char* chArrayPtr = &chArray[0])
-                        return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
-                }
-            }
-        }
-
-        private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)
-        {
-            Debug.Assert(length > 0);
-            Debug.Assert(chArrayLength == length * 3);
-
-            char* p = chArray;
-            int endIndex = startIndex + length;
-            for (int i = startIndex; i < endIndex; i++)
-            {
-                byte b = value[i];
-                *p++ = GetHexValue(b >> 4);
-                *p++ = GetHexValue(b & 0xF);
-                *p++ = '-';
-            }
-
-            // We don't need the last '-' character
-            return new string(chArray, 0, chArrayLength - 1);
+            });
         }

         // Converts an array of bytes into a String.


Whitespace.

Whitespace.

--- src/Extensions/Icarus/Gallio.Icarus/Filters/FiltersView.cs
+++ src/Extensions/Icarus/Gallio.Icarus/Filters/FiltersView.cs
@@ -90,6 +90,5 @@
             var filterInfo = (FilterInfo)filtersListBox.SelectedItem;
             filterController.ApplyFilter(filterInfo.FilterExpr);
         }
-
     }
 }


Maintenance: use modern C#

Maintenance: use modern C#

--- src/Core/Translate/TypeReferenceTranslator.cs
+++ src/Core/Translate/TypeReferenceTranslator.cs
@@ -235,24 +235,24 @@
             return (elementTypes, namespaces);
         }

-        private ISet<string>? Join(ISet<string>? a, ISet<string>? b)
-        {
-            if (a == null && b == null)
+        private static ISet<string>? Join(ISet<string>? a, ISet<string>? b)
+        {
+            if (a is null && b is null)
                 return null;
-            if (a == null)
+            if (a is null)
                 return b;
-            if (b == null)
+            if (b is null)
                 return a;
             var result = new HashSet<string>(a);
             result.UnionWith(b);
             return result;
         }

-        private ISet<string>? Join(ISet<string>? a, string b)
-        {
-            if (b == null)
+        private static ISet<string>? Join(ISet<string>? a, string b)
+        {
+            if (b is null)
                 return a;
-            if (a == null)
+            if (a is null)
                 return new HashSet<string> { b };
             a.Add(b);
             return a;


adding new test coverage project

adding new test coverage project

--- src/Couchbase.Lite/Properties/AssemblyInfo.cs
+++ src/Couchbase.Lite/Properties/AssemblyInfo.cs
@@ -43,4 +43,5 @@
 [assembly: InternalsVisibleTo("Couchbase.Lite.Tests.Android")]
 [assembly: InternalsVisibleTo("Couchbase.Lite.Support.NetDesktop")]
 [assembly: InternalsVisibleTo("Couchbase.Lite.Tests.NetCore")]
+[assembly: InternalsVisibleTo("Couchbase.Lite.TestCoverage")]
 #endif


Default model binder instance

Default model binder instance

--- src/Dolstagis.Web/ModelBinding/ModelBinder.cs
+++ src/Dolstagis.Web/ModelBinding/ModelBinder.cs
@@ -21,6 +21,13 @@
             new StringConverter(),
             new ObjectConverter(() => defaultConverters)
         };
+
+        public static ModelBinder Default { get; private set; }
+
+        static ModelBinder()
+        {
+            Default = new ModelBinder();
+        }

         public IConverter[] Converters { get; set; }


Fixed a bug where MaintainAsync would fail with no indexes.

--- src/Elasticsearch/Configuration/DailyIndex.cs
+++ src/Elasticsearch/Configuration/DailyIndex.cs
@@ -210,11 +210,17 @@
                 return;

             var indexes = await GetIndexesAsync().AnyContext();
+            if (indexes.Count == 0)
+                return;
+
             await UpdateAliasesAsync(indexes).AnyContext();
             await DeleteOldIndexesAsync(indexes).AnyContext();
         }

         protected virtual async Task UpdateAliasesAsync(IList<IndexInfo> indexes) {
+            if (indexes.Count == 0)
+                return;
+
             var aliasDescriptor = new AliasDescriptor();
             foreach (var indexGroup in indexes.OrderBy(i => i.Version).GroupBy(i => i.DateUtc)) {
                 var indexExpirationDate = GetIndexExpirationDate(indexGroup.Key);
@@ -258,7 +264,7 @@
         }

         protected virtual async Task DeleteOldIndexesAsync(IList<IndexInfo> indexes) {
-            if (!MaxIndexAge.HasValue || MaxIndexAge <= TimeSpan.Zero)
+            if (indexes.Count == 0 || !MaxIndexAge.HasValue || MaxIndexAge <= TimeSpan.Zero)
                 return;

             var sw = new Stopwatch();


added TryAndWaitUntil method

added TryAndWaitUntil method

--- src/FluentBrowserAutomation/BrowserContext.cs
+++ src/FluentBrowserAutomation/BrowserContext.cs
@@ -82,6 +82,9 @@
 		TextBoxWrapper TextBoxWithLabel([NotNull] string label);
 		IEnumerable<TextBoxWrapper> TextBoxes();
 		IBrowserContext WaitUntil([NotNull] Func<IBrowserContext, bool> func, int secondsToWait = 10, string errorMessage = null);
+	    IBrowserContext TryAndWaitUntil([NotNull] Func<IBrowserContext, bool> func,
+	        [NotNull] Func<IBrowserContext, bool> waitOn, int secondsToWait = 5, int totalNumberOfRetries = 1,
+	        string errorMessage = null);
 	}

 	public class BrowserContext : IBrowserContext
@@ -577,6 +580,49 @@
 			throw new AssertionException(errorMessage ?? "state being waited upon never happened.");
 		}

+        public IBrowserContext TryAndWaitUntil(Func<IBrowserContext, bool> func, Func<IBrowserContext, bool> waitOn, int secondsToWait = 5, int totalNumberOfRetries = 1, string errorMessage = null)
+		{
+		    int numberOfTries = 0;
+            Exception caughtException = null;
+
+            while (numberOfTries < totalNumberOfRetries)
+            {
+                func(this);
+
+                var stopwatch = new Stopwatch();
+                stopwatch.Start();
+                do
+                {
+                    try
+                    {
+                        if (waitOn(this))
+                        {
+                            return this;
+                        }
+                    }
+                        // ReSharper disable once EmptyGeneralCatchClause
+                    catch (Exception exception)
+                    {
+                        caughtException = exception;
+                    }
+                    Thread.Sleep(TimeSpan.FromSeconds(.25));
+                } while (stopwatch.Elapsed.TotalSeconds < secondsToWait);
+
+                numberOfTries++;
+            }
+
+            if (caughtException != null)
+            {
+                if (errorMessage != null)
+                {
+                    throw new ArgumentException(
+                        "WaitUntil '" + errorMessage + "' caught: " + caughtException.Message, caughtException);
+                }
+                throw new ArgumentException(caughtException.Message, caughtException);
+            }
+            throw new AssertionException(errorMessage ?? "state being waited upon never happened.");
+		}
+
 		public string BaseUrl
 		{
 			get { return _browserManager.BaseUrl; }


~commit

~commit

--- src/Joke.Web/Controllers/AccountController.cs
+++ src/Joke.Web/Controllers/AccountController.cs
@@ -112,6 +112,7 @@
         public ActionResult UpdateJoke(int jokeid)
         {
             var jokeinfo = jokeLogic.JokeDetailGet(jokeid);
+            ////
             return View(jokeinfo);
         }
     }


Sessions back

Sessions back

--- src/Leto.Windows/WindowsSecurePipeListener.cs
+++ src/Leto.Windows/WindowsSecurePipeListener.cs
@@ -18,7 +18,7 @@
         public WindowsSecurePipeListener(ICertificate certificate, PipeFactory pipeFactory = null)
             :base(certificate, pipeFactory)
         {
-            //_sessionProvider = new Sessions.EphemeralSessionProvider();
+            _sessionProvider = new Sessions.EphemeralSessionProvider();
             _cryptoProvider = new WindowsCryptoProvider();
         }


Lucene.Net.Analysis.OpenNLP.Tools.OpenNLPOpsFactory: Simplified logic by using GetOrAdd() instead of TryGetValue. See #417.

--- src/Lucene.Net.Analysis.OpenNLP/Tools/OpenNLPOpsFactory.cs
+++ src/Lucene.Net.Analysis.OpenNLP/Tools/OpenNLPOpsFactory.cs
@@ -7,7 +7,6 @@
 using opennlp.tools.sentdetect;
 using opennlp.tools.tokenize;
 using System.Collections.Concurrent;
-using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
 using System.Text;
@@ -37,13 +36,13 @@
     /// </summary>
     public static class OpenNLPOpsFactory // LUCENENET: Made static because all members are static
     {
-        private static readonly IDictionary<string, SentenceModel> sentenceModels = new ConcurrentDictionary<string, SentenceModel>();
+        private static readonly ConcurrentDictionary<string, SentenceModel> sentenceModels = new ConcurrentDictionary<string, SentenceModel>();
         private static readonly ConcurrentDictionary<string, TokenizerModel> tokenizerModels = new ConcurrentDictionary<string, TokenizerModel>();
         private static readonly ConcurrentDictionary<string, POSModel> posTaggerModels = new ConcurrentDictionary<string, POSModel>();
         private static readonly ConcurrentDictionary<string, ChunkerModel> chunkerModels = new ConcurrentDictionary<string, ChunkerModel>();
-        private static readonly IDictionary<string, TokenNameFinderModel> nerModels = new ConcurrentDictionary<string, TokenNameFinderModel>();
-        private static readonly IDictionary<string, LemmatizerModel> lemmatizerModels = new ConcurrentDictionary<string, LemmatizerModel>();
-        private static readonly IDictionary<string, string> lemmaDictionaries = new ConcurrentDictionary<string, string>();
+        private static readonly ConcurrentDictionary<string, TokenNameFinderModel> nerModels = new ConcurrentDictionary<string, TokenNameFinderModel>();
+        private static readonly ConcurrentDictionary<string, LemmatizerModel> lemmatizerModels = new ConcurrentDictionary<string, LemmatizerModel>();
+        private static readonly ConcurrentDictionary<string, string> lemmaDictionaries = new ConcurrentDictionary<string, string>();

         public static NLPSentenceDetectorOp GetSentenceDetector(string modelName)
         {
@@ -60,15 +59,12 @@

         public static SentenceModel GetSentenceModel(string modelName, IResourceLoader loader)
         {
-            if (!sentenceModels.TryGetValue(modelName, out SentenceModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return sentenceModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new SentenceModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                sentenceModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new SentenceModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         public static NLPTokenizerOp GetTokenizer(string modelName)
@@ -86,15 +82,12 @@

         public static TokenizerModel GetTokenizerModel(string modelName, IResourceLoader loader)
         {
-            if (!tokenizerModels.TryGetValue(modelName, out TokenizerModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return tokenizerModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new TokenizerModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                tokenizerModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new TokenizerModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         public static NLPPOSTaggerOp GetPOSTagger(string modelName)
@@ -105,15 +98,12 @@

         public static POSModel GetPOSTaggerModel(string modelName, IResourceLoader loader)
         {
-            if (!posTaggerModels.TryGetValue(modelName, out POSModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return posTaggerModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new POSModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                posTaggerModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new POSModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         public static NLPChunkerOp GetChunker(string modelName)
@@ -124,15 +114,12 @@

         public static ChunkerModel GetChunkerModel(string modelName, IResourceLoader loader)
         {
-            if (!chunkerModels.TryGetValue(modelName, out ChunkerModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return chunkerModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new ChunkerModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                chunkerModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new ChunkerModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         public static NLPNERTaggerOp GetNERTagger(string modelName)
@@ -143,15 +130,12 @@

         public static TokenNameFinderModel GetNERTaggerModel(string modelName, IResourceLoader loader)
         {
-            if (!nerModels.TryGetValue(modelName, out TokenNameFinderModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return nerModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new TokenNameFinderModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                nerModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new TokenNameFinderModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         public static NLPLemmatizerOp GetLemmatizer(string dictionaryFile, string lemmatizerModelFile)
@@ -169,7 +153,8 @@

         public static string GetLemmatizerDictionary(string dictionaryFile, IResourceLoader loader)
         {
-            if (!lemmaDictionaries.TryGetValue(dictionaryFile, out string dictionary) || dictionary == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return lemmaDictionaries.GetOrAdd(dictionaryFile, (dictionaryFile) =>
             {
                 using TextReader reader = new StreamReader(loader.OpenResource(dictionaryFile), Encoding.UTF8);
                 StringBuilder builder = new StringBuilder();
@@ -183,23 +168,18 @@
                         builder.Append(chars, 0, numRead);
                     }
                 } while (numRead > 0);
-                dictionary = builder.ToString();
-                lemmaDictionaries[dictionaryFile] = dictionary;
-            }
-            return dictionary;
+                return builder.ToString();
+            });
         }

         public static LemmatizerModel GetLemmatizerModel(string modelName, IResourceLoader loader)
         {
-            if (!lemmatizerModels.TryGetValue(modelName, out LemmatizerModel model) || model == null)
+            // LUCENENET: Two competing threads in the add operation is okay as per the original implementation
+            return lemmatizerModels.GetOrAdd(modelName, (modelName) =>
             {
-                using (Stream resource = loader.OpenResource(modelName))
-                {
-                    model = new LemmatizerModel(new ikvm.io.InputStreamWrapper(resource));
-                }
-                lemmatizerModels[modelName] = model;
-            }
-            return model;
+                using Stream resource = loader.OpenResource(modelName);
+                return new LemmatizerModel(new ikvm.io.InputStreamWrapper(resource));
+            });
         }

         // keeps unit test from blowing out memory


We only create the List<string> for allowed values in StateVariable when we are about to need it for deserialization. This means the IEnumerable<T> will be null if no allowed values are specified in the XML. I'm not entirely sure if this is the right thing to do because the only benefit is that it allows you to distinguish between an empty <allowedValueList/> and no <allowedValueList/>. I don't expect any service state variable to have an empty list and it is usually a bad idea to have a null IEnumerable member b/c most people expect to be able to foreach over any IEnumerable, but making the distinction allows us to cope with such a situation if it ever arrises.

--- src/Mono.Upnp/Mono.Upnp/Mono.Upnp.Control/StateVariable.cs
+++ src/Mono.Upnp/Mono.Upnp/Mono.Upnp.Control/StateVariable.cs
@@ -38,7 +38,7 @@
     public class StateVariable : XmlAutomatable
     {
         readonly ServiceController controller;
-        readonly IList<string> allowed_values;
+        IList<string> allowed_values;
         //event EventHandler<StateVariableChangedArgs<string>> changed;

         protected internal StateVariable (ServiceController service)
@@ -46,7 +46,6 @@
             if (service == null) throw new ArgumentNullException ("service");

             this.controller = service;
-            allowed_values = new List<string> ();
         }

         public ServiceController Controller {
@@ -99,6 +98,9 @@
         {
             if (context == null) throw new ArgumentNullException ("context");

+            if (context.Reader.LocalName == "allowedValueList" && context.Reader.NamespaceURI == Protocol.ServiceUrn) {
+                allowed_values = new List<string> ();
+            }
             context.AutoDeserializeElement (this);
         }


Fix warning

Fix warning

git-tfs-id: [https://tfs.codeplex.com:443/tfs/TFS36]$/ResXResourceManager/Main;C37465

--- ResXManager.VSIX/DteConfiguration.cs
+++ ResXManager.VSIX/DteConfiguration.cs
@@ -106,6 +106,8 @@

         private void TrySetValue<T>(EnvDTE.Globals globals, string internalKey, T value)
         {
+            Contract.Requires(globals != null);
+
             try
             {
                 globals[internalKey] = ConvertToString(value);


Null checking

Null checking

--- src/Main/Hadouken.Impl/Http/Api/SetSetting.cs
+++ src/Main/Hadouken.Impl/Http/Api/SetSetting.cs
@@ -21,6 +21,9 @@
         {
             var data = BindModel<Dictionary<string, object>>();

+            if (data == null)
+                return Json(false);
+
             foreach (var key in data.Keys)
             {
                 _keyValueStore.Set(key, data[key]);


Detect initial bolding for console colors

--- src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs
+++ src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs
@@ -8,11 +8,14 @@
 {
     public class AnsiConsole
     {
+        private const int Light = 0x08;
+
         private AnsiConsole(TextWriter writer)
         {
             Writer = writer;

             OriginalForegroundColor = Console.ForegroundColor;
+            _boldRecursion = ((int)OriginalForegroundColor & Light) != 0 ? 1 : 0;
         }

         private int _boldRecursion;
@@ -33,7 +36,6 @@

         private void SetColor(ConsoleColor color)
         {
-            const int Light = 0x08;
             int c = (int)color;

             Console.ForegroundColor =


Make admin api port nullable

Make admin api port nullable

--- src/MiningCore/Configuration/ClusterConfig.cs
+++ src/MiningCore/Configuration/ClusterConfig.cs
@@ -62,7 +62,7 @@
         PAK, // PAKcoin
         CANN, // CannabisCoin
         RVN, // Ravencoin
-        PGN, // Pigeoncoin
+        PGN, // Pigeoncoin
     }

     public class CoinConfig
@@ -341,7 +341,7 @@
         /// <summary>
         /// Port for admin-apis
         /// </summary>
-        public int AdminPort { get; set; }
+        public int? AdminPort { get; set; }
     }

     public partial class ZmqPubSubEndpointConfig
@@ -355,7 +355,7 @@
         public string PublishUrl { get; set; }

         /// <summary>
-        /// If set to true, the relay will "Connect" to the url, rather than "Bind" it
+        /// If set to true, the relay will "Connect" to the url, rather than "Bind" it
         /// </summary>
         public bool Connect { get; set; }
     }


Fix length of data for null results.

Fix length of data for null results.

--- src/MySql.Data/MySqlClient/MySqlDataReader.cs
+++ src/MySql.Data/MySqlClient/MySqlDataReader.cs
@@ -68,7 +68,7 @@
 				var length = (int) reader.ReadLengthEncodedInteger();
 				m_dataLengths[column] = length;
 				m_dataOffsets[column] = length == 0xFB ? -1 : reader.Offset;
-				reader.Offset += length == 0xFB ? 1 : length;
+				reader.Offset += length == 0xFB ? 0 : length;
 			}

 			m_currentRow = payload.ArraySegment.Array;


Remove legacy govuk-template JS to fix cookie banner being displayed

--- src/SFA.DAS.EmployerAccounts.Web/App_Start/BundleConfig.cs
+++ src/SFA.DAS.EmployerAccounts.Web/App_Start/BundleConfig.cs
@@ -9,7 +9,6 @@
         {
             bundles.Add(new ScriptBundle("~/bundles/sfajs").Include(
           "~/dist/javascripts/jquery-1.11.0.min.js",
-          "~/dist/javascripts/govuk-template.js",
           "~/dist/javascripts/selection-buttons.js",
           "~/dist/javascripts/showhide-content.js",
           "~/dist/javascripts/stacker.js",


Basic serialization overview, recursion stop and unique objects, needs more work with array and dictionary

--- SQLiteSerializer/SQLiteSerializer.cs
+++ SQLiteSerializer/SQLiteSerializer.cs
@@ -39,6 +39,7 @@

 		protected int primaryKeyCount = 0;
 		protected List<SerializedObjectTable> activeTables = new List<SerializedObjectTable>();
+		protected Dictionary<object,int> processedComplexObjects = new Dictionary<object, int>();

 		public void Serialize(object target, string databaseConnectionString) {
 			buildInfoTables();
@@ -59,11 +60,22 @@
 			return container;
 		}

+		protected bool hasBeenSeenBefore(object targetCheck) {
+			return processedComplexObjects.ContainsKey(targetCheck);
+        }
+
 		#region Internal Serialization Functions
 		protected void buildInfoTables() {
 		}

 		protected int buildComplexObjectTables(object target) {
+			// check and add object to the global seen list. Makes unique objects (top-down) and stops infinite recursion
+			if (hasBeenSeenBefore(target))
+				return processedComplexObjects[target];		// return the already proc'ed PK
+
+			int localPK = ++primaryKeyCount;
+			processedComplexObjects.Add(target, localPK);
+
 			Type localType = target.GetType();
 			if (!canSerialize(target))
 				throw new Exception("Your object is not serializable! Please add [Serializable] to the class definition for " + localType.Name + " and all child objects you are attempting to store.");
@@ -76,10 +88,16 @@

 			foreach (FieldInfo field in fields) {
 				Type fieldType = field.FieldType;
-                if (fieldType.IsPrimitive || fieldType.IsEnum || fieldType.IsValueType || fieldType.Equals(typeof(string)) || fieldType.IsSubclassOf(typeof(ValueType))) {
+				if (fieldType.IsPrimitive || fieldType.IsEnum || fieldType.IsValueType || fieldType.Equals(typeof(string)) || fieldType.IsSubclassOf(typeof(ValueType))) {
 					// we can store this raw
 					SerializedObjectColumn col = new SerializedObjectColumn(field.Name, fieldType.FullName, field.GetValue(target));
-                    table.AddColumn(col);
+					table.AddColumn(col);
+				} else if (field.FieldType.GetInterface(typeof(IDictionary<,>).FullName) != null) {		// handle dicts
+					// make a dict entry
+					// foreach the objs
+				} else if (field.FieldType.GetInterface(typeof(IEnumerable<>).FullName) != null) {		// handle all other collections
+					// make an array entry
+					// foreach the objs
 				} else {
 					// this is a complex type (a class or something), so recurse
 					int FK = buildComplexObjectTables(field.GetValue(target));	// we need a Foreign Key (otherwise objects would randomize themselves across the object structure on each load [goofy effect])
@@ -90,7 +108,7 @@
 			}

 			activeTables.Add(table);
-			return ++primaryKeyCount;
+			return localPK;
 		}

 		public bool canSerialize(object target) {


Changed DefaultWritableBufferExtensions.Write to take ROSpan<byte>

The Write method currently takes Span<byte> as a parameter.
It should take ReadOnlySpan<byte> as the method does not mutate the contents of the data it writes.

--- src/System.IO.Pipelines/DefaultWritableBufferExtensions.cs
+++ src/System.IO.Pipelines/DefaultWritableBufferExtensions.cs
@@ -17,7 +17,7 @@
         /// </summary>
         /// <param name="buffer">The <see cref="WritableBuffer"/></param>
         /// <param name="source">The <see cref="Span{Byte}"/> to write</param>
-        public static void Write(this WritableBuffer buffer, Span<byte> source)
+        public static void Write(this WritableBuffer buffer, ReadOnlySpan<byte> source)
         {
             if (buffer.Memory.IsEmpty)
             {


Added some extra handlebars helpers

Added some extra handlebars helpers

--- src/TypeScriptDefinitionsGenerator.Common/MainGenerator.cs
+++ src/TypeScriptDefinitionsGenerator.Common/MainGenerator.cs
@@ -746,7 +746,7 @@
             });
             Handlebars.RegisterHelper("IfEqualsAny", (writer, options, context, parameters) =>
             {
-                if (parameters.Length <= 2) throw new HandlebarsException("{{IfEqualsAny}} helper expects at least two parameters: input string, and N number of matching strings");
+                if (parameters.Length < 2) throw new HandlebarsException("{{IfEqualsAny}} helper expects at least two parameters: input string, and N number of matching strings");
                 var item = parameters[0].ToString();
                 var otherParameters = parameters.Skip(1).ToArray();
                 if (otherParameters.Any(x => x.Equals(item)))
@@ -756,10 +756,28 @@
             });
             Handlebars.RegisterHelper("IfEqualsAll", (writer, options, context, parameters) =>
             {
-                if (parameters.Length <= 2) throw new HandlebarsException("{{IfEqualsAll}} helper expects at least two parameters: input string, and N number of matching strings");
+                if (parameters.Length < 2) throw new HandlebarsException("{{IfEqualsAll}} helper expects at least two parameters: input string, and N number of matching strings");
                 var item = parameters[0].ToString();
                 var otherParameters = parameters.Skip(1).ToArray();
                 if (otherParameters.All(x => x.Equals(item)))
+                    options.Template(writer, null);
+                else
+                    options.Inverse(writer, null);
+            });
+            Handlebars.RegisterHelper("IfEqual", (writer, options, context, parameters) =>
+            {
+                if (parameters.Length != 2) throw new HandlebarsException("{{IfEquals}} helper expects at two parameters");
+                var item = parameters[0].ToString();
+                if (parameters[1].ToString().Equals(item))
+                    options.Template(writer, null);
+                else
+                    options.Inverse(writer, null);
+            });
+            Handlebars.RegisterHelper("IfNotEqual", (writer, options, context, parameters) =>
+            {
+                if (parameters.Length != 2) throw new HandlebarsException("{{IfNotEquals}} helper expects at two parameters");
+                var item = parameters[0].ToString();
+                if (!parameters[1].ToString().Equals(item))
                     options.Template(writer, null);
                 else
                     options.Inverse(writer, null);


Removing unused field

Removing unused field

--- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs
+++ src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs
@@ -27,7 +27,6 @@
         [NonSerialized] private double notificationClearTime = -1;
         [NonSerialized] private double timeSinceLastRotation = -1f;
         [NonSerialized] private bool currentBranchAndRemoteHasUpdate;
-        [NonSerialized] private bool gitExecutableIsSet;
         [NonSerialized] private Spinner spinner;
         [NonSerialized] private IProgress progress;
         [NonSerialized] private float progressValue;
@@ -269,7 +268,6 @@
                 progressMessage = progress.Message;
             }

-            gitExecutableIsSet = !String.IsNullOrEmpty(Environment.GitExecutablePath);
             string updatedRepoRemote = null;
             string updatedRepoUrl = DefaultRepoUrl;


fix #297

fix #297

--- Simple.Data.SqlServer/SqlDbTypeEx.cs
+++ Simple.Data.SqlServer/SqlDbTypeEx.cs
@@ -18,7 +18,7 @@
                                                                             { SqlDbType.Date, typeof(DateTime)},
                                                                             { SqlDbType.DateTime, typeof(DateTime)},
                                                                             { SqlDbType.DateTime2, typeof(DateTime)},
-                                                                            { SqlDbType.DateTimeOffset, typeof(DateTime)},
+                                                                            { SqlDbType.DateTimeOffset, typeof(DateTimeOffset)},
                                                                             { SqlDbType.Decimal, typeof(decimal)},
                                                                             { SqlDbType.Float, typeof(double)},
                                                                             { SqlDbType.Image, typeof(byte[])},


Added Update overload.

Added Update overload.

--- Source/Linq/Builder/UpdateBuilder.cs
+++ Source/Linq/Builder/UpdateBuilder.cs
@@ -47,7 +47,7 @@
 					{
 						var expr = methodCall.Arguments[1].Unwrap();

-						if (expr is LambdaExpression && expr.Type == typeof(bool))
+						if (expr is LambdaExpression && ((LambdaExpression)expr).ReturnType == typeof(bool))
 						{
 							CheckAssociation(sequence);


Added error handling for invalid config file and custom path

--- SourceEngineConsoleParser/Program.cs
+++ SourceEngineConsoleParser/Program.cs
@@ -77,7 +77,16 @@

         static void ReadConfig()
         {
+            bool runSetup = false;
+            String[] cfgLines;
             if (!File.Exists("config.cfg"))
+                runSetup = true;
+            else {
+                cfgLines = System.IO.File.ReadAllLines("config.cfg");
+                if (cfgLines.Contains(""))
+                    runSetup = true;
+            }
+            if (runSetup)
             {
                 logger.ClearConsole();
                 Console.Write("Please enter path to Source game directory:  ");
@@ -135,8 +144,17 @@

         static void UpdateAutoexec()
         {
-            string autoexec = File.ReadAllText(customPath + @"cfg\autoexec.cfg");
-            StreamWriter sw = new StreamWriter(customPath + @"cfg\autoexec.cfg", true);
+            String autoexec = "";
+            StreamWriter sw = null;
+            try {
+                autoexec = File.ReadAllText(customPath + @"cfg\autoexec.cfg");
+                sw = new StreamWriter(customPath + @"cfg\autoexec.cfg", true);
+            }
+            catch (System.IO.DirectoryNotFoundException) {
+                Console.Write("Invalid path to directory containing autoexec:\n" + customPath + "\nPress any key to exit.");
+                Console.ReadKey();
+                Environment.Exit(0);
+            }
             //Ensure logging is enabled
             if (!autoexec.Contains("con_logfile out.log"))
             {


Fixing source analysis

Fixing source analysis

--- Src/MathelSharp.Tests/MatrixTests.cs
+++ Src/MathelSharp.Tests/MatrixTests.cs
@@ -257,11 +257,13 @@
             Matrix matrix1 = new Matrix(new double[][] { new double[] { 1.0, 2.0 }, new double[] { 3.0, 4.0 } });
             Matrix matrix2 = new Matrix(new double[][] { new double[] { 5.0, 6.0 }, new double[] { 7.0, 8.0 }, new double[] { 9.0, 10.0 } });

-            try {
+            try
+            {
                 matrix1.Multiply(matrix2);
                 Assert.Fail();
             }
-            catch (Exception ex) {
+            catch (Exception ex)
+            {
                 Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                 Assert.AreEqual("Matrices cannot be multiplied", ex.Message);
             }


Implimented Read and Write cmdlets for VM settings. Resolves #21

--- Src/VMLib/Properties/AssemblyInfo.cs
+++ Src/VMLib/Properties/AssemblyInfo.cs
@@ -11,8 +11,8 @@
 [assembly: AssemblyDescription("Virtual Machine Control Library.")]
 [assembly: AssemblyCompany("Wil Taylor")]
 [assembly: AssemblyProduct("VMLib")]
-[assembly: AssemblyVersion("0.0.0.66")]
-[assembly: AssemblyFileVersion("0.0.0.66")]
+[assembly: AssemblyVersion("0.0.0.70")]
+[assembly: AssemblyFileVersion("0.0.0.70")]
 [assembly: AssemblyCopyright("Copyright Wil Taylor 2016")]
 [assembly: ComVisible(false)]


Remove unused usings.

Remove unused usings.

--- Paymetheus.Rpc/ConnectTimeoutException.cs
+++ Paymetheus.Rpc/ConnectTimeoutException.cs
@@ -2,10 +2,6 @@
 // Licensed under the ISC license.  See LICENSE file in the project root for full license information.

 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;

 namespace Paymetheus.Rpc
 {


Update anchor within help link (follow-up to r3671). Closes #3647.

git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@3683 af82e41b-90c4-0310-8c96-b1721e28e2e2

--- templates/anydiff.cs
+++ templates/anydiff.cs
@@ -38,7 +38,7 @@

   Note: See <a href="<?cs var:trac.href.wiki
-  ?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset for help on using the arbitrary diff feature.
+  ?>/TracChangeset#ExaminingDifferencesBetweenBranches">TracChangeset for help on using the arbitrary diff feature.


Pseudo-Implemented setting of system font

--- AngleSharp/DOM/Css/Properties/Font/CSSFontProperty.cs
+++ AngleSharp/DOM/Css/Properties/Font/CSSFontProperty.cs
@@ -157,20 +157,29 @@
         /// keyword can be used to represent a specific system font.
         /// </summary>
         /// <param name="font">The font to select.</param>
-        static void SetSystemFont(SystemFont font)
-        {
-            //TODO set properties to the setting given by the enumeration value
-
+        void SetSystemFont(SystemFont font)
+        {
             switch (font)
             {
                 case SystemFont.Caption:
                 case SystemFont.Icon:
+                case SystemFont.MessageBox:
+                    SetFont("Arial", "16px");
+                    break;
+                case SystemFont.StatusBar:
                 case SystemFont.Menu:
-                case SystemFont.MessageBox:
+                    SetFont("Segoe UI", "12px");
+                    break;
                 case SystemFont.SmallCaption:
-                case SystemFont.StatusBar:
+                    SetFont("Segoe UI", "15px");
                     break;
             }
+        }
+
+        void SetFont(String family, String size)
+        {
+            var value = String.Concat(size, " ", family.CssString());
+            Rule.SetPropertyValue(Name, value);
         }

         internal override String SerializeValue(IEnumerable<CssProperty> properties)


date format bug

date format bug

--- App/StackExchange.DataExplorer/Helpers/QueryRunner.cs
+++ App/StackExchange.DataExplorer/Helpers/QueryRunner.cs
@@ -236,7 +236,7 @@
                             if (col is DateTime)
                             {
                                 var date = (DateTime) col;
-                                col = date.ToString("yyyy-MM-dd hh:mm:ss");
+                                col = date.ToString("yyyy-MM-dd H:mm:ss");
                             }
                             row.Add(col);
                         }


Better naming in conv

Better naming in conv

--- CSharpLLVM/Generator/Instructions/Casting/EmitConv.cs
+++ CSharpLLVM/Generator/Instructions/Casting/EmitConv.cs
@@ -22,16 +22,16 @@
             if (TypeHelper.IsFloatingPoint(element))
             {
                 if (instruction.OpCode.Code == Code.Conv_R4 || instruction.OpCode.Code == Code.Conv_R8)
-                    result = LLVM.BuildFPCast(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fromfloat");
+                    result = LLVM.BuildFPCast(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fp2fp");
                 else
-                    result = LLVM.BuildFPToSI(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fromfloat");
+                    result = LLVM.BuildFPToSI(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fp2int");
             }
             else
             {
                 if (instruction.OpCode.Code == Code.Conv_R4 || instruction.OpCode.Code == Code.Conv_R8)
-                    result = LLVM.BuildSIToFP(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fromint");
+                    result = LLVM.BuildSIToFP(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "int2fp");
                 else
-                    result = LLVM.BuildIntCast(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "fromint");
+                    result = LLVM.BuildIntCast(builder, element.Value, TypeHelper.GetTypeRefFromConv(instruction.OpCode.Code), "int2int");
             }

             context.CurrentStack.Push(result);


Made fields public

Made fields public

--- CoCSharp/Networking/Packets/ChangeAvatarNamePacket.cs
+++ CoCSharp/Networking/Packets/ChangeAvatarNamePacket.cs
@@ -5,7 +5,7 @@
         public ushort ID { get { return 0x27E4; } }

         public string NewName;
-        private bool Unknown1;
+        public bool Unknown1;

         public void ReadPacket(PacketReader reader)
         {
@@ -16,7 +16,7 @@
         public void WritePacket(PacketWriter writer)
         {
             writer.WriteString(NewName);
-            writer.WriteBoolean(true); // Unknown1
+            writer.WriteBoolean(Unknown1);
         }
     }
 }


More spelling mistakes issues.

More spelling mistakes issues.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@2805

--- src/NHibernate/Expression/DetachedCriteria.cs
+++ src/NHibernate/Expression/DetachedCriteria.cs
@@ -155,12 +155,12 @@
 			return detachedCriteria;
 		}

-		public DetachedCriteria GetCriteiraByPath(string path)
+		public DetachedCriteria GetCriteriaByPath(string path)
 		{
 			return new DetachedCriteria(impl, impl.GetCriteriaByPath(path));
 		}

-		public DetachedCriteria GetCriteriaByPath(string alias)
+		public DetachedCriteria GetCriteriaByAlias(string alias)
 		{
 			return new DetachedCriteria(impl, impl.GetCriteriaByAlias(alias));
 		}


Handle cancelled lock acquisition in operation loop

--- Akavache.Sqlite3/OperationQueue.cs
+++ Akavache.Sqlite3/OperationQueue.cs
@@ -78,7 +78,18 @@
                 {
                     toProcess.Clear();

-                    using (await flushLock.LockAsync(shouldQuit.Token))
+                    IDisposable @lock = null;
+
+                    try
+                    {
+                        @lock = await flushLock.LockAsync(shouldQuit.Token);
+                    }
+                    catch (OperationCanceledException)
+                    {
+                        break;
+                    }
+
+                    using (@lock)
                     {
                         // NB: We special-case the first item because we want to
                         // in the empty list case, we want to wait until we have an item.


Logger thread safety?

Logger thread safety?

--- test/Microsoft.AspNetCore.SignalR.Tests.Utils/ServerLogScope.cs
+++ test/Microsoft.AspNetCore.SignalR.Tests.Utils/ServerLogScope.cs
@@ -14,12 +14,15 @@
         private readonly IDisposable _wrappedDisposable;
         private readonly ConcurrentDictionary<string, ILogger> _serverLoggers;
         private readonly ILogger _scopeLogger;
+        private readonly object _lock;

         public ServerLogScope(ServerFixture serverFixture, ILoggerFactory loggerFactory, IDisposable wrappedDisposable)
         {
             _loggerFactory = loggerFactory;
             _serverFixture = serverFixture;
             _wrappedDisposable = wrappedDisposable;
+
+            _lock = new object();

             _serverLoggers = new ConcurrentDictionary<string, ILogger>(StringComparer.Ordinal);
             _scopeLogger = _loggerFactory.CreateLogger(nameof(ServerLogScope));
@@ -40,8 +43,16 @@
                 return;
             }

-            // Create (or get) a logger with the same name as the server logger
-            var logger = _serverLoggers.GetOrAdd(write.LoggerName, loggerName => _loggerFactory.CreateLogger(loggerName));
+            ILogger logger;
+
+            // There maybe thready safety issues in logging when creating multiple threads at the same time
+            // https://github.com/aspnet/Logging/issues/810
+            lock (_lock)
+            {
+                // Create (or get) a logger with the same name as the server logger
+                logger = _serverLoggers.GetOrAdd(write.LoggerName, loggerName => _loggerFactory.CreateLogger(loggerName));
+            }
+
             logger.Log(write.LogLevel, write.EventId, write.State, write.Exception, write.Formatter);
         }


Give nukies a medic (#8353)

Give nukies a medic (#8353)

Co-authored-by: metalgearsloth <5a6002283f4d0ed17bed24ee1f9d131baf85176c@gmail.com>

--- Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs
+++ Content.Server/GameTicking/Rules/NukeopsRuleSystem.cs
@@ -130,6 +130,7 @@
         // TODO: Loot table or something
         var commanderGear = _prototypeManager.Index<StartingGearPrototype>("SyndicateCommanderGearFull");
         var starterGear = _prototypeManager.Index<StartingGearPrototype>("SyndicateOperativeGearFull");
+        var medicGear = _prototypeManager.Index<StartingGearPrototype>("SyndicateOperativeMedicFull");

         var spawns = new List<EntityCoordinates>();

@@ -153,15 +154,20 @@
             string name;
             StartingGearPrototype gear;

-            if (i == 0)
+            switch (i)
             {
-                name = $"Commander";
-                gear = commanderGear;
-            }
-            else
-            {
-                name = $"Operator #{i}";
-                gear = starterGear;
+                case 0:
+                    name = $"Commander";
+                    gear = commanderGear;
+                    break;
+                case 1:
+                    name = $"Operator #{i}";
+                    gear = medicGear;
+                    break;
+                default:
+                    name = $"Operator #{i}";
+                    gear = starterGear;
+                    break;
             }

             var session = ops[i];


Line breaks

Line breaks

--- Anlab.Mvc/Views/Error/Error.cshtml
+++ Anlab.Mvc/Views/Error/Error.cshtml
@@ -2,8 +2,8 @@
     ViewData["Title"] = "Error Detected";
 }

-
Error.

-
An error occurred while processing your request.

-
If the problem persists please contact us.

+
Error.

+
An error occurred while processing your request.

+
If the problem persists please contact us.


fix bug;

fix bug;

--- AntSharesCore/Network/LocalNode.cs
+++ AntSharesCore/Network/LocalNode.cs
@@ -128,7 +128,7 @@
                 AddingTransactionEventArgs args = new AddingTransactionEventArgs(tx);
                 AddingTransaction?.Invoke(this, args);
                 if (!args.Cancel) MemoryPool.Add(tx.Hash, tx);
-                return args.Cancel;
+                return !args.Cancel;
             }
         }


DateTimeZone.getName()

DateTimeZone.getName()

--- src/Peachpie.Library/DateTime/DateTimeZone.cs
+++ src/Peachpie.Library/DateTime/DateTimeZone.cs
@@ -16,6 +16,9 @@
     public class DateTimeZone
     {
         internal TimeZoneInfo _timezone;
+
+        /// <summary>The timezone name if it differs from <see cref="TimeZoneInfo.Id"/>.</summary>
+        private protected string _name;

         #region Constants

@@ -53,10 +56,13 @@
             if (timezone_name != null)
             {
                 _timezone = PhpTimeZone.GetTimeZone(timezone_name);
+                _name = timezone_name;

                 if (_timezone == null)
                 {
-                    //PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", zoneName));
+                    // TODO: an offset value (+0200)
+
+                    //PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", timezone_name));
                     throw new ArgumentException();
                 }
             }
@@ -100,8 +106,7 @@
         //public string getName ( void )
         public virtual string getName()
         {
-            //return (timezone != null) ? timezone.Id : null;
-            throw new NotImplementedException();
+            return _name ?? _timezone.Id;
         }

         //public int getOffset ( DateTime $datetime )


Fix broken tests

Fix broken tests

--- tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs
+++ tests/NuGetGallery.Facts/Controllers/PackagesControllerFacts.cs
@@ -32,7 +32,6 @@
             Mock<ISearchService> searchService = null,
             Exception readPackageException = null,
             Mock<IAutomaticallyCuratePackageCommand> autoCuratePackageCmd = null,
-            Mock<INuGetExeDownloaderService> downloaderService = null,
             Mock<IAppConfiguration> config = null,
             Mock<IPackageFileService> packageFileService = null,
             Mock<IEntitiesContext> entitiesContext = null,
@@ -50,7 +49,6 @@
             messageService = messageService ?? new Mock<IMessageService>();
             searchService = searchService ?? CreateSearchService();
             autoCuratePackageCmd = autoCuratePackageCmd ?? new Mock<IAutomaticallyCuratePackageCommand>();
-            downloaderService = downloaderService ?? new Mock<INuGetExeDownloaderService>(MockBehavior.Strict);
             config = config ?? new Mock<IAppConfiguration>();

             if (packageFileService == null)
@@ -73,7 +71,6 @@
                 messageService.Object,
                 searchService.Object,
                 autoCuratePackageCmd.Object,
-                downloaderService.Object,
                 packageFileService.Object,
                 entitiesContext.Object,
                 config.Object,


Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests

--- src/Runners/Giles.Runner.NUnit/NUnitRunner.cs
+++ src/Runners/Giles.Runner.NUnit/NUnitRunner.cs
@@ -1,9 +1,7 @@
-using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Reflection;
 using Giles.Core.Runners;
-using Giles.Core.Utility;
 using NUnit.Core;
 using NUnit.Core.Filters;

@@ -20,7 +18,10 @@
             var package = SetupTestPackager(assembly);
             remoteTestRunner.Load(package);
             var listener = new GilesNUnitEventListener();
-            remoteTestRunner.Run(listener, GetFilters());
+            if (filters.Count() == 0)
+                remoteTestRunner.Run(listener);
+            else
+                remoteTestRunner.Run(listener, GetFilters());
             return listener.SessionResults;
         }


test stability update

test stability update

--- tests/ServiceStack.AzureServiceBus.Tests/AzureBusServerTests.cs
+++ tests/ServiceStack.AzureServiceBus.Tests/AzureBusServerTests.cs
@@ -358,6 +358,8 @@

                     var msg = mqClient.Get<HelloNull>(replyMq, TimeSpan.FromSeconds(10));

+                    await Task.Delay(200);
+
                     HelloNull response = msg.GetBody();
                     Assert.That(response.Name, Is.EqualTo("Into the Void"));
                     Assert.That(msgsReceived, Is.EqualTo(1));


make code more concise, as per review comment

--- src/SFA.DAS.EAS.Portal.Client/PortalClient.cs
+++ src/SFA.DAS.EAS.Portal.Client/PortalClient.cs
@@ -43,8 +43,7 @@
             if (vacancies == null)
                 return account;

-            var vacanciesCount = vacancies.Count();
-            switch (vacanciesCount)
+            switch (vacancies.Count())
             {
                 case 0:
                     account.VacancyCardinality = Cardinality.None;


fixed the bug Pong was not sent correctly

--- src/SuperSocket.WebSocket/WebSocketPackage.cs
+++ src/SuperSocket.WebSocket/WebSocketPackage.cs
@@ -60,7 +60,7 @@

         internal void SaveOpCodeByte()
         {
-            OpCodeByte = (byte)(OpCodeByte | (byte)OpCode);
+            OpCodeByte = (byte)((OpCodeByte & 0xF0) | (byte)OpCode);
         }

         internal bool HasMask { get; set; }


Update copyright.

Update copyright.

--- src/TeamCityBackup/Properties/AssemblyInfo.cs
+++ src/TeamCityBackup/Properties/AssemblyInfo.cs
@@ -9,7 +9,7 @@
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("FantasticFiasco")]
 [assembly: AssemblyProduct("TeamCity Backup")]
-[assembly: AssemblyCopyright("Copyright © FantasticFiasco 2014")]
+[assembly: AssemblyCopyright("Copyright © FantasticFiasco 2014-2016")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]


Update help responder with new commands

Update help responder with new commands

--- FineBot/FineBot.BotRunner/Responders/HelpResponder.cs
+++ FineBot/FineBot.BotRunner/Responders/HelpResponder.cs
@@ -30,7 +30,9 @@
             builder.AppendLine();
             builder.AppendLine("@finesbot leaderboard <today|week|month|year>: Leaderboard of the top five users with the most fines for the current day/week/month/year. If no time period is specified, the all time leaderboard is displayed");
             builder.AppendLine();
-            builder.AppendLine("@finesbot count all: Counts the number of fines successfully issued (i.e. seconded) by all users.");
+            builder.AppendLine("@finesbot fine count <all|users>: Counts the number of fines successfully issued (i.e. seconded) by the specified users. If \"all\" is specified the count for all fines will be displayed. If no users are specified, the fine count of the requester will be displayed.");
+            builder.AppendLine();
+            builder.AppendLine("@finesbot seconded count <users>: Counts the number of fines seconded by the specified users. If no user is specified, the number of fines seconded by the requester will be displayed.");
             builder.AppendLine();
             builder.AppendLine(String.Format("@FinesBot support <support type: {0}> <message>: Creates a support ticket with the status selected. If no status is specified it is created as a general issue.", String.Join("|", Enum.GetNames(typeof(SupportType)))));


Refactoring: web api methods now async

Refactoring: web api methods now async

--- GalleryMVC_With_Auth/Controllers/WebAPIsController.cs
+++ GalleryMVC_With_Auth/Controllers/WebAPIsController.cs
@@ -1,5 +1,7 @@
 using System.Collections.Generic;
+using System.Data.Entity;
 using System.Linq;
+using System.Threading.Tasks;
 using System.Web.Http;
 using GalleryMVC_With_Auth.Domain.Abstract;
 using GalleryMVC_With_Auth.Models;
@@ -15,9 +17,9 @@
             _repository = repository;
         }

-        public List<AlbumModel> GetAlbums()
+        public async Task<List<AlbumModel>> GetAlbums()
         {
-            return
+            return await
                 _repository.Albums.Select(
                     a =>
                         new AlbumModel
@@ -27,7 +29,7 @@
                             ImgPath = a.ImgPath,
                             Link = a.Link,
                             Name = a.Name
-                        }).ToList();
+                        }).ToListAsync();
         }

         public string Get()
@@ -35,9 +37,26 @@
             return "U in web api controller!";
         }

-        public List<PictureModel> GetAllPictures()
+        //public List<PictureModel> GetAllPictures()
+        //{
+        //    return _repository.Pictures
+        //        .Select(
+        //            p =>
+        //                new PictureModel
+        //                {
+        //                    Id = p.Id,
+        //                    Name = p.Name,
+        //                    Description = p.Description,
+        //                    Price = p.Price,
+        //                    Path = p.Path,
+        //                    TmbPath = p.TmbPath
+        //                })
+        //        .ToList();
+        //}
+
+        public async Task<List<PictureModel>> GetAllPictures()
         {
-            return _repository.Pictures
+            return await _repository.Pictures
                 .Select(
                     p =>
                         new PictureModel
@@ -49,12 +68,12 @@
                             Path = p.Path,
                             TmbPath = p.TmbPath
                         })
-                .ToList();
+                .ToListAsync();
         }

-        public List<PictureModel> GetPictures(int id)
+        public async Task<List<PictureModel>> GetPictures(int id)
         {
-            return _repository.Pictures.Where(p => p.AlbumId == id)
+            return await _repository.Pictures.Where(p => p.AlbumId == id)
                 .Select(
                     p =>
                         new PictureModel
@@ -66,7 +85,7 @@
                             Path = p.Path,
                             TmbPath = p.TmbPath
                         })
-                .ToList();
+                .ToListAsync();
         }

         public List<PictureModel> GetFound(string search)


- unused file

- unused file

--- HudsonTrayTracker/BusinessComponents/UpdateService.cs
+++ HudsonTrayTracker/BusinessComponents/UpdateService.cs
@@ -1,134 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Threading;
-using Dotnet.Commons.Logging;
-using System.Reflection;
-using Hudson.TrayTracker.Entities;
-using System.ComponentModel;
-using Hudson.TrayTracker.Utils.Logging;
-using Iesi.Collections.Generic;
-
-namespace Hudson.TrayTracker.BusinessComponents
-{
-    public class UpdateService
-    {
-        public enum UpdateSource
-        {
-            User,
-            Timer,
-            Program
-        }
-
-        public delegate void ProjectsUpdatedHandler();
-        public event ProjectsUpdatedHandler ProjectsUpdated;
-
-        static readonly ILog logger = LogFactory.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
-        // every 15 seconds
-        static readonly int DEFAULT_UPDATE_PERIOD = 15 * 1000;
-
-        ConfigurationService configurationService;
-        HudsonService hudsonService;
-
-        Timer timer;
-        int updatePeriod = DEFAULT_UPDATE_PERIOD;
-        bool updating;
-
-        public ConfigurationService ConfigurationService
-        {
-            get { return configurationService; }
-            set { configurationService = value; }
-        }
-
-        public HudsonService HudsonService
-        {
-            get { return hudsonService; }
-            set { hudsonService = value; }
-        }
-
-        public UpdateService()
-        {
-            timer = new Timer(UpdateProjects, null, 0, updatePeriod);
-        }
-
-        public void UpdateProjects()
-        {
-            BackgroundWorker worker = new BackgroundWorker();
-            worker.DoWork += delegate
-            {
-                DoUpdateProjects(UpdateSource.User);
-            };
-            worker.RunWorkerAsync();
-        }
-
-        private void UpdateProjects(object state)
-        {
-            DoUpdateProjects(UpdateSource.Timer);
-        }
-
-        private void DoUpdateProjects(UpdateSource source)
-        {
-            logger.Info("Running update from " + source);
-            try
-            {
-                DoUpdateProjectsInternal(source);
-            }
-            catch (Exception ex)
-            {
-                LoggingHelper.LogError(logger, ex);
-                throw;
-            }
-            logger.Info("Done");
-        }
-
-        private void DoUpdateProjectsInternal(UpdateSource source)
-        {
-            lock (this)
-            {
-                if (updating)
-                {
-                    logger.Info("Already in update: skipping");
-                    return;
-                }
-                updating = true;
-            }
-
-            try
-            {
-                ISet<Project> projects = configurationService.GetProjects();
-                IDictionary<Project, AllBuildDetails> newBuildDetails = new Dictionary<Project, AllBuildDetails>();
-
-                foreach (Project project in projects)
-                {
-                    try
-                    {
-                        AllBuildDetails newBuildDetail = hudsonService.UpdateProject(project);
-                        newBuildDetails[project] = newBuildDetail;
-                    }
-                    catch (Exception ex)
-                    {
-                        LoggingHelper.LogError(logger, ex);
-                    }
-                }
-
-                foreach (Project project in projects)
-                {
-                    AllBuildDetails newStatus;
-                    newBuildDetails.TryGetValue(project, out newStatus);
-                    project.AllBuildDetails = newStatus;
-                }
-
-                if (ProjectsUpdated != null)
-                    ProjectsUpdated();
-            }
-            finally
-            {
-                lock (this)
-                {
-                    updating = false;
-                }
-            }
-        }
-    }
-}


Refactored: nullチェックのコードを簡略化。

Refactored: nullチェックのコードを簡略化。

--- Implem.Pleasanter/Libraries/HtmlParts/HtmlCommands.cs
+++ Implem.Pleasanter/Libraries/HtmlParts/HtmlCommands.cs
@@ -145,7 +145,7 @@
                                     _using: exportButton && permissionType.CanExport());
                         }
                     }
-                    if (extensions != null) extensions();
+                    extensions?.Invoke();
                 }));
         }
     }


Always escape parameter names

Always escape parameter names

--- InterfaceStubGenerator.Core/InterfaceStubGenerator.cs
+++ InterfaceStubGenerator.Core/InterfaceStubGenerator.cs
@@ -510,7 +510,7 @@
         /// <ineritdoc />
         {methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} {methodSymbol.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}.{methodSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}(");

-            source.Append(string.Join(", ", methodSymbol.Parameters.Select(p => $"{p.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} {p.MetadataName}")));
+            source.Append(string.Join(", ", methodSymbol.Parameters.Select(p => $"{p.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} @{p.MetadataName}")));

            source.Append(@")
         {");


storing more datas

storing more datas

--- King.Azure.Integration.Test/Data/TableStorageTests.cs
+++ King.Azure.Integration.Test/Data/TableStorageTests.cs
@@ -143,12 +143,14 @@
             var entity = new Dictionary<string, object>();
             entity.Add(TableStorage.PartitionKey, p);
             entity.Add(TableStorage.RowKey, r);
+            entity.Add("Id", Guid.NewGuid());
             await storage.InsertOrReplace(entity);

-            var e = storage.QueryByPartitionAndRow<TableEntity>(p, r);
+            var e = storage.QueryByPartitionAndRow<Helper>(p, r);
             Assert.IsNotNull(e);
             Assert.AreEqual(entity[TableStorage.PartitionKey], e.PartitionKey);
             Assert.AreEqual(entity[TableStorage.RowKey], e.RowKey);
+            Assert.AreEqual(entity["Id"], e.Id);
         }

         [Test]