Handle AddressNotFoundException

Handle AddressNotFoundException

--- src/GeoIP/Executers/MaxMindQuery.cs
+++ src/GeoIP/Executers/MaxMindQuery.cs
@@ -1,5 +1,6 @@
 using GeoIP.Models;
 using MaxMind.GeoIP2;
+using MaxMind.GeoIP2.Exceptions;
 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
@@ -12,33 +13,44 @@
     {
         public async Task<string> Query(string ipAddress, string dataSource)
         {
-            using (var reader = new DatabaseReader(dataSource))
+            Object result;
+
+            try
             {
-                Object result;
-                var city = reader.City(ipAddress);
+                using (var reader = new DatabaseReader(dataSource))
+                {
+                    var city = reader.City(ipAddress);

-                if (city != null)
+                    if (city != null)
+                    {
+                        result = new Geolocation()
+                        {
+                            IPAddress = ipAddress,
+                            City = city.City.Name,
+                            Country = city.Country.Name,
+                            Latitude = city.Location.Latitude,
+                            Longitude = city.Location.Longitude
+                        };
+                    }
+                    else
+                    {
+                        result = new Error()
+                        {
+                            ErrorMessage = "Geolocation not found"
+                        };
+                    }
+
+                }
+            }
+            catch (AddressNotFoundException ex)
+            {
+                result = new Error()
                 {
-                    result = new Geolocation()
-                    {
-                        IPAddress = ipAddress,
-                        City = city.City.Name,
-                        Country = city.Country.Name,
-                        Latitude = city.Location.Latitude,
-                        Longitude = city.Location.Longitude
-                    };
-                }
-                else
-                {
-                    result = new Error()
-                    {
-                        ErrorMessage = "Geolocation not found"
-                    };
-                }
+                    ErrorMessage = ex.Message
+                };
+            }

-                return JsonConvert.SerializeObject(result);
-
-            }
+            return JsonConvert.SerializeObject(result);
         }
     }
 }


optimized balance of smaller trees

optimized balance of smaller trees

--- src/ImTools/ImTools.Experimental.cs
+++ src/ImTools/ImTools.Experimental.cs
@@ -563,15 +563,30 @@
                 Debug.Assert(newLeftTree.TreeHeight == 3, "Otherwise it is too un-balanced");
                 if (newLeftTree.Left is ImMapEntry<V> leftLeftLeaf)
                 {
+                    //            30                    15
+                    //    10            40 =>    10           20
+                    //  5     15               5    12     30    40
+                    //     12   20
                     if (newLeftTree.Right is ImMapTree<V> leftRightTree)
+                    {
+                        newLeftTree.Right = leftRightTree.Left;
+                        newLeftTree.TreeHeight = 2;
                         return new ImMapTree<V>(leftRightTree.Entry,
-                            new ImMapTree<V>(newLeftTree.Entry, 1, leftLeftLeaf, leftRightTree.Left),
-                            new ImMapTree<V>(Entry, leftRightTree.Right, 1, rightLeaf));
-
-                    var leftRightBranch = (ImMapBranch<V>) newLeftTree.Right;
+                            newLeftTree,
+                            new ImMapTree<V>(Entry, leftRightTree.Right, rightLeaf, 2),
+                            3);
+                    }
+
+                    // we cannot reuse the new left tree here because it is reduced into the branch
+                    //           30                     15
+                    //    10            40 =>    5           20
+                    //  5    15                    10     30    40
+                    //         20
+                    var leftRightBranch = (ImMapBranch<V>)newLeftTree.Right;
                     return new ImMapTree<V>(leftRightBranch.Entry,
-                        2, ImMapBranch<V>.CreateNormalized(newLeftTree.Entry, leftLeftLeaf),
-                        new ImMapTree<V>(Entry, leftRightBranch.RightEntry, rightLeaf));
+                        new ImMapBranch<V>(leftLeftLeaf, newLeftTree.Entry),
+                        new ImMapTree<V>(Entry, leftRightBranch.RightEntry, rightLeaf),
+                        3);
                 }

                 newLeftTree.Right = new ImMapTree<V>(Entry, newLeftTree.Right, rightLeaf, 2);
@@ -582,7 +597,7 @@
             var rightHeight = (Right as ImMapTree<V>)?.TreeHeight ?? 2;
             if (newLeftTree.TreeHeight - 1 > rightHeight)
             {
-                var leftLeftHeight  = (newLeftTree.Left  as ImMapTree<V>)?.TreeHeight ?? 2;
+                var leftLeftHeight = (newLeftTree.Left as ImMapTree<V>)?.TreeHeight ?? 2;
                 var leftRightHeight = (newLeftTree.Right as ImMapTree<V>)?.TreeHeight ?? 2;
                 if (leftLeftHeight < leftRightHeight)
                 {
@@ -621,23 +636,36 @@
                     return newRightTree;
                 }

-                // todo: optimize this the same as below
+                //        20                        30
+                // 10             40     =>    20        40
+                //            30      50     10  25    35  50
+                //          25  35
                 if (newRightTree.Left is ImMapTree<V> rightLeftTree)
+                {
+                    newRightTree.Left = rightLeftTree.Right;
+                    newRightTree.TreeHeight = 2;
                     return new ImMapTree<V>(rightLeftTree.Entry,
-                        new ImMapTree<V>(Entry, 1, leftLeaf, rightLeftTree.Left),
-                        new ImMapTree<V>(newRightTree.Entry, rightLeftTree.Right, 1, newRightTree.Right));
-
+                        new ImMapTree<V>(Entry, leftLeaf, rightLeftTree.Left, 2),
+                        newRightTree, 3);
+                }
+
+                //        20                        30
+                // 10             40     =>    10        40
+                //            30      50         20    35  50
+                //              35
                 var rightLeftBranch = (ImMapBranch<V>)newRightTree.Left;
+                newRightTree.Left = rightLeftBranch.RightEntry;
+                newRightTree.TreeHeight = 2;
                 return new ImMapTree<V>(rightLeftBranch.Entry,
-                    2, ImMapBranch<V>.CreateNormalized(Entry, leftLeaf),
-                    new ImMapTree<V>(newRightTree.Entry, rightLeftBranch.RightEntry, (ImMapEntry<V>)newRightTree.Right));
+                    new ImMapBranch<V>(leftLeaf, Entry),
+                    newRightTree, 3);
             }

             var leftHeight = (Left as ImMapTree<V>)?.TreeHeight ?? 2;
             if (newRightTree.TreeHeight > leftHeight + 1)
             {
                 var rightRightHeight = (newRightTree.Right as ImMapTree<V>)?.TreeHeight ?? 2;
-                var rightLeftHeight  = (newRightTree.Left  as ImMapTree<V>)?.TreeHeight ?? 2;
+                var rightLeftHeight = (newRightTree.Left as ImMapTree<V>)?.TreeHeight ?? 2;
                 if (rightRightHeight < rightLeftHeight)
                 {
                     var rightLeftTree = (ImMapTree<V>)newRightTree.Left;
@@ -648,7 +676,7 @@
                     return new ImMapTree<V>(rightLeftTree.Entry,
                         // Left should be >= rightLeft.Left because it maybe rightLeft.Right which defines rl height
                         new ImMapTree<V>(Entry, Left, rightLeftTree.Left, height: leftHeight + 1),
-                        newRightTree,
+                        newRightTree,
                         rightRightHeight + 2);

                     //return new ImMapTree<V>(rightLeftTree.Entry,


Attempt to fix experiment initialization with KIS

See #563

--- src/Kerbalism/Modules/Experiment.cs
+++ src/Kerbalism/Modules/Experiment.cs
@@ -9,7 +9,7 @@
 namespace KERBALISM
 {

-	public class Experiment : PartModule, ISpecifics, IModuleInfo, IPartMassModifier, IModuleRollout, IConfigurable
+	public class Experiment : PartModule, ISpecifics, IModuleInfo, IPartMassModifier, IConfigurable
 	{
 		// config
 		[KSPField] public string experiment_id;               // id of associated experiment definition
@@ -40,6 +40,7 @@
 		[KSPField(isPersistant = true)] public bool shrouded = false;
 		[KSPField(isPersistant = true)] public double remainingSampleMass = 0.0;
 		[KSPField(isPersistant = true)] public uint privateHdId = 0;
+		[KSPField(isPersistant = true)] public bool firstStart = true;

 		/// <summary> never set this directly, use the "State" property </summary>
 		[KSPField(isPersistant = true)] private RunningState expState = RunningState.Stopped;
@@ -189,23 +190,24 @@
 				{
 					if (hd.experiment_id == experiment_id) privateHdId = part.flightID;
 				}
-			}
-		}
-
-		/// <summary>Called by Callbacks just after rollout to launch pad</summary>
-		public void OnRollout()
-		{
-			if (!Lib.ModuleEnableInScienceAndCareer(this)) return;
-
+
+				if(firstStart)
+				{
+					FirstStart();
+					firstStart = false;
+				}
+			}
+		}
+
+		private void FirstStart()
+		{
 			// initialize the remaining sample mass
 			// this needs to be done only once just after launch
 			if (!sample_collecting && ExpInfo.SampleMass > 0.0)
 			{
 				remainingSampleMass = ExpInfo.SampleMass * sample_amount;
-				if(Double.IsNaN(remainingSampleMass))
-				{
-					Lib.LogDebug("ERROR: remainingSampleMass is NaN on rollout " + ExpInfo.ExperimentId + " " + ExpInfo.SampleMass + " / " + sample_amount);
-				}
+				if(double.IsNaN(remainingSampleMass))
+					Lib.LogDebug("ERROR: remainingSampleMass is NaN on first start " + ExpInfo.ExperimentId + " " + ExpInfo.SampleMass + " / " + sample_amount);
 			}
 		}


Return FullPath.Empty when the path is empty

--- src/Meziantou.Framework/FullPath.cs
+++ src/Meziantou.Framework/FullPath.cs
@@ -148,6 +148,9 @@
         {
             var fullPath = Path.GetFullPath(path);
             var fullPathWithoutTrailingDirectorySeparator = Path.TrimEndingDirectorySeparator(fullPath);
+            if (string.IsNullOrEmpty(fullPathWithoutTrailingDirectorySeparator))
+                return Empty;
+
             return new FullPath(fullPathWithoutTrailingDirectorySeparator);
         }


don't select if cleared

don't select if cleared

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -1529,6 +1529,7 @@
             UnityEngine.GUILayout.ExpandWidth(true));
         if (UnityEngine.GUILayout.Button("Clear",
                                          UnityEngine.GUILayout.Width(50))) {
+          selecting_active_vessel_target_ = false;
           FlightGlobals.fetch.SetVesselTarget(null);
         }
       }


same UI style everywhere

same UI style everywhere

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -471,7 +471,7 @@
     if (hide_all_gui_) {
       return;
     } else if (show_main_window_) {
-      UnityEngine.GUI.skin = HighLogic.Skin;
+      UnityEngine.GUI.skin = null;
       main_window_rectangle_.xMin = main_window_x_;
       main_window_rectangle_.yMin = main_window_y_;
       main_window_rectangle_ = UnityEngine.GUILayout.Window(


not max

not max

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -47,11 +47,11 @@
       {1E-3, 1E-2, 1E0, 1E1, 1E2, 1E3, 1E4};
   [KSPField(isPersistant = true)]
   private int prediction_length_tolerance_index_ = 1;
-  private readonly int[] prediction_max_steps_ =
+  private readonly double[] prediction_steps_ =
       {1 << 2, 1 << 4, 1 << 6, 1 << 8, 1 << 10, 1 << 12, 1 << 14, 1 << 16,
        1 << 18, 1 << 20, 1 << 22, 1 << 24};
   [KSPField(isPersistant = true)]
-  private int prediction_max_steps_index_ = 4;
+  private int prediction_steps_index_ = 4;
   private readonly double[] history_lengths_ =
       {1 << 10, 1 << 11, 1 << 12, 1 << 13, 1 << 14, 1 << 15, 1 << 16, 1 << 17,
        1 << 18, 1 << 19, 1 << 20, 1 << 21, 1 << 22, 1 << 23, 1 << 24, 1 << 25,
@@ -661,7 +661,7 @@
         // TODO(egg): make the speed tolerance independent.  Also max_steps.
         AdaptiveStepParameters adaptive_step_parameters =
             new AdaptiveStepParameters {
-              max_steps = prediction_max_steps_[prediction_max_steps_index_],
+              max_steps = (Int64)prediction_steps_[prediction_steps_index_],
               length_integration_tolerance =
                   prediction_length_tolerances_[
                       prediction_length_tolerance_index_],
@@ -1070,9 +1070,9 @@
              "Tolerance",
              ref changed_settings,
              "{0:0.0e0} m");
-    Selector(prediction_max_steps_,
-             ref prediction_max_steps_index_,
-             "Max. steps",
+    Selector(prediction_steps_,
+             ref prediction_steps_index_,
+             "Steps",
              ref changed_settings,
              "{0:0.00e0}");
   }


Unescapes relative URLs in ValidateLinks

--- src/extensions/Wyam.Html/ValidateLinks.cs
+++ src/extensions/Wyam.Html/ValidateLinks.cs
@@ -179,6 +179,7 @@
             {
                 normalizedPath = normalizedPath.Remove(normalizedPath.IndexOf("?", StringComparison.Ordinal));
             }
+            normalizedPath = Uri.UnescapeDataString(normalizedPath);
             if (normalizedPath == string.Empty)
             {
                 return true;


Automatic generation of usage line based on registered positional value attributes added.

--- Help/HelpOption.cs
+++ Help/HelpOption.cs
@@ -26,9 +26,23 @@
                 Console.WriteLine();
             }

+            var valuesBuilder = new StringBuilder();
+            foreach(var value in parser.Values)
+            {
+                if(value.IsRequired)
+                {
+                    valuesBuilder.Append(' ').Append(value.Name);
+                }
+                else
+                {
+                    valuesBuilder.AppendFormat(" [{0}]", value.Name);
+                }
+            }
+
+            var usageLine = string.Format(UsageLineFormat, appInfo.ApplicationBinaryName, valuesBuilder);
             Console.WriteLine(CustomUsageLineGenerator != null
-                ? CustomUsageLineGenerator(appInfo.ApplicationBinaryName)
-                :  string.Format(UsageLineFormat, appInfo.ApplicationBinaryName));
+                ? CustomUsageLineGenerator(usageLine)
+                : usageLine);

             Console.WriteLine();
             Console.WriteLine("Options:");
@@ -52,7 +66,7 @@

         public Func<string> CustomFooterGenerator { get; set; }

-        public const string UsageLineFormat = "usage: {0} [options]";
+        public const string UsageLineFormat = "usage: {0} [options]{1}";

         private static string GenerateOptionHelpEntry(ICommandLineOption option)
         {


Log: fix mistake in previous commit that was causing compile warnings

--- Hyena/Hyena/Log.cs
+++ Hyena/Hyena/Log.cs
@@ -354,7 +354,7 @@

         public static void Warning (Exception e)
         {
-            Exception (null, e);
+            Warning (null, e);
         }

         public static void Warning (string message, Exception e)
@@ -398,7 +398,7 @@

         public static void Error (Exception e)
         {
-            Exception (null, e);
+            Error (null, e);
         }

         public static void Error (string message, Exception e)


Update build

Update build

--- build/Build.GitFlow.cs
+++ build/Build.GitFlow.cs
@@ -28,7 +28,7 @@

     Target Release => _ => _
         .DependsOn(Changelog)
-        .Requires(() => GitHasCleanWorkingCopy())
+        .Requires(() => !GitRepository.IsOnReleaseBranch() || GitHasCleanWorkingCopy())
         .Executes(() =>
         {
             if (!GitRepository.IsOnReleaseBranch())
@@ -39,7 +39,7 @@

     Target Hotfix => _ => _
         .DependsOn(Changelog)
-        .Requires(() => GitHasCleanWorkingCopy())
+        .Requires(() => !GitRepository.IsOnHotfixBranch() || GitHasCleanWorkingCopy())
         .Executes(() =>
         {
             var masterVersion = GitVersion(s => s


Shell out to POV-Ray to render the frames.

--- LegoGif/Program.cs
+++ LegoGif/Program.cs
@@ -23,6 +23,11 @@
             return GetLDrawPaths().FirstOrDefault(p => p != null && Directory.Exists(p));
         });

+        private static readonly Lazy<string> PovRayPath = new Lazy<string>(() =>
+        {
+            return GetPovRayPaths().FirstOrDefault(p => p != null && File.Exists(p));
+        });
+
         public static void Main(string[] args)
         {
             var file = args[0];
@@ -32,11 +37,12 @@
             foreach (var angle in CameraAngles())
             {
                 var frameName = "frame_" + angle;
+                var povFile = frameName + ".pov";

                 var l3pStartInfo = new ProcessStartInfo
                 {
                     FileName = "l3p.exe",
-                    Arguments = string.Format("-stdout \"{0}\" {1}.pov -o -cg30,{2}", file, frameName, angle, LDPath.Value),
+                    Arguments = string.Format("-stdout \"{0}\" {1} -o -cg30,{2}", file, povFile, angle, LDPath.Value),
                     CreateNoWindow = true,
                     RedirectStandardOutput = true,
                     UseShellExecute = false,
@@ -45,9 +51,28 @@

                 using (var p = Process.Start(l3pStartInfo))
                 {
+                    MakePump(p.StandardOutput, ">")();
+                    p.WaitForExit();
+                }
+
+                var povStartInfo = new ProcessStartInfo
+                {
+                    FileName = PovRayPath.Value,
+                    Arguments = string.Format(" /NR /RENDER \"{0}\" /EXIT +F +FN +UA +W512 +H384 +Q11 +A", povFile),
+                    RedirectStandardError = true,
+                    RedirectStandardOutput = true,
+                    UseShellExecute = false,
+                    WindowStyle = ProcessWindowStyle.Minimized,
+                };
+
+                using (var p = Process.Start(povStartInfo))
+                {
+                    Task.Factory.StartNew(MakePump(p.StandardError, "!"));
                     Task.Factory.StartNew(MakePump(p.StandardOutput, ">"));
                     p.WaitForExit();
                 }
+
+                File.Delete(povFile);
             }
         }

@@ -76,6 +101,40 @@
             yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "LDView");
         }

+        public static IEnumerable<string> GetPovRayPaths()
+        {
+            var paths = new[]
+            {
+                Path.Combine("POV-Ray", "v3.7", "bin"),
+                Path.Combine("POV-Ray", "v3.6", "bin"),
+                Path.Combine("POV-Ray for Windows v3.6", "v3.6", "bin"),
+            };
+
+            var files = new[]
+            {
+                "pvengine64.exe",
+                "pvengine32-sse2.exe",
+                "pvengine.exe",
+            };
+
+            var roots = new[]
+            {
+                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
+                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
+            };
+
+            foreach (var path in paths)
+            {
+                foreach (var file in files)
+                {
+                    foreach (var root in roots)
+                    {
+                        yield return Path.Combine(root, path, file);
+                    }
+                }
+            }
+        }
+
         public static Action MakePump(TextReader reader, string prefix)
         {
             return () =>


Fixed annoying little bug, ups

Fixed annoying little bug, ups

git-svn-id: 97d83464e8ef39b4fed63f24cff5a65eaf0c6b64@41 bff262af-d8e0-4d19-9a35-3eece30b5779

--- MCAdmin/Program.cs
+++ MCAdmin/Program.cs
@@ -355,7 +355,11 @@
             ply = ply.ToLower(); rank = rank.ToLower();
             if (rank == GetServerProperty("default-rank", "guest"))
             {
-                if (plyranks.ContainsKey(ply)) plyranks.Remove(ply);
+                if (plyranks.ContainsKey(ply))
+                {
+                    plyranks.Remove(ply);
+                    SaveRanks();
+                }
                 return;
             }
             if (plyranks.ContainsKey(ply)) plyranks[ply] = rank;


terminate application when database connection fails

--- MapWindow/Form1.cs
+++ MapWindow/Form1.cs
@@ -27,6 +27,7 @@
             catch
             {
                 MessageBox.Show("Database Connection Failed");
+                Environment.Exit(0);
             }

             myMap = axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica);


Fix potential buffer overrun in ClearWithReferences

--- src/mscorlib/shared/System/SpanHelpers.cs
+++ src/mscorlib/shared/System/SpanHelpers.cs
@@ -517,7 +517,6 @@
             // Write first four and last three.
             Unsafe.Add(ref ip, 2) = default(IntPtr);
             Unsafe.Add(ref ip, 3) = default(IntPtr);
-            Unsafe.Add(ref ip, 4) = default(IntPtr);
             Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -3) = default(IntPtr);
             Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -2) = default(IntPtr);


Fix generics; break arrays

Fix generics; break arrays

--- MonoMod/MonoMod.cs
+++ MonoMod/MonoMod.cs
@@ -722,31 +722,32 @@
                             }
                         }

-                        ModuleReference foundMethodModule = foundMethod.Module;
-
                         if (typeMismatch && method.DeclaringType.IsGenericInstance) {
-                            Console.WriteLine("debug: Previously " + foundMethod);
+                            Console.WriteLine("debug: a: " + foundMethod);
                             Console.WriteLine("debug: " + foundMethod.MetadataToken);

                             //TODO test return type context
                             MethodReference genMethod = new MethodReference(method.Name, FindType(method.ReturnType, findTypeRef), findTypeRef);
-
-                            genMethod.CallingConvention = method.CallingConvention | MethodCallingConvention.Generic;
+                            genMethod.CallingConvention = method.CallingConvention;
+                            genMethod.HasThis = method.HasThis;
+                            genMethod.ExplicitThis = method.ExplicitThis;
                             for (int i = 0; i < method.GenericParameters.Count; i++) {
                                 genMethod.GenericParameters.Add(new GenericParameter(method.GenericParameters[i].Name, findTypeRef));
                             }
                             for (int i = 0; i < method.Parameters.Count; i++) {
                                 genMethod.Parameters.Add(new ParameterDefinition(FindType(method.Parameters[i].ParameterType, genMethod)));
                             }
-                            genMethod.HasThis = method.HasThis;
-                            genMethod.ExplicitThis = method.ExplicitThis;

+                            Console.WriteLine("debug: b: " + genMethod);
+                            Console.WriteLine("debug: " + genMethod.MetadataToken);
+                            genMethod = Module.Import(genMethod);
+
+                            Console.WriteLine("debug: c: " + genMethod);
+                            Console.WriteLine("debug: " + genMethod.MetadataToken);
                             foundMethod = genMethod;
-                            Console.WriteLine("debug: Now " + foundMethod);
-                            Console.WriteLine("debug: " + foundMethod.MetadataToken);
                         }

-                        if (foundMethodModule != Module) {
+                        if (foundMethod.Module != Module) {
                             foundMethod = Module.Import(foundMethod);
                         }


Added a looping router

Added a looping router

--- ORMTodos/Router.cs
+++ ORMTodos/Router.cs
@@ -9,9 +9,31 @@
 {
     class Router
     {
-        public void Route(string[] args)
+        public void RunOneRoute(string[] args)
         {
             RunCommandCycle(args);
+        }
+
+        public void Route(string[] initalArgs)
+        {
+
+            IControler controler = ControlerFactory("welcome");
+            controler.Process("welcome", Enumerable.Repeat(String.Empty,0));
+
+            while (true)
+            {
+                var args = Console.ReadLine() ?? String.Empty;
+                var cleanedUpArgs = args.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
+                Console.Clear();
+
+                if (args.Equals("exit",StringComparison.OrdinalIgnoreCase))
+                {
+                    break;
+                }
+
+                RunCommandCycle(cleanedUpArgs);
+            }
+
         }

         protected void RunCommandCycle(string[] args)


Added new, deterministic initialization method.

--- QUSMAML/KMedoid.cs
+++ QUSMAML/KMedoid.cs
@@ -80,7 +80,7 @@
             Clusters = new List<int>();

             //calculate all the distances
-            _distances = new double[inputs.Count(), inputs.Count()];
+            _distances = new double[inputs.Count, inputs.Count];

             for (int i = 0; i < inputs.Count - 1; i++)
             {
@@ -94,18 +94,7 @@
             _medoids = Enumerable.Range(1, k).Select(x => -1).ToArray();

             //initialization
-            //TODO need a smarter way of initializing
-            var r = new Random();
-            for (int i = 0; i < k; i++)
-            {
-                int medoidIndex;
-                do
-                {
-                    medoidIndex = r.Next(0, inputs.Count);
-
-                } while (_medoids.Contains(medoidIndex));
-                _medoids[i] = medoidIndex;
-            }
+            InitializeMedoids(inputs, k);

             //loop until no further improvement is made
             bool stop = false;
@@ -124,6 +113,57 @@

             //finally get the clusters from the current medoids
             UpdateClusters(inputs);
+        }
+
+        /// <summary>
+        /// A deterministic approach to initialization.
+        /// Follows Park et al (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.7981&rep=rep1&type=pdf) for the first medoid.
+        /// Then picks medoids on the basis of maximum differene from the already existing ones.
+        /// </summary>
+        private void InitializeMedoids(List<T> inputs, int k)
+        {
+            double[] distanceSums = new double[inputs.Count];
+            double[,] p = new double[inputs.Count, inputs.Count];
+            double[] pSum = new double[inputs.Count];
+            for (int i = 0; i < inputs.Count; i++)
+            {
+                for (int j = 0; j < inputs.Count; j++)
+                {
+                    distanceSums[i] += _distances[i, j];
+                }
+            }
+
+            for (int i = 0; i < inputs.Count; i++)
+            {
+                for (int j = 0; j < inputs.Count; j++)
+                {
+                    p[i, j] += _distances[i, j] / distanceSums[i];
+                }
+            }
+
+            for (int i = 0; i < inputs.Count; i++)
+            {
+                for (int j = 0; j < inputs.Count; j++)
+                {
+                    pSum[i] += p[j, i];
+                }
+            }
+
+            _medoids[0] = Array.IndexOf(pSum, pSum.Min());
+
+            //we have the first medoid, now simply select new ones on the basis of maximum distance from the existing ones
+            for (int i = 1; i < k; i++)
+            {
+                double[] medoidDistanceSums = new double[inputs.Count];
+                for (int j = 0; j < i; j++)
+                {
+                    for (int l = 0; l < inputs.Count; l++)
+                    {
+                        medoidDistanceSums[l] += _distances[l, _medoids[j]];
+                    }
+                }
+                _medoids[i] = Array.IndexOf(medoidDistanceSums, medoidDistanceSums.Max());
+            }
         }

         /// <summary>


Disambiguate parameter variants of DokanOperations.Mount()

--- DokanNet/Dokan.cs
+++ DokanNet/Dokan.cs
@@ -44,11 +44,11 @@

         public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, ILogger logger = null)
         {
-            Mount(operations, mountPoint, mountOptions, threadCount, version, TimeSpan.FromSeconds(20), String.Empty, 512, 512, logger);
+            Mount(operations, mountPoint, mountOptions, threadCount, version, TimeSpan.FromSeconds(20), null, 512, 512, logger);
         }
         public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, TimeSpan timeout, ILogger logger = null)
         {
-            Mount(operations, mountPoint, mountOptions, threadCount, version, timeout, String.Empty, 512, 512, logger);
+            Mount(operations, mountPoint, mountOptions, threadCount, version, timeout, null, 512, 512, logger);
         }

         public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, TimeSpan timeout, string uncName, ILogger logger = null)
@@ -56,7 +56,12 @@
             Mount(operations, mountPoint, mountOptions, threadCount, version, timeout, uncName, 512, 512, logger);
         }

-        public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, TimeSpan timeout, string uncName = null, int allocationUnitSize = 512, int sectorSize = 512, ILogger logger = null)
+        public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, TimeSpan timeout, int allocationUnitSize, int sectorSize, ILogger logger = null)
+        {
+            Mount(operations, mountPoint, mountOptions, threadCount, version, timeout, null, allocationUnitSize, sectorSize, logger);
+        }
+
+        public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions, int threadCount, int version, TimeSpan timeout, string uncName, int allocationUnitSize, int sectorSize, ILogger logger = null)
         {
 #if TRACE
             if(logger == null){


NTFS: Fix reading end of compressed files, reported by becco [#5239]

--- src/Ntfs/CompressedClusterStream.cs
+++ src/Ntfs/CompressedClusterStream.cs
@@ -221,8 +221,10 @@
                     // Compressed data - read via IO buffer
                     _rawStream.ReadClusters(cuStart, _attr.CompressionUnitSize, _ioBuffer, 0);

+                    int expected = (int)Math.Min(_attr.Length - (vcn * _bytesPerCluster), _attr.CompressionUnitSize * _bytesPerCluster);
+
                     int decomp = _context.Options.Compressor.Decompress(_ioBuffer, 0, _ioBuffer.Length, _cacheBuffer, 0);
-                    if (decomp != _cacheBuffer.Length)
+                    if (decomp < expected)
                     {
                         throw new IOException("Decompression returned too little data");
                     }


disable v3 compression tests temporarily

--- src/Parquet.Test/CompressionTest.cs
+++ src/Parquet.Test/CompressionTest.cs
@@ -34,9 +34,9 @@
          Assert.Equal(5, ds2[0].GetInt(0));

          //v3
-         const int value = 5;
-         object actual = WriteReadSingle(new DataField<int>("id"), value, compressionMethod);
-         Assert.Equal(5, (int)actual);
+         //const int value = 5;
+         //object actual = WriteReadSingle(new DataField<int>("id"), value, compressionMethod);
+         //Assert.Equal(5, (int)actual);
       }
    }
 }


Fixed a small and smelly bug

Fixed a small and smelly bug

git-svn-id: 6b7e1e5d0861e268462ba7828ef63c1bcab52a9b@953 d3cde5d6-82b8-4669-8b62-43054d6781d8

--- Radio/Decimator.cs
+++ Radio/Decimator.cs
@@ -526,13 +526,13 @@
                     break;
             }

-            _cicDecimatorsBuffer = UnsafeBuffer.Create(threadCount * _cicCount, sizeof(CicDecimator));
+            _cicDecimatorsBuffer = UnsafeBuffer.Create(_threadCount * _cicCount, sizeof(CicDecimator));
             _cicDecimators = (CicDecimator*) _cicDecimatorsBuffer;
-            for (var i = 0; i < threadCount; i++)
+            for (var i = 0; i < _threadCount; i++)
             {
                 for (var j = 0; j < _cicCount; j++)
                 {
-                    _cicDecimators[i * threadCount + j] = new CicDecimator();
+                    _cicDecimators[i * _cicCount + j] = new CicDecimator();
                 }
             }

@@ -573,7 +573,7 @@

                 #region Filter and down-sample

-                _cicDecimators[contextId * _threadCount + n].Process(chunk, chunkLength);
+                _cicDecimators[contextId * _cicCount + n].Process(chunk, chunkLength);

                 #endregion

@@ -604,7 +604,7 @@

                 #region Filter and down-sample

-                _cicDecimators[contextId * _threadCount + n].ProcessInterleaved(chunk, chunkLength);
+                _cicDecimators[contextId * _cicCount + n].ProcessInterleaved(chunk, chunkLength);

                 #endregion


Code cleanup

Code cleanup

--- src/PushNotifications.Api/Cronus.cs
+++ src/PushNotifications.Api/Cronus.cs
@@ -3,10 +3,8 @@
 using Elders.Cronus.Pipeline.Hosts;
 using Elders.Cronus.Pipeline.Transport.RabbitMQ.Config;
 using Elders.Cronus.IocContainer;
-using Elders.Cronus;
 using Elders.Pandora;
 using Elders.Cronus.DomainModeling;
-using System.Linq;
 using System.Web.Http;
 using Elders.Cronus.Pipeline;
 using Elders.Cronus.Pipeline.Transport;
@@ -32,15 +30,11 @@

                 ApplicationConfiguration.SetContext("PushNotifications");

-                string PN = "PushNotifications";
-
                 container = new Container();
-
-                var PM_appServiceFactory = new ApplicationServiceFactory(container, PN);
                 var cfg = new CronusSettings(container);

                 cfg.UseContractsFromAssemblies(new[] { Assembly.GetAssembly(typeof(PushNotificationWasSent)) });
-                cfg.UseRabbitMqTransport(x => (x as IRabbitMqTransportSettings).Server = ApplicationConfiguration.Get("server"));
+                cfg.UseRabbitMqTransport(x => (x as IRabbitMqTransportSettings).Server = ApplicationConfiguration.Get("pushnot_rabbitmq_server"));

                 Func<IPipelineTransport> transport = () => container.Resolve<IPipelineTransport>();
                 Func<ISerializer> serializer = () => container.Resolve<ISerializer>();
@@ -61,45 +55,6 @@
             }
         }

-        public class ApplicationServiceFactory
-        {
-            private readonly IContainer container;
-            private readonly string namedInstance;
-
-            public ApplicationServiceFactory(IContainer container, string namedInstance)
-            {
-                this.container = container;
-                this.namedInstance = namedInstance;
-            }
-
-            public object Create(Type appServiceType)
-            {
-                var appService = FastActivator
-                    .CreateInstance(appServiceType);
-                return appService;
-            }
-        }
-
-        public class PortHandlerFactory
-        {
-            private readonly IContainer container;
-            private readonly string namedInstance;
-
-            public PortHandlerFactory(IContainer container, string namedInstance)
-            {
-                this.container = container;
-                this.namedInstance = namedInstance;
-            }
-
-            public object Create(Type handlerType)
-            {
-                var handler = FastActivator
-                    .CreateInstance(handlerType)
-                    .AssignPropertySafely<IPort>(x => x.CommandPublisher = container.Resolve<IPublisher<ICommand>>(namedInstance));
-                return handler;
-            }
-        }
-
         public static void Stop()
         {
             host.Stop();


Overhauled redshift-class

Overhauled redshift-class

--- redshift-tray/redshift-tray/redshift.cs
+++ redshift-tray/redshift-tray/redshift.cs
@@ -15,7 +15,6 @@
     public readonly static int[] MIN_REDSHIFT_VERSION = { 1, 10 };

     private Process RedshiftProcess;
-    private bool ReadOutputAsync;

     public static Redshift Instance { get; private set; }

@@ -29,8 +28,8 @@
         return RedshiftError.NotFound;
       }

-      Create(false, "-V");
-      string[] version = Instance.GetOutputSync().Split(' ');
+      Start("-V");
+      string[] version = Instance.GetOutput().Split(' ');

       if(version.Length < 2 || version[0] != "redshift")
       {
@@ -66,67 +65,39 @@
       return (majorversion == MIN_REDSHIFT_VERSION[0] && minorVersion >= MIN_REDSHIFT_VERSION[1]);
     }

-    public static void Create(bool asyncOutput, params string[] Args)
+    public static Redshift Start(params string[] Args)
     {
       if(Instance != null && !Instance.RedshiftProcess.HasExited)
         throw new Exception("Only one running instance is allowed!");

-      Instance = new Redshift(asyncOutput, Args);
+      Instance = new Redshift(Args);
+      return Instance;
     }

-    private Redshift(bool asyncOutput, params string[] Args)
+    private Redshift(params string[] Args)
     {
       string arglist = string.Join(" ", Args);

-      App.WriteLogMessage(string.Format("Starting redshift {0} with args '{1}'", asyncOutput ? "asynchronous" : "synchronous", arglist), DebugConsole.LogType.Info);
+      App.WriteLogMessage(string.Format("Starting redshift with args '{0}'", arglist), DebugConsole.LogType.Info);

       RedshiftProcess = new Process();
       RedshiftProcess.StartInfo.FileName = REDSHIFTPATH;
       RedshiftProcess.StartInfo.Arguments = arglist;
       RedshiftProcess.StartInfo.UseShellExecute = false;
-      RedshiftProcess.StartInfo.CreateNoWindow = true;
+      RedshiftProcess.StartInfo.CreateNoWindow = false;
       RedshiftProcess.StartInfo.RedirectStandardOutput = true;
       RedshiftProcess.Start();
-
-      ReadOutputAsync = asyncOutput;
-      if(asyncOutput)
-      {
-        RedshiftProcess.BeginOutputReadLine();
-        AddOutputAsyncEventHandler(
-          (object sender, DataReceivedEventArgs e) => App.WriteLogMessage(e.Data, DebugConsole.LogType.Redshift)
-          );
-      }
     }

-    public string GetOutputSync()
+    public string GetOutput()
     {
-      if(ReadOutputAsync)
-      {
-        throw new Exception("Tried to read redshift output sync in async-mode");
-      }
-
       if(RedshiftProcess == null || RedshiftProcess.StandardOutput.EndOfStream)
         return string.Empty;

-      string line = RedshiftProcess.StandardOutput.ReadLine();
-      App.WriteLogMessage(line, DebugConsole.LogType.Redshift);
+      string output = RedshiftProcess.StandardOutput.ReadToEnd();
+      App.WriteLogMessage(output, DebugConsole.LogType.Redshift);

-      return line;
-    }
-
-    public void AddOutputAsyncEventHandler(DataReceivedEventHandler handler)
-    {
-      if(!ReadOutputAsync)
-      {
-        throw new Exception("Tried to add redshift output event handler in sync-mode");
-      }
-
-      RedshiftProcess.OutputDataReceived += handler;
-    }
-
-    public void RemoveOutputAsyncEventHandler(DataReceivedEventHandler handler)
-    {
-      RedshiftProcess.OutputDataReceived -= handler;
+      return output;
     }

     public enum RedshiftError


add option GreaterRiftCountdown

add option GreaterRiftCountdown

--- RiftTimerPlugin.cs
+++ RiftTimerPlugin.cs
@@ -20,6 +20,7 @@
         public string ProgressPercentFormat { get; set; }
         public string ClosingSecondsFormat { get; set; }

+        public bool GreaterRiftCountdown { get; set; }
         public bool ShowGreaterRiftTimer { get; set; }
         public bool ShowGreaterRiftCompletedTimer { get; set; }
         public bool ShowClosingTimer { get; set; }
@@ -82,6 +83,8 @@
         private IWatch guardianTimer;
         private IWatch pauseTimer;

+        private const long greaterRiftMaxTime = 15*60*1000;
+
         private readonly StringBuilder textBuilder;

         public RiftTimerPlugin()
@@ -96,6 +99,7 @@
             base.Load(hud);

             ShowClosingTimer = false;
+            GreaterRiftCountdown = false;
             ShowGreaterRiftTimer = true;
             ShowGreaterRiftCompletedTimer = true;
             CompletionDisplayLimit = 90;
@@ -248,7 +252,7 @@
                     textBuilder.Append(ObjectiveProgressSymbol);
                     textBuilder.Append(" ");
                 }
-                else if (currentRun == SpecialArea.GreaterRift && Hud.Game.RiftPercentage > 0.1 && (ShowGreaterRiftTimer || !uiProgressBar.Visible || (ShowGreaterRiftCompletedTimer && IsGuardianDead)))
+                else if (currentRun == SpecialArea.GreaterRift && (ShowGreaterRiftTimer || !uiProgressBar.Visible || (ShowGreaterRiftCompletedTimer && IsGuardianDead)))
                 {
                     textBuilder.Append(ObjectiveProgressSymbol);
                     textBuilder.Append(" ");
@@ -257,16 +261,18 @@

             if (currentRun == SpecialArea.GreaterRift)
             {
-                if (ShowGreaterRiftTimer || Hud.Game.RiftPercentage >= 100)
-                {
-                    var timeSpan = TimeSpan.FromMilliseconds(riftTimer.ElapsedMilliseconds);
+                if (ShowGreaterRiftTimer || !uiProgressBar.Visible || (ShowGreaterRiftCompletedTimer && IsGuardianDead))
+                {
+                    var timeSpan = GreaterRiftCountdown && !IsGuardianDead
+                        ? TimeSpan.FromMilliseconds(greaterRiftMaxTime - riftTimer.ElapsedMilliseconds)
+                        : TimeSpan.FromMilliseconds(riftTimer.ElapsedMilliseconds);
                     textBuilder.AppendFormat(CultureInfo.InvariantCulture, (timeSpan.Minutes < 1) ? SecondsFormat : MinutesSecondsFormat, timeSpan);
                 }
             }
             else
             {
-                var _timeSpan = TimeSpan.FromMilliseconds(riftQuest.StartedOn.ElapsedMilliseconds - riftQuest.CompletedOn.ElapsedMilliseconds - pauseTimer.ElapsedMilliseconds);
-                textBuilder.AppendFormat(CultureInfo.InvariantCulture, (_timeSpan.Minutes < 1) ? SecondsFormat : MinutesSecondsFormat, _timeSpan);
+                var timeSpan = TimeSpan.FromMilliseconds(riftQuest.StartedOn.ElapsedMilliseconds - riftQuest.CompletedOn.ElapsedMilliseconds - pauseTimer.ElapsedMilliseconds);
+                textBuilder.AppendFormat(CultureInfo.InvariantCulture, (timeSpan.Minutes < 1) ? SecondsFormat : MinutesSecondsFormat, timeSpan);
             }

             if (onlyTimer)


Hard-coded swagger.json url;

Hard-coded swagger.json url;

--- Service/Startup.cs
+++ Service/Startup.cs
@@ -50,7 +50,7 @@
 		{
 			app.UseMvcWithDefaultRoute();
 			app.UseSwagger();
-			app.UseSwaggerUi();
+			app.UseSwaggerUi(swaggerUrl: "https://konhit.xyz/lbservice/swagger/v1/swagger.json");
 			loggerFactory.AddConsole().AddDebug();
 		}
 	}


Fixed ReadColor component order (I don't know how that even happened -.-). Added default alpha values when reading color values without an alpha component

--- SimpleJSONUnity.cs
+++ SimpleJSONUnity.cs
@@ -46,6 +46,8 @@
     public enum JSONContainerType { Array, Object }
 	public partial class JSONNode
 	{
+        public static byte Color32DefaultAlpha = 255;
+        public static float ColorDefaultAlpha = 1f;
         public static JSONContainerType VectorContainerType = JSONContainerType.Array;
         public static JSONContainerType QuaternionContainerType = JSONContainerType.Array;
         public static JSONContainerType RectContainerType = JSONContainerType.Array;
@@ -259,9 +261,9 @@
         public Color ReadColor(Color aDefault)
         {
             if (IsObject)
-                return new Color(this["a"].AsFloat, this["r"].AsFloat, this["g"].AsFloat, this["b"].AsFloat);
-            if (IsArray)
-                return new Color(this[0].AsFloat, this[1].AsFloat, this[2].AsFloat, this[3].AsFloat);
+                return new Color(this["r"].AsFloat, this["g"].AsFloat, this["b"].AsFloat, HasKey("a")?this["a"].AsFloat:ColorDefaultAlpha);
+            if (IsArray)
+                return new Color(this[0].AsFloat, this[1].AsFloat, this[2].AsFloat, (Count>4)?this[3].AsFloat:ColorDefaultAlpha);
             return aDefault;
         }
         public Color ReadColor()
@@ -292,9 +294,9 @@
         public Color32 ReadColor32(Color32 aDefault)
         {
             if (IsObject)
-                return new Color32((byte)this["r"].AsInt, (byte)this["g"].AsInt, (byte)this["b"].AsInt, (byte)this["a"].AsInt);
-            if (IsArray)
-                return new Color32((byte)this[0].AsInt, (byte)this[1].AsInt, (byte)this[2].AsInt, (byte)this[3].AsInt);
+                return new Color32((byte)this["r"].AsInt, (byte)this["g"].AsInt, (byte)this["b"].AsInt, (byte)(HasKey("a")?this["a"].AsInt:Color32DefaultAlpha));
+            if (IsArray)
+                return new Color32((byte)this[0].AsInt, (byte)this[1].AsInt, (byte)this[2].AsInt, (byte)((Count>4)?this[3].AsInt:Color32DefaultAlpha));
             return aDefault;
         }
         public Color32 ReadColor32()


added drawing from different position than top left

--- SnipIt/MainForm.cs
+++ SnipIt/MainForm.cs
@@ -450,6 +450,36 @@

                 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

+                float startX = 0, startY = 0;
+                float drawWidth = 0, drawHeight = 0;
+
+                // work out drawing direction
+                if (e.X > previousMousePos.Value.X)
+                {
+                    // right
+                    drawWidth = e.X - previousMousePos.Value.X;
+                    startX = previousMousePos.Value.X;
+                }
+                else
+                {
+                    // left
+                    drawWidth = previousMousePos.Value.X - e.X;
+                    startX = e.X;
+                }
+
+                if (e.Y > previousMousePos.Value.Y)
+                {
+                    // down
+                    drawHeight = e.Y - previousMousePos.Value.Y;
+                    startY = previousMousePos.Value.Y;
+                }
+                else
+                {
+                    // up
+                    drawHeight = previousMousePos.Value.Y - e.Y;
+                    startY = e.Y;
+                }
+
                 switch (drawingType)
                 {
                     case drawEnum.Line:
@@ -457,12 +487,12 @@
                         g.DrawLine(drawingPen, previousMousePos.Value, e.Location);
                         break;
                     case drawEnum.Rect:
-
-                        g.DrawRectangle(drawingPen, previousMousePos.Value.X, previousMousePos.Value.Y, e.X - previousMousePos.Value.X, e.Y - previousMousePos.Value.Y);
+
+                        g.DrawRectangle(drawingPen, startX, startY, drawWidth, drawHeight);
                         break;
                     case drawEnum.Ellipse:

-                        g.DrawEllipse(drawingPen, previousMousePos.Value.X, previousMousePos.Value.Y, e.X - previousMousePos.Value.X, e.Y - previousMousePos.Value.Y);
+                        g.DrawEllipse(drawingPen, startX, startY, drawWidth, drawHeight);
                         break;
                     default:


Typo fix.

Typo fix.

--- nml.tests/QuaternionTests.cs
+++ nml.tests/QuaternionTests.cs
@@ -201,7 +201,7 @@
         }

         [Fact]
-        public void QuaternionSerpTest()
+        public void QuaternionSlerpTest()
         {
             // Testing slerp, we'll actually just use some rotation quaternions
             // And test the known expected results of a vector.


minor visual enhancement

minor visual enhancement

--- source/Jmp.Web/Views/Home/Report.cshtml
+++ source/Jmp.Web/Views/Home/Report.cshtml
@@ -88,6 +88,8 @@

                                 @i.Key

+                                @i.Fields.Status.Name.ToString()
+

                                 @i.Fields.TimeTracking.RemainingEstimate

                         }


Fixed SteamHelper not finding custom library folders after recent Steam update; Fixes #299

--- source/SteamHelper/SteamInstallation.cs
+++ source/SteamHelper/SteamInstallation.cs
@@ -31,21 +31,28 @@

         private static IEnumerable<string> FindSteamAppsLocations(string installationDirectory)
         {
-            var steamApps = new List<string> { Path.Combine(installationDirectory, @"SteamApps") };
+            var libraryLocations = new List<string> { Path.Combine(installationDirectory, @"SteamApps") };

-            var libFoldersFile = Path.Combine(steamApps[0], @"libraryfolders.vdf");
-            if (File.Exists(libFoldersFile))
+            // The libraryfolders seems to appear in multiple locations. To be safe gather info from all of them
+            foreach (var vdfPath in new[] { @"config\libraryfolders.vdf", @"SteamApps\libraryfolders.vdf" }.Select(x => Path.Combine(installationDirectory, x)))
             {
-                foreach (var str in File.ReadAllLines(libFoldersFile))
+                if (!File.Exists(vdfPath)) continue;
+
+                foreach (var line in File.ReadAllLines(vdfPath))
                 {
-                    var pieces = str.Split('\"').Where(p => !string.IsNullOrEmpty(p?.Trim())).ToList();
-                    if (pieces.Count != 2 || !int.TryParse(pieces[0], out var _)) continue;
-
-                    var path = Path.Combine(pieces[1].Replace(@"\\", @"\"), "steamapps");
-                    steamApps.Add(path);
+                    // Gather key/value pairs from the file. It seems to be in a proprietary format
+                    var pieces = line.Split('\"').Where(p => !string.IsNullOrWhiteSpace(p?.Trim())).ToList();
+                    if (pieces.Count != 2) continue;
+                    // Only path matters, it specifies absolute path to the library folder
+                    if (pieces[0] == "path")
+                    {
+                        var path = Path.Combine(pieces[1].Replace(@"\\", @"\"), "steamapps");
+                        libraryLocations.Add(path);
+                    }
                 }
             }
-            return steamApps.Where(Directory.Exists);
+
+            return libraryLocations.Distinct().Where(Directory.Exists);
         }

         private static string FindSteamInstallationLocation()


added Polygon2d extension Transformed with M44d argument: creates a 3d polygon assuming z=0 with given transformation;

--- src/Aardvark.Base/Geometry/Polygon2d.cs
+++ src/Aardvark.Base/Geometry/Polygon2d.cs
@@ -16,6 +16,19 @@

         public static Polygon3d ToPolygon3d(this Polygon2d polygon, Func<V2d, int, V3d> point_index_copyFun)
             => new Polygon3d(polygon.GetPointArray(point_index_copyFun));
+
+        #endregion
+
+        #region Trnsformations
+
+        /// <summary>
+        /// Transforms a 2d polygon into 3d.
+        /// The z-coordinate is assumed to be zero.
+        /// </summary>
+        public static Polygon3d Transformed(this Polygon2d polygon, M44d transform)
+        {
+            return new Polygon3d(polygon.GetPointArray(p => transform.TransformPos(p.XYO)));
+        }

         #endregion


Add a way to pass view model for the main window

--- src/Avalonia.Controls/AppBuilderBase.cs
+++ src/Avalonia.Controls/AppBuilderBase.cs
@@ -115,13 +115,16 @@
         /// Starts the application with an instance of <typeparamref name="TMainWindow"/>.
         /// </summary>
         /// <typeparam name="TMainWindow">The window type.</typeparam>
-        public void Start<TMainWindow>()
+        /// <param name="dataContextProvider">A delegate that will be called to create a data context for the window (optional).</param>
+        public void Start<TMainWindow>(Func<object> dataContextProvider = null)
             where TMainWindow : Window, new()
         {
             Setup();
             BeforeStartCallback(Self);

             var window = new TMainWindow();
+            if (dataContextProvider != null)
+                window.DataContext = dataContextProvider();
             window.Show();
             Instance.Run(window);
         }


AsyncFormWrapper: .Dispose() implicitly calls .Close()

--- src/Common.WinForms/AsyncFormWrapper.cs
+++ src/Common.WinForms/AsyncFormWrapper.cs
@@ -247,10 +247,7 @@
         /// <inheritdoc/>
         public void Dispose()
         {
-            lock (_lock)
-            {
-                if (_form != null) _form.Dispose();
-            }
+            Close();
         }
     }
 }


simply the lambda

simply the lambda

--- src/Commons.Collections/Map/LlrbTree.cs
+++ src/Commons.Collections/Map/LlrbTree.cs
@@ -48,7 +48,7 @@

         public LlrbTree(IComparer<K> comparer)
         {
-            Comparer = (k1, k2) => comparer.Compare(k1, k2);
+			Comparer = comparer.Compare;
         }

         public LlrbTree(Comparison<K> comparison)


renamed alledgedCount to expectedCount for clearer meaning

--- src/LinqContrib/EnumerableExtensions.cs
+++ src/LinqContrib/EnumerableExtensions.cs
@@ -13,15 +13,15 @@
     {
         #region Public Methods and Operators

-        public static bool IsCountEqual<T>(this IEnumerable<T> source, int alledgedCount)
+        public static bool IsCountEqual<T>(this IEnumerable<T> source, int expectedCount)
         {
-            // naive implementation, could be optimized in cases where Count is > alledgedCount.
-            return source.Count() == alledgedCount;
+            // naive implementation, could be optimized in cases where Count is > expectedCount.
+            return source.Count() == expectedCount;
         }

         public static bool IsCountGreater<T>(this IEnumerable<T> source, int comparisonCount)
         {
-            // naive implementation, could be optimized in cases where Count is > alledgedCount.
+            // naive implementation, could be optimized in cases where Count is > comparisonCount.
             return source.Count() > comparisonCount;
         }


LDM: Throw more meaningful exception when trying to access failed volumes.

--- src/LogicalDiskManager/DynamicVolume.cs
+++ src/LogicalDiskManager/DynamicVolume.cs
@@ -23,6 +23,7 @@
 namespace DiscUtils.LogicalDiskManager
 {
     using System;
+    using System.IO;

     internal class DynamicVolume
     {
@@ -62,7 +63,14 @@

         public SparseStream Open()
         {
-            return _group.OpenVolume(Record.Id);
+            if (Status == LogicalVolumeStatus.Failed)
+            {
+                throw new IOException("Attempt to open 'failed' volume");
+            }
+            else
+            {
+                return _group.OpenVolume(Record.Id);
+            }
         }
     }
 }


Update comment

Update comment

Update class documentation.

--- src/LondonTravel.Skill/AlexaFunction.cs
+++ src/LondonTravel.Skill/AlexaFunction.cs
@@ -10,7 +10,7 @@
 namespace MartinCostello.LondonTravel.Skill
 {
     /// <summary>
-    /// A class representing the AWS Lambda handler for the London Travel Amazon Alexa skill.
+    /// A class representing the AWS Lambda function for the London Travel Amazon Alexa skill.
     /// </summary>
     public class AlexaFunction
     {


Revert "Lucene.Net.Search.FieldCacheImpl: Removed field value types and declared Get methods inline using delegate methods"

This reverts commit 34758c1315391794825f33a3f48b5a3dd6083745.

As per #370, using delegates creates extra allocations so we trade some maintainability for top performance in this case.

--- src/Lucene.Net/Search/FieldCacheImpl.cs
+++ src/Lucene.Net/Search/FieldCacheImpl.cs
@@ -580,7 +580,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Bytes(get: (docID) => (byte)valuesIn.Get(docID));
+                return new FieldCache_BytesAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -601,6 +601,24 @@
 #pragma warning disable CS0612 // Type or member is obsolete
                 return caches_typeof_sbyte.Get(reader, new CacheKey<FieldCache.IByteParser>(field, parser), setDocsWithField);
 #pragma warning restore CS0612 // Type or member is obsolete
+            }
+        }
+
+        private class FieldCache_BytesAnonymousInnerClassHelper : FieldCache.Bytes
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_BytesAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override byte Get(int docID)
+            {
+                return (byte)valuesIn.Get(docID);
             }
         }

@@ -738,7 +756,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Int16s(get: (docID) => (short)valuesIn.Get(docID));
+                return new FieldCache_Int16sAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -757,6 +775,24 @@
                 }
                 // LUCENENET specific - eliminated unnecessary Dictionary lookup by declaring each cache as a member variable
                 return caches_typeof_short.Get(reader, new CacheKey<FieldCache.IInt16Parser>(field, parser), setDocsWithField);
+            }
+        }
+
+        private class FieldCache_Int16sAnonymousInnerClassHelper : FieldCache.Int16s
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_Int16sAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override short Get(int docID)
+            {
+                return (short)valuesIn.Get(docID);
             }
         }

@@ -895,7 +931,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Int32s(get: (docID) => (int)valuesIn.Get(docID));
+                return new FieldCache_Int32sAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -914,6 +950,24 @@
                 }
                 // LUCENENET specific - eliminated unnecessary Dictionary lookup by declaring each cache as a member variable
                 return caches_typeof_int.Get(reader, new CacheKey<FieldCache.IInt32Parser>(field, parser), setDocsWithField);
+            }
+        }
+
+        private class FieldCache_Int32sAnonymousInnerClassHelper : FieldCache.Int32s
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_Int32sAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override int Get(int docID)
+            {
+                return (int)valuesIn.Get(docID);
             }
         }

@@ -1175,7 +1229,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Singles(get: (docID) => J2N.BitConversion.Int32BitsToSingle((int)valuesIn.Get(docID)));
+                return new FieldCache_SinglesAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -1194,6 +1248,24 @@
                 }
                 // LUCENENET specific - eliminated unnecessary Dictionary lookup by declaring each cache as a member variable
                 return caches_typeof_float.Get(reader, new CacheKey<FieldCache.ISingleParser>(field, parser), setDocsWithField);
+            }
+        }
+
+        private class FieldCache_SinglesAnonymousInnerClassHelper : FieldCache.Singles
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_SinglesAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override float Get(int docID)
+            {
+                return J2N.BitConversion.Int32BitsToSingle((int)valuesIn.Get(docID));
             }
         }

@@ -1326,7 +1398,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Int64s(get: (docID) => valuesIn.Get(docID));
+                return new FieldCache_Int64sAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -1345,6 +1417,24 @@
                 }
                 // LUCENENET specific - eliminated unnecessary Dictionary lookup by declaring each cache as a member variable
                 return caches_typeof_long.Get(reader, new CacheKey<FieldCache.IInt64Parser>(field, parser), setDocsWithField);
+            }
+        }
+
+        private class FieldCache_Int64sAnonymousInnerClassHelper : FieldCache.Int64s
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_Int64sAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override long Get(int docID)
+            {
+                return valuesIn.Get(docID);
             }
         }

@@ -1489,7 +1579,7 @@
             {
                 // Not cached here by FieldCacheImpl (cached instead
                 // per-thread by SegmentReader):
-                return new FieldCache.Doubles(get: (docID) => J2N.BitConversion.Int64BitsToDouble(valuesIn.Get(docID)));
+                return new FieldCache_DoublesAnonymousInnerClassHelper(this, valuesIn);
             }
             else
             {
@@ -1508,6 +1598,24 @@
                 }
                 // LUCENENET specific - eliminated unnecessary Dictionary lookup by declaring each cache as a member variable
                 return caches_typeof_double.Get(reader, new CacheKey<FieldCache.IDoubleParser>(field, parser), setDocsWithField);
+            }
+        }
+
+        private class FieldCache_DoublesAnonymousInnerClassHelper : FieldCache.Doubles
+        {
+            private readonly FieldCacheImpl outerInstance;
+
+            private NumericDocValues valuesIn;
+
+            public FieldCache_DoublesAnonymousInnerClassHelper(FieldCacheImpl outerInstance, NumericDocValues valuesIn)
+            {
+                this.outerInstance = outerInstance;
+                this.valuesIn = valuesIn;
+            }
+
+            public override double Get(int docID)
+            {
+                return J2N.BitConversion.Int64BitsToDouble(valuesIn.Get(docID));
             }
         }


Add MI debugger working directory to PATH

--- src/MICore/Transports/LocalTransport.cs
+++ src/MICore/Transports/LocalTransport.cs
@@ -21,11 +21,18 @@
         public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer)
         {
             LocalLaunchOptions localOptions = (LocalLaunchOptions)options;
+            string miDebuggerDir = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath);

             Process proc = new Process();
             proc.StartInfo.FileName = localOptions.MIDebuggerPath;
             proc.StartInfo.Arguments = "--interpreter=mi";
-            proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath);
+            proc.StartInfo.WorkingDirectory = miDebuggerDir;
+
+            //GDB locally requires that the directory be on the PATH, being the working directory isn't good enough
+            if (proc.StartInfo.EnvironmentVariables.ContainsKey("PATH"))
+            {
+                proc.StartInfo.EnvironmentVariables["PATH"] = proc.StartInfo.EnvironmentVariables["PATH"] + ";" + miDebuggerDir;
+            }

             InitProcess(proc, out reader, out writer);
         }


Minor cleaning

Minor cleaning

--- src/Migrator.EF6.Tools/ProjectReader.cs
+++ src/Migrator.EF6.Tools/ProjectReader.cs
@@ -1,15 +1,15 @@
-using Microsoft.DotNet.Cli.Utils;
-using NuGet.Frameworks;
-using System;
+using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
+using Microsoft.DotNet.Cli.Utils;
+using NuGet.Frameworks;

 namespace Migrator.EF6.Tools
 {
 	public class ProjectReader
 	{
-		private static Dictionary<string, string> _targetFrameworkMonikerPrefixes = new Dictionary<string, string>()
+		private static readonly Dictionary<string, string> _targetFrameworkMonikerPrefixes = new Dictionary<string, string>
 		{
 			{ "netcoreapp", ".NETCoreApp" },
 			{ "netstandard", ".NETStandard" },
@@ -22,7 +22,7 @@
 			var fileName = Path.GetFileName(Path.GetDirectoryName(projectPath));

 			Project result;
-			using (FileStream fileStream = new FileStream(projectPath, FileMode.Open, FileAccess.Read, FileShare.Read))
+			using (var fileStream = new FileStream(projectPath, FileMode.Open, FileAccess.Read, FileShare.Read))
 			{
 				result = new ProjectReader().ReadProject(fileStream, fileName, projectPath);
 			}
@@ -75,7 +75,7 @@

 			var tmpFile = Path.GetTempFileName();

-			var args = new List<string>()
+			var args = new List<string>
 			{
 				project.ProjectFilePath,
 				"/t:_GetDotNetNames",
@@ -132,9 +132,13 @@

 		public static NuGetFramework GetTargetFramework(string frameworkString)
 		{
-			bool flag = false;
-			var targetFrameworkMonikerPrefix = _targetFrameworkMonikerPrefixes.FirstOrDefault(t => frameworkString.StartsWith(t.Key, StringComparison.OrdinalIgnoreCase) && (flag = true));
-			if (flag == false)
+			var flag = false;
+			var targetFrameworkMonikerPrefix = _targetFrameworkMonikerPrefixes
+				.FirstOrDefault(t =>
+					frameworkString.StartsWith(t.Key, StringComparison.OrdinalIgnoreCase) &&
+					(flag = true));
+
+			if (!flag)
 			{
 				return new NuGetFramework(frameworkString);
 			}


CR LF

CR LF

--- src/MinimumThreadingBridge/IProgress.cs
+++ src/MinimumThreadingBridge/IProgress.cs
@@ -1,7 +1,7 @@
 namespace System
 {
-    public interface IProgress<in T>
-    {
-        void Report(T value);
+    public interface IProgress<in T>
+    {
+        void Report(T value);
     }
 }


Fixed problem in proxy header handlign

Fixed problem in proxy header handlign

--- src/MiningCore/Stratum/StratumClient.cs
+++ src/MiningCore/Stratum/StratumClient.cs
@@ -359,8 +359,6 @@
                     // Update client
                     RemoteEndpoint = new IPEndPoint(IPAddress.Parse(remoteAddress), int.Parse(remotePort));
                     logger.Info(() => $"[{ConnectionId}] Real-IP via Proxy-Protocol: {RemoteEndpoint.Address}");
-
-                    return true;
                 }

                 //else
@@ -370,12 +368,13 @@
                 //}
             }

-            if (proxyProtocol.Mandatory)
+            else if (proxyProtocol.Mandatory)
             {
                 logger.Error(() => $"[{ConnectionId}] Missing mandatory Proxy-Protocol header from {peerAddress}. Closing connection.");
-            }
-
-            return false;
+                return false;
+            }
+
+            return true;
         }
     }
 }


Update AssemblyInfo.cs

Update AssemblyInfo.cs

--- src/NConsole/Properties/AssemblyInfo.cs
+++ src/NConsole/Properties/AssemblyInfo.cs
@@ -6,6 +6,6 @@
 [assembly: AssemblyCompany("Rico Suter")]
 [assembly: AssemblyProduct("NConsole")]
 [assembly: AssemblyCopyright("Copyright © Rico Suter, 2015")]
-[assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.1.*")]

 [assembly: InternalsVisibleTo("NConsole.Tests")]


NH-1163 - Applying patch from Matthew Gabeler-Lee, adding support for identity columns to SQLiteDialect

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@3025

--- src/NHibernate/Dialect/SQLiteDialect.cs
+++ src/NHibernate/Dialect/SQLiteDialect.cs
@@ -82,5 +82,25 @@
 		{
 			get { return true; }
 		}
+
+		public override bool HasDataTypeInIdentityColumn
+		{
+			get { return false; }
+		}
+
+		public override bool SupportsIdentityColumns
+		{
+			get { return true; }
+		}
+
+		public override string IdentityColumnString
+		{
+			get
+			{
+				// identity columns in sqlite are marked as being integer primary key
+				// the primary key part will be put in at the end of the create table,
+				// so just the integer part is needed here
+				return "integer";
+			}
 	}
-}+}


don't call expensive method triple

don't call expensive method triple

--- src/NLog/Internal/ObjectGraphScanner.cs
+++ src/NLog/Internal/ObjectGraphScanner.cs
@@ -78,7 +78,8 @@
                 return;
             }

-            if (!o.GetType().IsDefined(typeof(NLogConfigurationItemAttribute), true))
+            var type = o.GetType();
+            if (!type.IsDefined(typeof(NLogConfigurationItemAttribute), true))
             {
                 return;
             }
@@ -98,10 +99,10 @@

             if (InternalLogger.IsTraceEnabled)
             {
-                InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), o.GetType().Name, o);
+                InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), type.Name, o);
             }

-            var allReadableProperties = PropertyHelper.GetAllReadableProperties(o.GetType()).ToList();
+            var allReadableProperties = PropertyHelper.GetAllReadableProperties(type).ToList();
             foreach (PropertyInfo prop in allReadableProperties)
             {
                 if (prop.PropertyType.IsPrimitive || prop.PropertyType.IsEnum || prop.PropertyType == typeof(string) || prop.IsDefined(typeof(NLogConfigurationIgnorePropertyAttribute), true))


Rename SELECT * test cases to match naming convention

--- src/NQuery.UnitTests/SelectStarTests.cs
+++ src/NQuery.UnitTests/SelectStarTests.cs
@@ -9,7 +9,7 @@
     public class SelectStarTests
     {
         [TestMethod]
-        public void Binder_DisallowsSelectStarWithoutTables()
+        public void SelectStar_Disallowed_WhenNoTablesSpecified()
         {
             var syntaxTree = SyntaxTree.ParseQuery("SELECT *");
             var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable();
@@ -21,7 +21,7 @@
         }

         [TestMethod]
-        public void Binder_DisallowsSelectStarWithoutTables_UnlessInExists()
+        public void SelectStar_Disallowed_WhenNoTablesSpecified_UnlessInExists()
         {
             var syntaxTree = SyntaxTree.ParseQuery("SELECT 'Test' WHERE EXISTS (SELECT *)");
             var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable();


Fixed build warning

Fixed build warning

--- src/NetworkUtility/EventQueueManager.cs
+++ src/NetworkUtility/EventQueueManager.cs
@@ -24,7 +24,7 @@
         /// <param name="arg2">Value of second argument to pass to <paramref name="func" />.</param>
         /// <param name="arg3">Value of third argument to pass to <paramref name="func" />.</param>
         /// <param name="arg4">Value of fourth argument to pass to <paramref name="func" />.</param>
-        /// <param name="syncRoot"The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param>
+        /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param>
         /// <param name="func">Function to be invoked, which may result in events being raised.</param>
         /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns>
         /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> Raise
@@ -46,7 +46,7 @@
         /// <param name="arg2">Value of second argument to pass to <paramref name="method" />.</param>
         /// <param name="arg3">Value of third argument to pass to <paramref name="method" />.</param>
         /// <param name="arg4">Value of fourth argument to pass to <paramref name="method" />.</param>
-        /// <param name="syncRoot"The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param>
+        /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param>
         /// <param name="method">Method to be invoked, which may result in events being raised.</param>
         /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> Raise
         /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks>
@@ -133,7 +133,7 @@
         /// <typeparam name="T">Type of argument to pass to <paramref name="func" />.</typeparam>
         /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam>
         /// <param name="arg">Value of argument to pass to <paramref name="func" />.</param>
-        /// <param name="syncRoot"The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param>
+        /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param>
         /// <param name="func">Function to be invoked, which may result in events being raised.</param>
         /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns>
         /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> Raise


Random: NextBoolean extension

Random: NextBoolean extension

--- src/Numerics/Random/RandomExtensions.cs
+++ src/Numerics/Random/RandomExtensions.cs
@@ -178,7 +178,7 @@
         /// </summary>
         /// <param name="rnd">The random number generator.</param>
         /// <returns>
-        /// A 64-bit signed integer greater than or equal to 0, and less than <see cref="Int64.MaxValue"/>; that is,
+        /// A 64-bit signed integer greater than or equal to 0, and less than <see cref="Int64.MaxValue"/>; that is,
         /// the range of return values includes 0 but not <see cref="Int64.MaxValue"/>.
         /// </returns>
         /// <seealso cref="NextFullRangeInt64"/>
@@ -246,7 +246,7 @@
         /// </summary>
         /// <param name="rnd">The random number generator.</param>
         /// <returns>
-        /// A decimal floating point number greater than or equal to 0.0, and less than 1.0; that is,
+        /// A decimal floating point number greater than or equal to 0.0, and less than 1.0; that is,
         /// the range of return values includes 0.0 but not 1.0.
         /// </returns>
         /// <remarks>
@@ -273,5 +273,18 @@

             return candidate;
         }
+
+        /// <summary>
+        /// Returns a random boolean.
+        /// </summary>
+        /// <param name="rnd">The random number generator.</param>
+        /// <remarks>
+        /// This extension is thread-safe if and only if called on an random number
+        /// generator provided by Math.NET Numerics or derived from the RandomSource class.
+        /// </remarks>
+        public static bool NextBoolean(this System.Random rnd)
+        {
+            return rnd.NextDouble() >= 0.5;
+        }
     }
 }


Implement endpoint for remove instance

Implement endpoint for remove instance

--- src/Okanshi.Dashboard/SettingsModule.cs
+++ src/Okanshi.Dashboard/SettingsModule.cs
@@ -22,6 +22,12 @@
 				configuration.Add(server);
 				return Response.AsRedirect("/settings");
 			};
+			Post["/settings/delete"] = p =>
+			{
+				var name = (string)Request.Form.InstanceName;
+				configuration.Remove(name);
+				return Response.AsRedirect("/settings");
+			};
 		}
 	}
 }


Handle null

Handle null

--- src/Package/Impl/TaskList/VsTaskItem.cs
+++ src/Package/Impl/TaskList/VsTaskItem.cs
@@ -55,7 +55,7 @@
             }

             var textBuffer = _source.EditorBuffer as ITextBuffer;
-            HierarchyItem = textBuffer.GetHierarchy();
+            HierarchyItem = textBuffer?.GetHierarchy();

             return oldLine != Line ||
                    oldColumn != Column ||


Automatically load native delegates in extensions

--- src/SampSharp.GameMode/API/Extension.cs
+++ src/SampSharp.GameMode/API/Extension.cs
@@ -26,6 +26,8 @@
         /// </returns>
         public static bool Register<T>(T extension) where T : class
         {
+            Native.LoadDelegates<T>();
+
             return Interop.RegisterExtension(extension);
         }
     }


Ldfld/Ldflda: Also supports loading fields from pointer types (NativeInt).

--- src/SharpLang.Compiler/Compiler.Emit.cs
+++ src/SharpLang.Compiler/Compiler.Emit.cs
@@ -451,7 +451,7 @@
             // Build indices for GEP
             var indices = new List<ValueRef>(3);

-            if (stackValueType == StackValueType.Reference || stackValueType == StackValueType.Object)
+            if (stackValueType == StackValueType.Reference || stackValueType == StackValueType.Object || stackValueType == StackValueType.NativeInt)
             {
                 // First pointer indirection
                 indices.Add(LLVM.ConstInt(int32Type, 0, false));


Adding unit conversion methods FromMillimetersToPoints(double), FromPointsToMillimeters(double), FromInchesToMillimeters(double), FromMillimetersToInches(double).

--- src/StevenVolckaert.Core/UnitConvert.cs
+++ src/StevenVolckaert.Core/UnitConvert.cs
@@ -10,6 +10,16 @@
         private const double MillimetersPerInch = 25.4;
         private const double MillimetersPerFoot = MillimetersPerInch * 12;
         private const double MillimetersPerYard = MillimetersPerFoot * 3;
+
+        /// <summary>
+        ///     The millimeters per DTP point. The DTP is defined as 1⁄72 of an international inch
+        ///     (exactly 25.4 mm).
+        /// </summary>
+        /// <remarks>
+        ///     See https://en.wikipedia.org/wiki/Point_(typography) for more information.
+        /// </remarks>
+        private const double MillimetersPerPoint = MillimetersPerInch / 72;
+
         private const double MetersPerFoot = MillimetersPerFoot / 1000;
         private const double MetersPerYard = MillimetersPerYard / 1000;

@@ -76,6 +86,16 @@
         }

         /// <summary>
+        ///     Converts a value in international inches to its equivalent in millimeters.
+        /// </summary>
+        /// <param name="value">The value to convert.</param>
+        /// <returns>The value in millimeters.</returns>
+        public static double FromInchesToMillimeters(double value)
+        {
+            return value * MillimetersPerInch;
+        }
+
+        /// <summary>
         ///     Converts a value in meters to its equivalent in feet.
         /// </summary>
         /// <param name="value">The value to convert.</param>
@@ -94,5 +114,35 @@
         {
             return value / MetersPerFoot;
         }
+
+        /// <summary>
+        ///     Converts a value in millimeters to its equivalent in international inches.
+        /// </summary>
+        /// <param name="value">The value to convert.</param>
+        /// <returns>The value in international inches.</returns>
+        public static double FromMillimetersToInches(double value)
+        {
+            return value / MillimetersPerInch;
+        }
+
+        /// <summary>
+        ///     Converts a value in millimeters to its equivalent in DTPs (Desktop Publishing Points).
+        /// </summary>
+        /// <param name="value">The value to convert.</param>
+        /// <returns>The value in DTPs (Desktop Publishing Points).</returns>
+        public static double FromMillimetersToPoints(double value)
+        {
+            return value / MillimetersPerPoint;
+        }
+
+        /// <summary>
+        ///     Converts a value in DTPs (Desktop Publishing Points) to its equivalent in millimeters.
+        /// </summary>
+        /// <param name="value">The value to convert.</param>
+        /// <returns>The value in millimeters.</returns>
+        public static double FromPointsToMillimeters(double value)
+        {
+            return value * MillimetersPerPoint;
+        }
     }
 }


Fix NullReferenceException when adding child work items

--- src/TfsBot/Models/SlackWorkItemModel.cs
+++ src/TfsBot/Models/SlackWorkItemModel.cs
@@ -53,13 +53,17 @@
             if (hookModel != null)
             {
                 model.EventType = hookModel.EventType;
-                model.IsAssigmentChanged = hookModel.Resource.Fields.AssignedTo?.NewValue != hookModel.Resource.Fields.AssignedTo?.OldValue;
-                model.IsStateChanged = hookModel.Resource.Fields.State?.NewValue != hookModel.Resource.Fields.State?.OldValue;
-                model.PreviousState = hookModel.Resource.Fields.State?.OldValue;
+                model.Rev = hookModel.Resource.Rev;

-                model.IsBoardColumnChanged = hookModel.Resource.Fields.BoardColumn?.NewValue != hookModel.Resource.Fields.BoardColumn?.OldValue;
-                model.PreviousBoardColumn = hookModel.Resource.Fields.BoardColumn?.OldValue;
-                model.Rev = hookModel.Resource.Rev;
+                if (hookModel.Resource.Fields != null)
+                {
+                    model.IsAssigmentChanged = hookModel.Resource.Fields.AssignedTo?.NewValue != hookModel.Resource.Fields.AssignedTo?.OldValue;
+                    model.IsStateChanged = hookModel.Resource.Fields.State?.NewValue != hookModel.Resource.Fields.State?.OldValue;
+                    model.PreviousState = hookModel.Resource.Fields.State?.OldValue;
+
+                    model.IsBoardColumnChanged = hookModel.Resource.Fields.BoardColumn?.NewValue != hookModel.Resource.Fields.BoardColumn?.OldValue;
+                    model.PreviousBoardColumn = hookModel.Resource.Fields.BoardColumn?.OldValue;
+                }
             }

             return model;


Remove Console.WriteLine from time_to_main.

--- managed/time_to_main/src/Program.cs
+++ managed/time_to_main/src/Program.cs
@@ -10,7 +10,6 @@

         public static void Main(string[] args)
         {
-            Console.WriteLine("Hello World!");
             write_marker("/function/main");
         }
     }


Removed some unnecessary using statements.

--- src/Whodunit.app/Events/CreateTables.cs
+++ src/Whodunit.app/Events/CreateTables.cs
@@ -1,14 +1,11 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
 using Umbraco.Core;
 using Umbraco.Core.Logging;
 using Umbraco.Core.Persistence;
 using Whodunit.app.Models;

-namespace Whodunit.app.Events {
+namespace Whodunit.app.Events
+{
     public class CreateTables : ApplicationEventHandler {

         protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) {
@@ -29,4 +26,4 @@
         }

     }
-}
+}


Added OnComplete property missing in AjaxOptions class

--- src/X.PagedList.Mvc.Core/AjaxOptions.cs
+++ src/X.PagedList.Mvc.Core/AjaxOptions.cs
@@ -4,20 +4,22 @@
 {
     public class AjaxOptions
     {
-        public IEnumerable<HtmlAttribute> ToUnobtrusiveHtmlAttributes()
+        public virtual IEnumerable<HtmlAttribute> ToUnobtrusiveHtmlAttributes()
         {
             return new List<HtmlAttribute>
             {
                 new HtmlAttribute {Key = "data-ajax-method", Value = HttpMethod},
                 new HtmlAttribute {Key = "data-ajax-mode", Value = InsertionMode},
                 new HtmlAttribute {Key = "data-ajax-update", Value = "#" + UpdateTargetId},
-                new HtmlAttribute {Key = "data-ajax", Value = "true"}
+                new HtmlAttribute {Key = "data-ajax", Value = "true"},
+                new HtmlAttribute {Key = "data-ajax-complete", Value = OnComplete}
             };
         }

         public string HttpMethod { get; set; }
         public InsertionMode InsertionMode { get; set; }
         public string UpdateTargetId { get; set; }
+        public string OnComplete { get; set; }
     }

     public enum InsertionMode


updated windows proj for vs2012

updated windows proj for vs2012

--- Source/Filename.cs
+++ Source/Filename.cs
@@ -89,7 +89,7 @@
 		/// <param name="strFileName">the string to use as an absolute filename</param>
 		public Filename(string strFilename)
 		{
-			m_strFilename = strFilename;
+			SetRelFilename(strFilename);
 		}

 		/// <summary>


mover smoother into a submodule

mover smoother into a submodule

--- Source/Smoother.cs
+++ Source/Smoother.cs
@@ -1,74 +0,0 @@
-using System.Collections.Generic;
-
-namespace FlockBuddy
-{
-	/// <summary>
-	/// Template class to help calculate the average value of a history of values.
-	/// This can only be used with types that have a 'zero' and that have the += and / operators overloaded.
-	/// Example: Used to smooth frame rate calculations.
-	/// </summary>
-	/// <typeparam name="T"></typeparam>
-	public class Smoother<T>
-	{
-		#region Members
-
-		/// <summary>
-		/// this holds the history
-		/// </summary>
-		private Queue<T> History { get; set; }
-
-		/// <summary>
-		/// The max smaple size we want
-		/// </summary>
-		public int MaxSize { get; set; }
-
-		/// <summary>
-		/// an example of the 'zero' value of the type to be smoothed.
-		/// This would be something like Vector2D(0,0)
-		/// </summary>
-		private T ZeroValue;
-
-		#endregion //Members
-
-		#region Methods
-
-		//to instantiate a Smoother pass it the number of samples you want
-		//to use in the smoothing, and an exampe of a 'zero' type
-		public Smoother(int SampleSize, T ZeroValue)
-		{
-			m_History = new Queue<T>();
-			MaxSize = SampleSize;
-			m_ZeroValue = ZeroValue;
-		}
-
-		/// <summary>
-		/// each time you want to get a new average, feed it the most recent value
-		/// and this method will return an average over the last SampleSize updates
-		/// </summary>
-		/// <param name="MostRecentValue"></param>
-		/// <returns></returns>
-		public T Update(T MostRecentValue)
-		{
-			//add the new value to the beginning
-			History.Enqueue(MostRecentValue);
-
-			//pop enough items off to stay in the correct size
-			while (History.Count > MaxSize)
-			{
-				History.Dequeue();
-			}
-
-			//now to calculate the average of the history list
-			T sum = m_ZeroValue;
-
-			foreach (var iter in History)
-			{
-				sum += iter;
-			}
-
-			return sum / (float)History.size();
-		}
-
-		#endregion //Methods
-	}
-}


fix DateTime.DaysInMonth return days for the wrong month

--- System/DateTime.cs
+++ System/DateTime.cs
@@ -246,7 +246,7 @@
 	    public static int DaysInMonth(int year, int month)
 	    {
             // Create a calendar object and set year and month
-            Calendar mycal = new Java.Util.GregorianCalendar(year, month, 1);
+            Calendar mycal = new Java.Util.GregorianCalendar(year, month - MonthOffset, 1);

             // Get the number of days in that month
             return  mycal.GetActualMaximum(Calendar.DAY_OF_MONTH);


Added Game.Copy() with summary explaining why it's there.

--- Sandra.Chess/Game.cs
+++ Sandra.Chess/Game.cs
@@ -28,24 +28,34 @@
     public class Game
     {
         private readonly Position initialPosition;
-
         private readonly MoveTree moveTree;

         private Position currentPosition;
-
-        // Points at the variation with the move which was just played in the current position.
-        // Is null at the start of the game.
         private MoveTree activeTree;

-        public Game(Position initialPosition)
+        private Game(Position initialPosition, MoveTree moveTree)
         {
             this.initialPosition = initialPosition;
             currentPosition = initialPosition.Copy();
-            moveTree = new MoveTree(initialPosition.SideToMove == Color.Black);
+            this.moveTree = moveTree;
             activeTree = moveTree;
         }

         /// <summary>
+        /// Creates a new game with a given initial <see cref="Position"/>.
+        /// </summary>
+        public Game(Position initialPosition) : this(initialPosition,
+                                                     new MoveTree(initialPosition.SideToMove == Color.Black))
+        {
+        }
+
+        /// <summary>
+        /// Returns a copy of this game, with the same initial <see cref="Position"/> and shared <see cref="Chess.MoveTree"/>,
+        /// but in which <see cref="ActiveTree"/> can be manipulated independently.
+        /// </summary>
+        public Game Copy() => new Game(initialPosition, moveTree);
+
+        /// <summary>
         /// Gets the initial position of this game.
         /// </summary>
         public Position InitialPosition => initialPosition.Copy();
@@ -54,6 +64,11 @@
         /// Gets the <see cref="Color"/> of the side to move in the initial position.
         /// </summary>
         public Color InitialSideToMove => initialPosition.SideToMove;
+
+        /// <summary>
+        /// Gets a reference to the root of the <see cref="Chess.MoveTree"/> of this <see cref="Game"/>.
+        /// </summary>
+        public MoveTree MoveTree => moveTree;

         /// <summary>
         /// Gets the current position of this game.
@@ -133,8 +148,6 @@
             activeTree = activeTree.Main.MoveTree;
             RaiseActiveMoveIndexChanged();
         }
-
-        public MoveTree MoveTree => moveTree;

         /// <summary>
         /// Gets the <see cref="Color"/> of the side to move.


Server: update CreateSalesOrder

Server: update CreateSalesOrder

--- Server/DigiMarket.cs
+++ Server/DigiMarket.cs
@@ -447,7 +447,9 @@
             // get available offers
             var availablePurchaseOrders = PurchaseOrders.Where(order => !order.FulFilled && order.Buyer != requestingUser);
             var purchaseOrders = availablePurchaseOrders as IList<PurchaseOrder> ?? availablePurchaseOrders.ToList();
+
             var numOffers = purchaseOrders.Sum(  order => order.Count);
+            var surplus = quantity - numOffers;

             if (numOffers == 0)
             {
@@ -487,6 +489,17 @@
                 requestingUser.Diginotes.RemoveWhere(diginote => selectedDiginotes.Contains(diginote));
             }

+            // SalesOrder is totally fulfilled
+            if (surplus <= 0)
+            {
+                SalesOrders.Add(new SalesOrder(requestingUser, quantity, Quotation, true));
+            }
+            else
+            {
+                SalesOrders.Add(new SalesOrder(requestingUser, numOffers, Quotation, true));
+                SalesOrders.Add(new SalesOrder(requestingUser, surplus, Quotation));
+            }
+
             PublishMessage(Update.Balance);
             PublishMessage(Update.General);
             PublishMessage(Update.Diginotes);


Fixed container background not drawn

Fixed container background not drawn

--- Dependencies/Renderer.PdfSharp-wpf/PdfRenderer.cs
+++ Dependencies/Renderer.PdfSharp-wpf/PdfRenderer.cs
@@ -196,7 +196,7 @@
                 // draw container contents to pdf graphics
                 DrawBackgroundInternal(
                     gfx,
-                    container.Template.Background,
+                    container.Background,
                     Test2d.Rect2.Create(0, 0, page.Width.Value / scale, page.Height.Value / scale));
                 Draw(gfx, container, container.Properties, null);
             }


Fix: Generate pdf for unimported users

Fix: Generate pdf for unimported users

If a user wasn't previously imported into the database generating of
PDFs failed. This change attempts to import the user if its not found.

--- Disco.Web/Areas/API/Controllers/UserController.cs
+++ Disco.Web/Areas/API/Controllers/UserController.cs
@@ -169,6 +169,13 @@
             id = ActiveDirectory.ParseDomainAccountId(id, Domain);

             var user = Database.Users.Find(id);
+
+            if (user == null)
+            {
+                // Try importing the user
+                user = UserService.GetUser(id, Database, true);
+            }
+
             if (user != null)
             {
                 var documentTemplate = Database.DocumentTemplates.Find(DocumentTemplateId);


add the fileset file to dlist

add the fileset file to dlist

we also jsut set PartialBackup=false just to be clear and not assume the value

--- Duplicati/Library/Main/Operation/BackupHandler.cs
+++ Duplicati/Library/Main/Operation/BackupHandler.cs
@@ -30,6 +30,8 @@
 using Duplicati.Library.Utility;
 using Duplicati.Library.Common.IO;
 using Duplicati.Library.Common;
+using Duplicati.Library.Main.Operation.Backup;
+using Duplicati.Library.Main.Operation.Common;

 namespace Duplicati.Library.Main.Operation
 {
@@ -241,11 +243,11 @@

                 if (token.IsCancellationRequested)
                 {
-
                     result.PartialBackup = true;
                 }
                 else
                 {
+                    result.PartialBackup = false;
                     await database.UpdateFilesetAndMarkAsFullBackupAsync(filesetid);
                 }

@@ -499,8 +501,11 @@
                             }
                         }

+                        // Add the fileset file to the dlist file
+                        filesetvolume.CreateFilesetFile(!token.IsCancellationRequested);
+
                         // Ensure the database is in a sane state after adding data
-                        using(new Logging.Timer(LOGTAG, "VerifyConsistency", "VerifyConsistency"))
+                        using (new Logging.Timer(LOGTAG, "VerifyConsistency", "VerifyConsistency"))
                             await db.VerifyConsistencyAsync(m_options.Blocksize, m_options.BlockhashSize, false);

                         // Send the actual filelist


Fixed missing info

Fixed missing info

--- Duplicati/Library/Main/Operation/BackupHandler.cs
+++ Duplicati/Library/Main/Operation/BackupHandler.cs
@@ -109,7 +109,7 @@
                 catch (Exception ex)
                 {
                     if (m_logWriter != null)
-                        m_logWriter.AddWarning(string.Format("Failed to process path: ", path), ex);
+                        m_logWriter.AddWarning(string.Format("Failed to process path: {0}", path), ex);
                     return false;
                 }


Simplify implementation of keep-versions logic.

--- Duplicati/Library/Main/Operation/DeleteHandler.cs
+++ Duplicati/Library/Main/Operation/DeleteHandler.cs
@@ -225,43 +225,29 @@
             // and remove oldest backups while there are still more backups than should be kept as specified via option
             var backupsRemaining = sortedAllBackups.Except(toDelete).ToList();
             var fullVersionsToKeep = m_options.KeepVersions;
-            var fullVersionsKeptCount = 0;
             if (fullVersionsToKeep > 0 && fullVersionsToKeep < backupsRemaining.Count)
             {
+                int fullVersionsKept = 0;
                 ISet<DateTime> intermediatePartials = new HashSet<DateTime>();
-                bool haveFullBackup = false;
-
-                // Keep the number of full backups specified in fullVersionsToKeep.
-                // Remove partial backups that are followed by full backups.
-                // Once enough versions are kept, delete all older backups.
-                foreach (var backup in backupsRemaining)
-                {
-                    bool isFullBackup = db.IsFilesetFullBackup(backup);
-                    if (isFullBackup)
-                    {
+
+                // Enumerate the collection starting from the most recent full backup.
+                foreach (DateTime backup in backupsRemaining.SkipWhile(x => !db.IsFilesetFullBackup(x)))
+                {
+                    if (fullVersionsKept >= fullVersionsToKeep)
+                    {
+                        // If we have enough full backups, delete all older backups.
+                        toDelete.Add(backup);
+                    }
+                    else if (db.IsFilesetFullBackup(backup))
+                    {
+                        // We can delete partial backups that are surrounded by full backups.
                         toDelete.AddRange(intermediatePartials);
                         intermediatePartials.Clear();
-                        haveFullBackup = true;
-                    }
-                    else
-                    {
-                        // Only consider a partial backup for deletion if we have already encountered a full backup.
-                        if (haveFullBackup)
-                        {
-                            intermediatePartials.Add(backup);
-                        }
-                    }
-
-                    if (fullVersionsKeptCount < fullVersionsToKeep)
-                    {
-                        if (isFullBackup)
-                        {
-                            fullVersionsKeptCount++;
-                        }
-                    }
-                    else
-                    {
-                        toDelete.Add(backup);
+                        fullVersionsKept++;
+                    }
+                    else
+                    {
+                        intermediatePartials.Add(backup);
                     }
                 }
             }