tests around CanMonitor.

tests around CanMonitor.

--- src/LiberisLabs.DogStatsD.Interceptors.Tests/Monitors/InstrumentMonitorTests.cs
+++ src/LiberisLabs.DogStatsD.Interceptors.Tests/Monitors/InstrumentMonitorTests.cs
@@ -1,4 +1,6 @@
-using LiberisLabs.DogStatsD.Interceptors.Monitors;
+using System.Reflection;
+using LiberisLabs.DogStatsD.Interceptors.Annotations;
+using LiberisLabs.DogStatsD.Interceptors.Monitors;
 using LiberisLabs.DogStatsD.Interceptors.Tests.Helpers;
 using Moq;
 using NUnit.Framework;
@@ -52,5 +54,61 @@

             _dogStatsd.Verify(x => x.Increment("namespace.classname.methodname.success", 1, 1D, null), Times.Once);
         }
+
+        [Test]
+        public void WhenCallingCanMonitorWithNoAttibutesOn_ReturnsFalse()
+        {
+            var methodInfo = new Mock<MethodInfo>();
+            methodInfo.Setup(x => x.GetCustomAttributes(typeof(InstrumentAttribute), false))
+                .Returns(new InstrumentAttribute[0]);
+
+            var result = _monitor.CanMonitor(methodInfo.Object, methodInfo.Object);
+
+            Assert.That(result, Is.False);
+        }
+
+        [Test]
+        public void WhenCallingCanMonitorWithAttibutesOnMethodInfo_ReturnsTrue()
+        {
+            var methodInfo = new Mock<MethodInfo>();
+            methodInfo.Setup(x => x.GetCustomAttributes(typeof (InstrumentAttribute), false))
+                .Returns(new[] {new InstrumentAttribute()});
+
+            var methodInvocationTarget = new Mock<MethodInfo>();
+            methodInvocationTarget.Setup(x => x.GetCustomAttributes(typeof(InstrumentAttribute), false))
+                .Returns(new InstrumentAttribute[0]);
+
+            var result = _monitor.CanMonitor(methodInfo.Object, methodInvocationTarget.Object);
+
+            Assert.That(result, Is.True);
+        }
+
+        [Test]
+        public void WhenCallingCanMonitorWithAttibutesOnMethodInvocationTarget_ReturnsTrue()
+        {
+            var methodInfo = new Mock<MethodInfo>();
+            methodInfo.Setup(x => x.GetCustomAttributes(typeof(InstrumentAttribute), false))
+                .Returns(new InstrumentAttribute[0]);
+
+            var methodInvocationTarget = new Mock<MethodInfo>();
+            methodInvocationTarget.Setup(x => x.GetCustomAttributes(typeof(InstrumentAttribute), false))
+                .Returns(new[] { new InstrumentAttribute() });
+
+            var result = _monitor.CanMonitor(methodInfo.Object, methodInvocationTarget.Object);
+
+            Assert.That(result, Is.True);
+        }
+
+        [Test]
+        public void WhenCallingCanMonitorWithAttibutesBothMethodInfo_ReturnsTrue()
+        {
+            var methodInfo = new Mock<MethodInfo>();
+            methodInfo.Setup(x => x.GetCustomAttributes(typeof(InstrumentAttribute), false))
+                .Returns(new[] { new InstrumentAttribute() });
+
+            var result = _monitor.CanMonitor(methodInfo.Object, methodInfo.Object);
+
+            Assert.That(result, Is.True);
+        }
     }
 }


Revert IsWarning code path to avoid breaking change (e.g., if someone overrode OnErrorDataReceived to receive such lines)

--- src/Microsoft.AspNetCore.NodeServices/HostingModels/OutOfProcessNodeInstance.cs
+++ src/Microsoft.AspNetCore.NodeServices/HostingModels/OutOfProcessNodeInstance.cs
@@ -383,10 +383,6 @@
                     {
                         OutputLogger.LogWarning(evt.Data);
                     }
-                    else if (IsWarning(evt.Data))
-                    {
-                        OutputLogger.LogWarning(evt.Data);
-                    }
                     else if (!initializationIsCompleted)
                     {
                         _connectionIsReadySource.SetException(
@@ -410,11 +406,6 @@
                 message.StartsWith("Debugger listening ", StringComparison.OrdinalIgnoreCase) ||
                 message.StartsWith("To start debugging", StringComparison.OrdinalIgnoreCase) ||
                 message.Contains("chrome-devtools:");
-        }
-
-        private static bool IsWarning(string message)
-        {
-            return message.StartsWith("Warning:", StringComparison.OrdinalIgnoreCase);
         }

         private FileSystemWatcher BeginFileWatcher(string rootDir)


Address PR feedback and use pattern matching.

--- src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs
+++ src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs
@@ -118,15 +118,13 @@
             }

             ISymbol targetSymbol;
-            var invocation = parent as IInvocationExpression;
-            if (invocation != null)
+            if (parent is IInvocationExpression invocation)
             {
                 targetSymbol = invocation.TargetMethod;
             }
             else
             {
-                var objectCreation = parent as IObjectCreationExpression;
-                if (objectCreation != null)
+                if (parent is IObjectCreationExpression objectCreation)
                 {
                     targetSymbol = objectCreation.Constructor;
                 }


Extensions - Resource dropdown is not populated (#591)

* DNN-21484 Fixed resource dropdown for manifest files on module's creation.

* Code review

--- src/Modules/Settings/Dnn.PersonaBar.Extensions/Services/ExtensionsController.cs
+++ src/Modules/Settings/Dnn.PersonaBar.Extensions/Services/ExtensionsController.cs
@@ -29,6 +29,7 @@
 using System.Net.Http.Headers;
 using System.Reflection;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web.Http;
@@ -64,6 +65,7 @@
     public class ExtensionsController : PersonaBarApiController
     {
         private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExtensionsController));
+        private static readonly Regex ManifestExensionsRegex = new Regex(@"dnn\d*$");
         private readonly Components.ExtensionsController _controller = new Components.ExtensionsController();
         private static readonly string[] SpecialModuleFolders = new[] { "mvc" };
         private const string AuthFailureMessage = "Authorization has been denied for this request.";
@@ -982,8 +984,7 @@
                         files.AddRange(GetFiles(Globals.HostMapPath + "Templates\\", ".module.template"));
                         break;
                     case FileType.Manifest:
-                        files.AddRange(GetFiles(folder, "*.dnn"));
-                        files.AddRange(GetFiles(folder, "*.dnn5"));
+                        files.AddRange(GetFiles(folder, "*.dnn*").Where(file => ManifestExensionsRegex.IsMatch(file)));
                         break;
                 }


682.1

--- src/PixelFarm/PixelFarm.CpuBlit/03_Rasterization_Lines/4_OutlineAARasterizer.cs
+++ src/PixelFarm/PixelFarm.CpuBlit/03_Rasterization_Lines/4_OutlineAARasterizer.cs
@@ -449,7 +449,7 @@
                             x2 = v.x;
                             y2 = v.y;
                             dv.lcurr = v.len;
-                            LineParameters prev = new LineParameters(x1, y1, x2, y2, lprev);
+                            var prev = new LineParameters(x1, y1, x2, y2, lprev);
                             v = m_src_vertices[2];
                             dv1.x1 = v.x;
                             dv1.y1 = v.y;


Removing incorrect error numbers

Removing incorrect error numbers

Error codes 40020, 40143, 40166, and 40540 are embedded within the message of 40197 and not SQL error numbers to retry on.

--- src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
+++ src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
@@ -132,13 +132,6 @@
             // additional information about the kind of failure or failover that occurred. Some examples of the error codes are
             // embedded within the message of error 40197 are 40020, 40143, 40166, and 40540.
             40197,
-
-            40020,
-            40143,
-            40166,
-
-            // The service has encountered an error processing your request. Please try again.
-            40540,

             // The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d.
             40501,


Fix NRE

Fix NRE

--- BTCPayServer/HostedServices/StoreEmailRuleProcessorSender.cs
+++ BTCPayServer/HostedServices/StoreEmailRuleProcessorSender.cs
@@ -53,7 +53,7 @@
                     var sender = await _emailSenderFactory.GetEmailSender(invoiceEvent.Invoice.StoreId);
                     foreach (UIStoresController.StoreEmailRule actionableRule in actionableRules)
                     {
-                        var recipients = actionableRule.To.Split(",", StringSplitOptions.RemoveEmptyEntries)
+                        var recipients = (actionableRule.To?.Split(",", StringSplitOptions.RemoveEmptyEntries)??Array.Empty<string>())
                             .Select(o => { MailboxAddressValidator.TryParse(o, out var mb); return mb; })
                             .Where(o => o != null)
                             .ToList();


if we already do psn des checks, let's do one properly then

--- CompatBot/Utils/ResultFormatters/LogParserResultFormatter.cs
+++ CompatBot/Utils/ResultFormatters/LogParserResultFormatter.cs
@@ -59,6 +59,14 @@
             var collection = state.CompleteCollection ?? state.WipCollection;
             if (collection?.Count > 0)
             {
+                if (KnownDiscOnPsnIds.TryGetValue(collection["serial"], out var psnSerial)
+                    && collection["ldr_game_serial"] is string ldrGameSerial
+                    && ldrGameSerial.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase)
+                    && ldrGameSerial.Equals(psnSerial, StringComparison.InvariantCultureIgnoreCase))
+                {
+                    collection["serial"] = psnSerial;
+                    collection["game_category"] = "HG";
+                }
                 var gameInfo = await client.LookupGameInfoAsync(collection["serial"], collection["game_title"], true).ConfigureAwait(false);
                 builder = new DiscordEmbedBuilder(gameInfo) {ThumbnailUrl = null}; // or this will fuck up all formatting
                 if (state.Error == LogParseState.ErrorCode.PiracyDetected)
@@ -451,10 +459,7 @@
                 discInsideGame |= !string.IsNullOrEmpty(items["ldr_disc"]) && !(items["serial"]?.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase) ?? false);
                 discAsPkg |= items["serial"]?.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase) ?? false;
                 discAsPkg |= items["ldr_game_serial"] is string ldrGameSerial
-                             && ldrGameSerial.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase)
-                             && KnownDiscOnPsnIds.TryGetValue(items["serial"], out var whitelistedPsnMatch)
-                             && whitelistedPsnMatch is string matchingPsnId
-                             && !ldrGameSerial.Equals(matchingPsnId, StringComparison.InvariantCultureIgnoreCase);
+                             && ldrGameSerial.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase);
             }
             discAsPkg |= items["game_category"] == "HG" && !(items["serial"]?.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase) ?? false);
             if (discInsideGame)


Full CRUD for Images functional

Full CRUD for Images functional

--- DefinitelyNotGallery/DNG.Web/Controllers/ImagesController.cs
+++ DefinitelyNotGallery/DNG.Web/Controllers/ImagesController.cs
@@ -5,6 +5,7 @@
     using DNG.Web.Models;
     using System.Linq;
     using System.Web.Http;
+    using Microsoft.AspNet.Identity;

     public class ImagesController : BaseApiController
     {
@@ -48,5 +49,52 @@

             return Ok(images);
         }
+
+        [Authorize]
+        [HttpPut]
+        public IHttpActionResult UpdateImage(Image image)
+        {
+            var userId = this.User.Identity.GetUserId();
+
+            var imageFromDb = this.data
+                                .Images
+                                .All()
+                                .Where(i => i.ImageID == image.ImageID)
+                                .FirstOrDefault();
+
+            if(userId != imageFromDb.UserID)
+            {
+                return BadRequest("You are not authorized to change this image");
+            }
+
+            imageFromDb.Name = image.Name;
+            imageFromDb.Url = image.Url;
+            imageFromDb.Description = image.Description;
+
+            this.data.SaveChanges();
+            return Ok();
+        }
+
+        [Authorize]
+        [HttpDelete]
+        public IHttpActionResult DeleteImage(Image image)
+        {
+            var userId = this.User.Identity.GetUserId();
+
+            var imageFromDb = this.data
+                                .Images
+                                .All()
+                                .Where(i => i.ImageID == image.ImageID)
+                                .FirstOrDefault();
+
+            if (userId != imageFromDb.UserID)
+            {
+                return BadRequest("You are not authorized to change this image");
+            }
+
+            this.data.Images.Delete(imageFromDb);
+            this.data.SaveChanges();
+            return Ok();
+        }
     }
 }


fixed locator for close div

fixed locator for close div

--- Golem.PageObjects.Cael/Assessments/DeclineAssessmentPopup.cs
+++ Golem.PageObjects.Cael/Assessments/DeclineAssessmentPopup.cs
@@ -11,7 +11,7 @@
 {
     public class DeclineAssessmentPopup : BasePageObject
     {
-        public Element Close_Button = new Element("Decline Assessment Popup - CLOSE Button", By.XPath("//div[@id='diaglogDA']/div"));
+        public Element Close_Button = new Element("Decline Assessment Popup - CLOSE Button", By.ClassName("close-text"));
         public Element TakeIt_Button = new Element("Decline Assessment Popup - I'LL TAKE IT Button", By.Id("btnNevermind"));
         public Element Decline_Button = new Element("Decline Assessment Popup - DECLINE button", By.Id("btnDecline"));
         public Element Decline_ReasonDrop = new Element("Decline Assessment Popup - Reason Dropdown", By.Id("ddDeclineReason"));


reorganizing code and making a couple members private


Fix merge problem

Fix merge problem


Initialize to printer ActiveExtruderIndex

--- MatterControlLib/PrinterCommunication/Io/ToolChangeStream.cs
+++ MatterControlLib/PrinterCommunication/Io/ToolChangeStream.cs
@@ -39,7 +39,7 @@
 		private Queue<string> commandQueue = new Queue<string>();
 		private object locker = new object();
 		private int requestedExtruder;
-		private int extruderLastSwitchedTo;
+		private int activeExtruderIndex;
 		PrinterMove lastDestination = PrinterMove.Unknown;
 		int extruderCount = 0;

@@ -47,6 +47,7 @@
 			: base(printer, internalStream)
 		{
 			extruderCount = printer.Settings.GetValue<int>(SettingsKey.extruder_count);
+			activeExtruderIndex = printer.Connection.ActiveExtruderIndex;
 		}

 		private bool CheckIfNeedToSwitchExtruders(string lineIn)
@@ -63,7 +64,7 @@

 			if ((lineNoComment.StartsWith("G0 ") || lineNoComment.StartsWith("G1 ")) // is a G1 or G0
 				&& (lineNoComment.Contains("X") || lineNoComment.Contains("Y") || lineNoComment.Contains("Z")) // hase a move axis in it
-				&& extruderLastSwitchedTo != requestedExtruder) // is different than the last extruder set
+				&& activeExtruderIndex != requestedExtruder) // is different than the last extruder set
 			{
 				string gcodeToQueue = "";
 				switch (requestedExtruder)
@@ -99,7 +100,7 @@
 					queuedSwitch = true;
 				}

-				extruderLastSwitchedTo = requestedExtruder;
+				activeExtruderIndex = requestedExtruder;
 			}

 			return queuedSwitch;
@@ -143,7 +144,7 @@

 			if (line.StartsWith("G28)"))
 			{
-				extruderLastSwitchedTo = 0;
+				activeExtruderIndex = 0;
 				requestedExtruder = 0;
 			}


Corrected traversal issue introduced when I converted the processing algorithm to an iterative version.

--- OSCADSharp/OSCADSharp/Utility/Images/CubistImageProcessor.cs
+++ OSCADSharp/OSCADSharp/Utility/Images/CubistImageProcessor.cs
@@ -24,6 +24,8 @@

         #region Private Fields
         private int scannedRows = 0;
+        private int height = 0;
+        private int width = 0;
         private string imagePath;
         private string heightMode;
         List<OSCADObject> cubes = new List<OSCADObject>();
@@ -68,15 +70,17 @@

             List<OSCADObject> cubes = new List<OSCADObject>();
             bool[,] visited = new bool[img.Width, img.Height];
-
-            Point? start = this.getNextPoint(img, ref visited, img.Width - 1, img.Height - 1);
+            this.height = img.Height;
+            this.width = img.Width;
+
+            Point? start = this.getNextPoint(ref visited, img.Width - 1, img.Height - 1);
             do
             {
                 System.Drawing.Color color = pixels[((Point)start).X, ((Point)start).Y];
-                var cube = this.traverseIterative(img, (Point)start, ref visited, color);
+                var cube = this.traverseIterative((Point)start, ref visited, color);
                 if (cube != null)
                 {
-                    this.markVisited(ref visited, cube, (Point)start, img);
+                    markVisited(ref visited, cube, (Point)start);
                     if (color.A != 0)
                     {
                         this.htMapper.SetHeight(color, cube);
@@ -86,7 +90,7 @@
                     }
                 }

-                start = this.getNextPoint(img, ref visited, img.Width - 1, img.Height - 1);
+                start = this.getNextPoint(ref visited, img.Width - 1, img.Height - 1);
             } while (start != null);

             return cubes;
@@ -117,90 +121,66 @@
             }
         }

-        private void markVisited(ref bool[,] visited, Cube cube, Point start, Bitmap img)
-        {
-            var bounds = cube.Bounds();
-            for (int x = start.X; x < start.X + bounds.Length && x < img.Width; x++)
-            {
-                for (int y = start.Y; y < start.Y + bounds.Width && y < img.Height; y++)
-                {
-                    visited[x, y] = true;
-                }
-            }
-        }
-
-        private Cube traverseIterative(Bitmap img, Point start, ref bool[,] visited, System.Drawing.Color color, Cube cube = null)
+        private Cube traverseIterative(Point start, ref bool[,] visited, System.Drawing.Color color, Cube cube = null)
         {
             TraversalDirection direction = TraversalDirection.None;
             Cube current = cube ?? new Cube();
-            direction = canContinueTraversal(img, ref start, visited, color, current);
+            direction = traversePixels(ref start, visited, color, current);

             while (direction != TraversalDirection.None)
             {
-
-                if (direction == TraversalDirection.X_Only)
-                {
-                    current.Size.X += 1;
-                }
-                else if (direction == TraversalDirection.Y_Only)
-                {
-                    current.Size.Y += 1;
-                }
-                else
-                {
-                    current.Size.X += 1;
-                    current.Size.Y += 1;
-                }
-
-                direction = canContinueTraversal(img, ref start, visited, color, current);
+                direction = traversePixels(ref start, visited, color, current);
             }

             return current;
         }

-        private TraversalDirection canContinueTraversal(Bitmap img, ref Point start, bool[,] visited, Color color, Cube cube)
+        private TraversalDirection traversePixels(ref Point start, bool[,] visited, Color color, Cube cube)
         {
             var direction = TraversalDirection.Bidirectional;
             var bounds = cube.Bounds();
             //Bidirectional
-            for (int x = start.X; x < start.X + bounds.Length+1 && direction != TraversalDirection.None; x++)
-            {
-                for (int y = start.Y; y < start.Y + bounds.Width+1 && direction != TraversalDirection.None; y++)
-                {
-                    if (x >= img.Width || y >= img.Height)
-                    {
-                        direction = TraversalDirection.None;
-                    }
-                    else
-                    {
-                        if(!pixelCanBeTraversed(img, ref visited, new Point(x, y), color))
-                        {
-                            direction = TraversalDirection.None;
-                        }
-                    }
-                }
-            }
-
+            visited[start.X, start.Y] = true;
+            Point next = new Point(start.X + 1, start.Y + 1);
+            if (next.X >= this.width || next.Y >= this.height)
+            {
+                direction = TraversalDirection.None;
+            }
+            else
+            {
+                if(pixelCanBeTraversed(ref visited, next, color))
+                {
+                    visited[next.X, next.Y] = true;
+                    cube.Size.X += 1;
+                    cube.Size.Y += 1;
+                }
+                else
+                {
+                    direction = TraversalDirection.None;
+                }
+            }

             if (direction != TraversalDirection.None)
                 return direction;
+
             //X-axis
             direction = TraversalDirection.X_Only;
-            for (int x = start.X; x < start.X + bounds.Length + 1 && direction != TraversalDirection.None; x++)
-            {
-                for (int y = start.Y; y < start.Y + bounds.Width && direction != TraversalDirection.None; y++)
-                {
-                    if (x >= img.Width || y >= img.Height)
-                    {
-                        direction = TraversalDirection.None;
-                    }
-                    else
-                    {
-                        if (!pixelCanBeTraversed(img, ref visited, new Point(x, y), color))
-                        {
-                            direction = TraversalDirection.None;
-                        }
-                    }
+            next.Y = start.Y;
+
+            if (next.X >= this.width || next.Y >= this.height)
+            {
+                direction = TraversalDirection.None;
+            }
+            else
+            {
+                if (pixelCanBeTraversed(ref visited, next, color))
+                {
+                    visited[next.X, next.Y] = true;
+                    cube.Size.X += 1;
+                }
+                else
+                {
+                    direction = TraversalDirection.None;
                 }
             }

@@ -209,35 +189,49 @@

             //Y-Axis
             direction = TraversalDirection.Y_Only;
-            for (int x = start.X; x < start.X + bounds.Length && direction != TraversalDirection.None; x++)
-            {
-                for (int y = start.Y; y < start.Y + bounds.Width + 1 && direction != TraversalDirection.None; y++)
-                {
-                    if (x >= img.Width || y >= img.Height)
-                    {
-                        direction = TraversalDirection.None;
-                    }
-                    else
-                    {
-                        if (!pixelCanBeTraversed(img, ref visited, new Point(x, y), color))
-                        {
-                            direction = TraversalDirection.None;
-                        }
-                    }
-                }
-            }
-
+            next.X = start.X;
+            next.Y = start.Y + 1;
+
+            if (next.X >= this.width || next.Y >= this.height)
+            {
+                direction = TraversalDirection.None;
+            }
+            else
+            {
+                if (pixelCanBeTraversed(ref visited, next, color))
+                {
+                    visited[next.X, next.Y] = true;
+                    cube.Size.Y += 1;
+                }
+                else
+                {
+                    direction = TraversalDirection.None;
+                }
+            }
+
             return direction;
         }

-        private bool pixelCanBeTraversed(Bitmap img, ref bool[,] visited, Point pixel, Color colorToMatch)
-        {
-            return pixel.X < img.Width && pixel.Y < img.Height &&
+        private bool pixelCanBeTraversed(ref bool[,] visited, Point pixel, Color colorToMatch)
+        {
+            return pixel.X < this.width && pixel.Y < this.height &&
                     visited[pixel.X, pixel.Y] == false && pixels[pixel.X, pixel.Y] == colorToMatch;

         }

-        private Point? getNextPoint(Bitmap img, ref bool[,] visited, int width, int height)
+        private void markVisited(ref bool[,] visited, Cube cube, Point start)
+        {
+            var bounds = cube.Bounds();
+            for (int x = start.X; x < start.X + bounds.Length && x < this.width; x++)
+            {
+                for (int y = start.Y; y < start.Y + bounds.Width && y <this.height; y++)
+                {
+                    visited[x, y] = true;
+                }
+            }
+        }
+
+        private Point? getNextPoint(ref bool[,] visited, int width, int height)
         {
             int rowStart = this.scannedRows;
             for (int row = rowStart; row <= height; row++)
@@ -254,8 +248,6 @@

             return null;
         }
-
-
         #endregion
     }
 }


Added missing tests

Added missing tests


More on map search: send extra messages to the user regarding the region being found or not, because the UI is horribly confusing -- places profile is always "loading..." whether the region exists or not.

--- OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs
+++ OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs
@@ -159,6 +159,17 @@
             // flags are agent flags sent from the viewer.
             // they have different values depending on different viewers, apparently
             remoteClient.SendMapBlock(blocks, flags);
+
+            // send extra user messages for V3
+            // because the UI is very confusing
+            // while we don't fix the hard-coded urls
+            if (flags == 2)
+            {
+                if (regionInfos.Count == 0)
+                    remoteClient.SendAgentAlertMessage("No regions found with that name.", true);
+                else if (regionInfos.Count == 1)
+                    remoteClient.SendAgentAlertMessage("Region found!", false);
+            }
         }

 //        private Scene GetClientScene(IClientAPI client)


Add unit test

Add unit test


statistics draws now bars per pixel, not per step -> fixed with, adding interpolation is easy

--- ParticleStormControl/ParticleStormControl/Menu/Statistics.cs
+++ ParticleStormControl/ParticleStormControl/Menu/Statistics.cs
@@ -207,19 +207,19 @@
             switch (currentDiagramType)
             {
                 case DiagramType.DOMINATION:
-                    DrawDiagram(spriteBatch, (step, player) => statistics.getDominationInStep(player, step),
+                    DrawDiagram(spriteBatch, (progress, player) => statistics.getDominationInStep(player, (int)(progress * statistics.Steps)),
                                                     (float)gameTime.ElapsedGameTime.TotalSeconds, maxWidth, height, yPos);
                     break;
                 case DiagramType.HEALTH:
-                    DrawDiagram(spriteBatch, (step, player) => (float)statistics.getHealthInStep(player, step) / statistics.MaxOverallSimultaneousHealth,
+                    DrawDiagram(spriteBatch, (progress, player) => (float)statistics.getHealthInStep(player, (int)(progress * statistics.Steps)) / statistics.MaxOverallSimultaneousHealth,
                                                                      (float)gameTime.ElapsedGameTime.TotalSeconds, maxWidth, height, yPos);
                     break;
                 case DiagramType.MASS:
-                    DrawDiagram(spriteBatch, (step, player) => (float)statistics.getParticlesInStep(player, step) / statistics.MaxOverallSimultaneousParticles,
+                    DrawDiagram(spriteBatch, (progress, player) => (float)statistics.getParticlesInStep(player, (int)(progress * statistics.Steps)) / statistics.MaxOverallSimultaneousParticles,
                                                                      (float)gameTime.ElapsedGameTime.TotalSeconds, maxWidth, height, yPos);
                     break;
                 case DiagramType.SPAWN_POINTS:
-                    DrawDiagram(spriteBatch, (step, player) => (float)statistics.getPossessingSpawnPointsInStep(player, step) / statistics.OverallNumberOfSpawnPoints,
+                    DrawDiagram(spriteBatch, (progress, player) => (float)statistics.getPossessingSpawnPointsInStep(player, (int)(progress * statistics.Steps)) / statistics.OverallNumberOfSpawnPoints,
                                                                      (float)gameTime.ElapsedGameTime.TotalSeconds, maxWidth, height, yPos);
                     break;
             }
@@ -232,24 +232,17 @@
         ///
         /// </summary>
         /// <param name="spriteBatch"></param>
-        /// <param name="heightFunction">function returning a height for a given (1st para) step from a given (2nd para) player. Sum of heights in a step should be one!</param>
+        /// <param name="heightFunction">function returning a height for a given (1st para) progress-percentage from a given (2nd para) player. Sum of heights in a step should be one!</param>
         /// <param name="frameTimeInterval"></param>
         /// <param name="area"></param>
-        private void DrawDiagram(SpriteBatch spriteBatch, Func<int, int, float> heightFunction, float frameTimeInterval, int maxWidth, int heightVal, int yPos)
+        private void DrawDiagram(SpriteBatch spriteBatch, Func<float, int, float> heightFunction, float frameTimeInterval, int maxWidth, int heightVal, int yPos)
         {
             Rectangle area;

             const int ARROW_PADDING = 20;

             int diagramAreaMaxWidth = maxWidth - ARROW_SIZE * 2 - ARROW_PADDING * 2;
-            int stepWidth = Math.Max(1, diagramAreaMaxWidth / statistics.Steps);
-            int startStep;
-            if (statistics.Steps > diagramAreaMaxWidth)
-                startStep = (statistics.Steps - diagramAreaMaxWidth) / stepWidth + 1;   // if a step is only a pixel... DAMDAM
-            else
-                startStep = 0;
-            area.Width = stepWidth * (statistics.Steps - startStep) + 20;
-
+            area.Width = diagramAreaMaxWidth + 20;
             area.Height = heightVal;
             area.X = (menu.ScreenWidth-area.Width) / 2;
             area.Y = yPos + InterfaceElement.PADDING*2 + menu.GetFontHeight();
@@ -265,18 +258,19 @@
             // gray background
             spriteBatch.Draw(menu.TexPixel, area, Color.Gray);

-            // draw amount of particles per player and step
-            for (int step = startStep; step < statistics.Steps; step++)
+            // draw amount of particles per player and pixel
+            for (int pixel = 0; pixel < area.Width; pixel++)
             {
                 int offset = 0;
+                float progress = (float)pixel / area.Width;
                 for (int playerIndex = statistics.PlayerCount-1; playerIndex >= 0; --playerIndex)
                 {
-                    float percentage = heightFunction(step, playerIndex);
+                    float percentage = heightFunction(progress, playerIndex);
                     int height = (int)(percentage * area.Height);

                     offset += height;

-                    Rectangle rect = new Rectangle(area.X + (step - startStep) * stepWidth, area.Bottom - offset, stepWidth, height);
+                    Rectangle rect = new Rectangle(area.X + pixel, area.Bottom - offset, 1, height);
                     spriteBatch.Draw(menu.TexPixel, rect, Player.Colors[PlayerColorIndices[playerIndex]]);
                 }
             }
@@ -288,12 +282,14 @@
             spriteBatch.Draw(menu.TexPixel, rouningHide, Color.Black);

             // draw items
-            for (int step = startStep; step < statistics.Steps; step++)
+            float stepWidth = (float)area.Width / statistics.Steps;
+            for (int step = 0; step < statistics.Steps; step++)
             {
                 int offset = 0;
+                float progress = (float)step / (statistics.Steps-1);
                 for (int playerIndex = statistics.PlayerCount - 1; playerIndex >= 0; --playerIndex)
                 {
-                    float percentage = heightFunction(step, playerIndex);
+                    float percentage = heightFunction(progress, playerIndex);
                     int height = (int)(percentage * area.Height);

@@ -304,13 +300,13 @@
                     if (itemUsed != null)
                     {
                         int y = (int)MathHelper.Clamp(area.Bottom - offset + (height - ITEM_DISPLAY_SIZE) / 2, area.Y, area.Y + area.Height - ITEM_DISPLAY_SIZE);
-                        int x = area.X + (step - startStep) * stepWidth - ITEM_DISPLAY_SIZE / 2;
+                        int x = (int)(area.X + step * stepWidth - ITEM_DISPLAY_SIZE / 2 + 0.5f);

                         if ((Statistics.StatItems)itemUsed == Statistics.StatItems.MUTATION)
                         {
-                            if (Level.SWITCH_COUNTDOWN_LENGTH / statistics.StepTime + step > statistics.Steps - startStep)  // never happen?
+                            if (Level.SWITCH_COUNTDOWN_LENGTH / statistics.StepTime + step > statistics.Steps)  // never happen?
                                 continue;
-                            x += stepWidth * (int)(Level.SWITCH_COUNTDOWN_LENGTH / statistics.StepTime);
+                            x += (int)(Level.SWITCH_COUNTDOWN_LENGTH / statistics.StepTime);
                         }

                         x = (int)MathHelper.Clamp(x, area.X, area.X + area.Width - ITEM_DISPLAY_SIZE);
@@ -322,14 +318,14 @@
                     }
                 }
             }
-
+
             // draw deaths
             for (int playerIndex = 0; playerIndex<statistics.PlayerCount; ++playerIndex)
             {
                 int depthStep = statistics.getDeathStepOfPlayer(playerIndex);
                 if (depthStep >= 0)
                 {
-                    float percentage = (float)depthStep / (statistics.Steps - startStep);
+                    float percentage = (float)depthStep / statistics.Steps;
                     int xPos = (int)MathHelper.Clamp(area.X + percentage * area.Width - ITEM_DISPLAY_SIZE / 2, area.X, area.X + area.Width - ITEM_DISPLAY_SIZE);
                     spriteBatch.Draw(playerDiedTexture, new Rectangle(xPos, area.Bottom - ITEM_DISPLAY_SIZE + 5, ITEM_DISPLAY_SIZE, ITEM_DISPLAY_SIZE),
                                             Player.Colors[PlayerColorIndices[playerIndex]]);
@@ -342,7 +338,7 @@
             for (int i = 0; i < timeDisplays.Length; ++i)
             {
                 float progress = (float)i / (timeDisplays.Length-1);
-                float time = ((statistics.Steps - startStep) * progress + statistics.FirstStep + startStep) * statistics.StepTime;
+                float time = (statistics.Steps * progress + statistics.FirstStep) * statistics.StepTime;
                 string endTimeString = GenerateTimeString(time);
                 float textLen = menu.Font.MeasureString(endTimeString).X;


Add missing type check

Add missing type check

--- PortableExtensions/System.Action/Action.SafeExecuteExcept.cs
+++ PortableExtensions/System.Action/Action.SafeExecuteExcept.cs
@@ -19,8 +19,59 @@
         /// <param name="action">The action to execute.</param>
         /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
         public static Boolean SafeExecuteExcept<TException>(this Action action)
+            where TException : Exception
         {
             return action.SafeExecuteExcept(new[] { typeof(TException) });
+        }
+
+        /// <summary>
+        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
+        /// </summary>
+        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
+        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
+        /// <param name="action">The action to execute.</param>
+        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
+        public static Boolean SafeExecuteExcept<TException1, TException2>(this Action action)
+            where TException1 : Exception
+            where TException2 : Exception
+        {
+            return action.SafeExecuteExcept(new[] {typeof (TException1), typeof (TException2)});
+        }
+
+        /// <summary>
+        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
+        /// </summary>
+        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
+        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
+        /// <typeparam name="TException3">The third exception type to throw.</typeparam>
+        /// <param name="action">The action to execute.</param>
+        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
+        public static Boolean SafeExecuteExcept<TException1, TException2, TException3>(this Action action)
+            where TException1 : Exception
+            where TException2 : Exception
+            where TException3 : Exception
+        {
+            return action.SafeExecuteExcept(new[] {typeof (TException1), typeof (TException2), typeof (TException3)});
+        }
+
+        /// <summary>
+        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
+        /// </summary>
+        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
+        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
+        /// <typeparam name="TException3">The third exception type to throw.</typeparam>
+        /// <typeparam name="TException4">The fourth exception type to throw.</typeparam>
+        /// <param name="action">The action to execute.</param>
+        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
+        public static Boolean SafeExecuteExcept<TException1, TException2, TException3, TException4>(this Action action)
+            where TException1 : Exception
+            where TException2 : Exception
+            where TException3 : Exception
+            where TException4 : Exception
+        {
+            return
+                action.SafeExecuteExcept(new[]
+                {typeof (TException1), typeof (TException2), typeof (TException3), typeof (TException4)});
         }

         /// <summary>
@@ -46,46 +97,5 @@
                 return false;
             }
         }
-
-        /// <summary>
-        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
-        /// </summary>
-        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
-        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
-        /// <param name="action">The action to execute.</param>
-        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
-        public static Boolean SafeExecuteExcept<TException1, TException2>(this Action action)
-        {
-            return action.SafeExecuteExcept(new[] {typeof (TException1), typeof (TException2)});
-        }
-
-        /// <summary>
-        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
-        /// </summary>
-        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
-        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
-        /// <typeparam name="TException3">The third exception type to throw.</typeparam>
-        /// <param name="action">The action to execute.</param>
-        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
-        public static Boolean SafeExecuteExcept<TException1, TException2, TException3>(this Action action)
-        {
-            return action.SafeExecuteExcept(new[] {typeof (TException1), typeof (TException2), typeof (TException3)});
-        }
-
-        /// <summary>
-        ///     Executes the given action insed of a try catch block and catches all excepton expect the spcified typea.
-        /// </summary>
-        /// <typeparam name="TException1">The first exception type to throw.</typeparam>
-        /// <typeparam name="TException2">The second exception type to throw.</typeparam>
-        /// <typeparam name="TException3">The third exception type to throw.</typeparam>
-        /// <typeparam name="TException4">The fourth exception type to throw.</typeparam>
-        /// <param name="action">The action to execute.</param>
-        /// <returns>Returns true if the action was executed without an exception, otherwise false.</returns>
-        public static Boolean SafeExecuteExcept<TException1, TException2, TException3, TException4>(this Action action)
-        {
-            return
-                action.SafeExecuteExcept(new[]
-                {typeof (TException1), typeof (TException2), typeof (TException3), typeof (TException4)});
-        }
     }
 }


Fix: Web overlay settings not being available immediately on first SC boot

was breaking web overlay until SC was restarted or any of the web overlay settings was changed

--- plugins/WebSocketDataSender/WebOverlay/WebOverlay.cs
+++ plugins/WebSocketDataSender/WebOverlay/WebOverlay.cs
@@ -23,6 +23,7 @@
             _saver = saver;
             OverlayConfiguration = new OverlayConfiguration();
             LoadConfiguration();
+            SaveConfiguration();
             OverlayConfiguration.PropertyChanged += OverlayConfigurationPropertyChanged;
         }


Removed transaction abort case.

Removed transaction abort case.

--HG--
branch : 2011-02-17-advanced-durability


[DivisionDirectory] Replace last use of UniversityRepository


Fix Machine Type issue on old sql version

--- KServer.cs
+++ KServer.cs
@@ -20,13 +20,14 @@
         {
             string serverType = "Unknown";
             smo.Database d = s.Databases["master"];
-            string sql = @"IF EXISTS(SELECT *
-FROM sys.all_columns
-WHERE name = 'virtual_machine_type_desc'
-	AND OBJECT_NAME(object_id) = 'dm_os_sys_info')
-BEGIN
-	SELECT virtual_machine_type_desc FROM sys.dm_os_sys_info
-END";
+            string sql = @"IF EXISTS(SELECT *
+FROM sys.all_columns
+WHERE name = 'virtual_machine_type_desc'
+AND OBJECT_NAME(object_id) = 'dm_os_sys_info')
+BEGIN
+EXECUTE sys.sp_executesql N'SELECT virtual_machine_type_desc FROM sys.dm_os_sys_info'
+END
+";
             DataTable dt = d.ExecuteWithResults(sql).Tables[0];
             if (dt != null && dt.Rows.Count > 0)
             {


Changed layout a bit

Changed layout a bit

--- MotorwaySimulator/MotorwaySimulator.Designer.cs
+++ MotorwaySimulator/MotorwaySimulator.Designer.cs
@@ -307,7 +307,7 @@
             this.TrackBarTickTime.Location = new System.Drawing.Point(303, 12);
             this.TrackBarTickTime.Minimum = 1;
             this.TrackBarTickTime.Name = "TrackBarTickTime";
-            this.TrackBarTickTime.Size = new System.Drawing.Size(82, 45);
+            this.TrackBarTickTime.Size = new System.Drawing.Size(137, 45);
             this.TrackBarTickTime.TabIndex = 3;
             this.TrackBarTickTime.Value = 10;
             this.TrackBarTickTime.Scroll += new System.EventHandler(this.UpdateTickTime);
@@ -387,9 +387,9 @@
             // LabelVisibleRoadInterval
             //
             this.LabelVisibleRoadInterval.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
-            this.LabelVisibleRoadInterval.Location = new System.Drawing.Point(956, 16);
+            this.LabelVisibleRoadInterval.Location = new System.Drawing.Point(1010, 16);
             this.LabelVisibleRoadInterval.Name = "LabelVisibleRoadInterval";
-            this.LabelVisibleRoadInterval.Size = new System.Drawing.Size(181, 18);
+            this.LabelVisibleRoadInterval.Size = new System.Drawing.Size(127, 18);
             this.LabelVisibleRoadInterval.TabIndex = 60;
             this.LabelVisibleRoadInterval.Text = "0";
             this.LabelVisibleRoadInterval.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
@@ -398,7 +398,7 @@
             //
             this.LabelVisibleRoadIntervalTitle.AutoSize = true;
             this.LabelVisibleRoadIntervalTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
-            this.LabelVisibleRoadIntervalTitle.Location = new System.Drawing.Point(777, 16);
+            this.LabelVisibleRoadIntervalTitle.Location = new System.Drawing.Point(829, 16);
             this.LabelVisibleRoadIntervalTitle.Name = "LabelVisibleRoadIntervalTitle";
             this.LabelVisibleRoadIntervalTitle.Size = new System.Drawing.Size(175, 20);
             this.LabelVisibleRoadIntervalTitle.TabIndex = 59;
@@ -407,7 +407,7 @@
             // LabelTicksPerSecond
             //
             this.LabelTicksPerSecond.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
-            this.LabelTicksPerSecond.Location = new System.Drawing.Point(741, 16);
+            this.LabelTicksPerSecond.Location = new System.Drawing.Point(799, 16);
             this.LabelTicksPerSecond.Name = "LabelTicksPerSecond";
             this.LabelTicksPerSecond.Size = new System.Drawing.Size(26, 18);
             this.LabelTicksPerSecond.TabIndex = 58;
@@ -418,7 +418,7 @@
             //
             this.LabelTicksPerSecondTitle.AutoSize = true;
             this.LabelTicksPerSecondTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
-            this.LabelTicksPerSecondTitle.Location = new System.Drawing.Point(671, 16);
+            this.LabelTicksPerSecondTitle.Location = new System.Drawing.Point(729, 16);
             this.LabelTicksPerSecondTitle.Name = "LabelTicksPerSecondTitle";
             this.LabelTicksPerSecondTitle.Size = new System.Drawing.Size(64, 20);
             this.LabelTicksPerSecondTitle.TabIndex = 57;
@@ -2962,7 +2962,7 @@
             //
             this.LabelAllVehiclesLifetimeTitle.BackColor = System.Drawing.Color.Transparent;
             this.LabelAllVehiclesLifetimeTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
-            this.LabelAllVehiclesLifetimeTitle.Location = new System.Drawing.Point(385, 12);
+            this.LabelAllVehiclesLifetimeTitle.Location = new System.Drawing.Point(443, 12);
             this.LabelAllVehiclesLifetimeTitle.Name = "LabelAllVehiclesLifetimeTitle";
             this.LabelAllVehiclesLifetimeTitle.Size = new System.Drawing.Size(123, 28);
             this.LabelAllVehiclesLifetimeTitle.TabIndex = 124;
@@ -2973,7 +2973,7 @@
             //
             this.LabelAllVehiclesLifetime.BackColor = System.Drawing.Color.Transparent;
             this.LabelAllVehiclesLifetime.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F);
-            this.LabelAllVehiclesLifetime.Location = new System.Drawing.Point(506, 12);
+            this.LabelAllVehiclesLifetime.Location = new System.Drawing.Point(572, 12);
             this.LabelAllVehiclesLifetime.Name = "LabelAllVehiclesLifetime";
             this.LabelAllVehiclesLifetime.Size = new System.Drawing.Size(159, 28);
             this.LabelAllVehiclesLifetime.TabIndex = 125;


Exposed Build function with preset selection

--- MyHalp.Editor/Editor/MyCooker/MyCookerWindow.cs
+++ MyHalp.Editor/Editor/MyCooker/MyCookerWindow.cs
@@ -388,10 +388,7 @@
         [MenuItem("Window/MyCooker/Build &B")]
         public static void Build()
         {
-            var cookerManager = new MyCookerManager();
-            cookerManager.Load();
-
-            cookerManager.Build();
+            Build(-1);
         }

         /// <summary>
@@ -414,5 +411,16 @@

             cookerManager.ResetDefines();
         }
+
+        public static void Build(int preset)
+        {
+            var cookerManager = new MyCookerManager();
+            cookerManager.Load();
+
+            if(preset >= 0)
+                cookerManager.SelectedPreset = cookerManager.Presets[preset];
+
+            cookerManager.Build();
+        }
     }
 }


Fill name of first COM port on Refresh

Fill name of first COM port on Refresh

--- SerialTool/MainForm.cs
+++ SerialTool/MainForm.cs
@@ -244,7 +244,10 @@
         {
             serialPortName.Text = "";
             ShowSerialPorts();
-            closeButton.Enabled = port!= null ? port.IsOpen : false;
+            if (serialPortName.Items.Count > 0)
+            {
+                serialPortName.SelectedIndex = 0;
+            }
         }

         private void CloseSerialPort()


Pad todo item ids to make them equal width.

--- SlackCommander/SlackCommander.Web/Todo/TodoItemExtensions.cs
+++ SlackCommander/SlackCommander.Web/Todo/TodoItemExtensions.cs
@@ -15,23 +15,19 @@
             {
                 return "You are all done!";
             }
+            int idMaxLength = items.Max(i => i.Id.Length);
             var text = new StringBuilder();
             foreach (var item in items)
             {
-                text.AppendLine(item.ToSlackString());
+                text.AppendLine(string.Format(
+                "`{0}` {1} {2} {3} {4}",
+                item.Id.PadLeft(idMaxLength),
+                item.Done ? ":white_check_mark:" : ":white_square:",
+                item.Text,
+                item.ClaimedBy.Missing() ? string.Empty : ":lock:",
+                item.ClaimedBy.Missing() ? string.Empty : string.Format("<@{0}>", item.ClaimedBy)).Trim());
             }
             return text.ToString().Trim();
         }
-
-        public static string ToSlackString(this TodoItem todoItem)
-        {
-            return string.Format(
-                "`{0}` {1} {2} {3} {4}",
-                todoItem.Id,
-                todoItem.Done ? ":white_check_mark:" : ":white_square:",
-                todoItem.Text,
-                todoItem.ClaimedBy.Missing() ? string.Empty : ":lock:",
-                todoItem.ClaimedBy.Missing() ? string.Empty : string.Format("<@{0}>", todoItem.ClaimedBy)).Trim();
-        }
     }
 }


fix merge error (#3228)

fix merge error (#3228)

--- Source/ACE.Server/Factories/LootGenerationFactory_Jewelry.cs
+++ Source/ACE.Server/Factories/LootGenerationFactory_Jewelry.cs
@@ -160,15 +160,6 @@

             wo.ItemWorkmanship = GetWorkmanship(profile.Tier);

-            if (wo.GemCode != null)
-                wo.GemCount = GemCountChance.Roll(wo.GemCode.Value, profile.Tier);
-            else
-                wo.GemCount = ThreadSafeRandom.Next(1, 5);
-
-            wo.GemType = RollGemType(profile.Tier);
-
-            wo.ItemWorkmanship = GetWorkmanship(profile.Tier);
-
             double materialMod = LootTables.getMaterialValueModifier(wo);
             double gemMaterialMod = LootTables.getGemMaterialValueModifier(wo);
             var value = GetValue(profile.Tier, wo.ItemWorkmanship.Value, gemMaterialMod, materialMod);


Synchrophasor: Added minimum and maximum latency statistical calculation stubs.

git-tfs-id: [https://tfs.codeplex.com/tfs/TFS07]$/openpdc/Synchrophasor/Current Version;C53359

--- Source/Libraries/TVA.PhasorProtocols/CommonPhasorServices.cs
+++ Source/Libraries/TVA.PhasorProtocols/CommonPhasorServices.cs
@@ -1467,7 +1467,7 @@

                 try
                 {
-                    // Filter action adapter collection down to the phasor measurement mapper input streams
+                    // Filter input adapter collection down to the phasor measurement mapper input streams
                     IEnumerable<PhasorMeasurementMapper> inputStreams = m_inputAdapters.Where<IInputAdapter>(adapter => adapter is PhasorMeasurementMapper).Cast<PhasorMeasurementMapper>();

                     // Calculate defined statistics for each input stream
@@ -1754,7 +1754,7 @@
                         if (Convert.ToInt32(connection.ExecuteScalar(string.Format("SELECT COUNT(*) FROM Measurement WHERE SignalReference='{0}' AND HistorianID={1};", signalReference, statHistorianID))) == 0)
                         {
                             company = (string)connection.ExecuteScalar(string.Format("SELECT MapAcronym FROM Company WHERE ID={0};", device.Field<int>("CompanyID")));
-                            vendorDevice = (string)connection.ExecuteScalar(string.Format("SELECT Name FROM VendorDevice WHERE ID={0};", device.Field<int?>("VendorDeviceID") ?? 0)); // Modified to retrieve VendorDeviceID into Nullable of Int as it is not a required field.
+                            vendorDevice = (string)connection.ExecuteScalar(string.Format("SELECT Name FROM VendorDevice WHERE ID={0};", device.Field<int?>("VendorDeviceID") ?? 0));
                             pointTag = string.Format("{0}_{1}:ST{2}", company, acronym, signalIndex);
                             description = string.Format("{0} {1} Statistic for {2}", device.Field<string>("Name"), vendorDevice, statistic.Field<string>("Description"));

@@ -1953,18 +1953,35 @@
         }

         /// <summary>
-        /// Calculates percentage of variability of latency from input stream during last reporting interval.
+        /// Calculates minimum latency from input stream, in milliseconds, during last reporting interval.
         /// </summary>
         /// <param name="source">Source InputStream.</param>
         /// <param name="arguments">Any needed arguments for statistic calculation.</param>
-        /// <returns>Variability in Latency Statistic.</returns>
-        private static double GetInputStreamStatistic_LatencyVariability(object source, string arguments)
+        /// <returns>Minimum Latency Statistic.</returns>
+        private static double GetInputStreamStatistic_MinimumLatency(object source, string arguments)
         {
             double statistic = 0.0D;
             //PhasorMeasurementMapper inputStream = source as PhasorMeasurementMapper;

             //if (inputStream != null)
-            //    statistic = s_statisticValueCache.GetDifference(inputStream, inputStream.LatencyVariability, "LatencyVariability");
+            //    statistic = s_statisticValueCache.GetDifference(inputStream, inputStream.MinimumLatency, "MinimumLatency");
+
+            return statistic;
+        }
+
+        /// <summary>
+        /// Calculates maximum latency from input stream, in milliseconds, during last reporting interval.
+        /// </summary>
+        /// <param name="source">Source InputStream.</param>
+        /// <param name="arguments">Any needed arguments for statistic calculation.</param>
+        /// <returns>Maximum Latency Statistic.</returns>
+        private static double GetInputStreamStatistic_MaximumLatency(object source, string arguments)
+        {
+            double statistic = 0.0D;
+            //PhasorMeasurementMapper inputStream = source as PhasorMeasurementMapper;
+
+            //if (inputStream != null)
+            //    statistic = s_statisticValueCache.GetDifference(inputStream, inputStream.MaximumLatency, "MaximumLatency");

             return statistic;
         }
@@ -2334,4 +2351,4 @@

         #endregion
     }
-}+}


Fixed MemberActivityResult

Fixed MemberActivityResult

--- MailChimp/Lists/MemberActivityResult.cs
+++ MailChimp/Lists/MemberActivityResult.cs
@@ -30,7 +30,7 @@
         /// List of members information
         /// </summary>
         [DataMember(Name = "data")]
-        public List<MergeVarListResult> Data
+        public List<MemberActivity> Data
         {
             get;
             set;


Small bug fix in _ContestHeader

Small bug fix in _ContestHeader

--- Source/PhotoContest.App/Views/Contests/_ContestHeader.cshtml
+++ Source/PhotoContest.App/Views/Contests/_ContestHeader.cshtml
@@ -12,7 +12,7 @@
         {
             @Html.ActionLink("Manage", "Manage", "Contests", new { id = Model.Id }, new { @class = "btn btn-warning" })
         }
-        @if (Model.CanParticipate && !Model.IsOwner)
+        @if (Model.CanParticipate && !Model.IsOwner && Model.Status != ContestStatus.Finished)
         {
             @Html.ActionLink("Add Picture", "SelectPictures", "Contests", new { id = Model.Id }, new { @class = "btn btn-info" })
         }


Added Noise Threshhold to unbalance Adapter

--- Source/Libraries/Adapters/openHistorian.Adapters/Unbalanced.cs
+++ Source/Libraries/Adapters/openHistorian.Adapters/Unbalanced.cs
@@ -96,6 +96,8 @@
             public bool activeAlarm;
             public bool acknowlegedAlarm;
             public int countExceeding;
+            public double BaseVoltage;
+
         #pragma warning restore 1591
         }

@@ -174,12 +176,14 @@
         private double m_lastS2S1;
         private bool m_countAlarms;
         private int m_sqlFailures = 0;
+        private int m_skipped = 0;

         private LongSynchronizedOperation m_sqlWritter;
         private IsolatedQueue<DailySummary> m_summaryQueue;
         private GSF.Threading.CancellationToken m_cancelationTokenSql;

         private ConcurrentBag<ThreePhaseSet> m_threePhaseComponent;
+
         #endregion

         #region [ Properties ]
@@ -258,6 +262,21 @@
         [DefaultValue(false)]
         public bool ReportSQL { get; set; }

+        /// <summary>
+        /// Gets or sets the UseNominalThreshhold flag.
+        /// </summary>
+        [ConnectionStringParameter]
+        [Description("Defines wether the Voltage Threshhold is in p.u. or Volts.")]
+        [DefaultValue(true)]
+        public bool UseNominalThreshhold { get; set; }
+
+        /// <summary>
+        /// Gets or sets the Voltage Threshhold.
+        /// </summary>
+        [ConnectionStringParameter]
+        [Description("Defines The minimum Voltage (in p.u. or V) for computing Unbalanced.")]
+        [DefaultValue(0.5D)]
+        public double NoiseThreshhold { get; set; }

         /// <summary>
         /// Gets or sets template for output measurement point tag names.
@@ -348,6 +367,12 @@
                 status.AppendLine();
                 status.AppendFormat("Sequential SQL exceptions: {0}", m_sqlFailures);
                 status.AppendLine();
+                status.AppendFormat("Use Nominal V for Threshhold: {0}", UseNominalThreshhold);
+                status.AppendLine();
+                status.AppendFormat("Noise threshhold: {0}", NoiseThreshhold);
+                status.AppendLine();
+                status.AppendFormat("Skipped Measurements: {0}", m_skipped);
+                status.AppendLine();
                 status.Append(base.Status);

                 return status.ToString();
@@ -371,7 +396,7 @@
             if (AggregationWindow > (AlarmDelay * FramesPerSecond))
                 throw new ArgumentException("Aggregation Window (in frames) needs to be smaller than AlarmDelay (in seconds)");

-
+            m_skipped = 0;
             m_threePhaseComponent = new ConcurrentBag<ThreePhaseSet>();

             List<string> entries = new List<string>();
@@ -497,7 +522,9 @@
                     keys.activeAlarm = false;
                     keys.countExceeding = 0;
                     keys.acknowlegedAlarm = false;
+                    keys.BaseVoltage = connection.ExecuteScalar<int>("SELECT COALESCE((SELECT BaseKV FROM Phasor WHERE ID = (SELECT PhasorID FROM ActiveMeasurement WHERE SignalID = '{0}')), 0)", keys.PositiveSequence.ToString());
                     m_threePhaseComponent.Add(keys);
+
                 }
                 // Need to add Measurements to inputMeasuremetnKeys
                 inputs.Add(input1);
@@ -542,6 +569,7 @@
         {

             m_numberOfFrames++;
+            m_skipped = 0;
             List<IMeasurement> outputmeasurements = new List<IMeasurement>();
             bool report = m_numberOfFrames > AggregationWindow;

@@ -558,9 +586,11 @@
                 double s0s1 = double.NaN;
                 double s2s1 = double.NaN;

+                double v1P = double.NaN;
+
                 if (hasP && hasN)
                 {
-                    double v1P = positiveSeq.AdjustedValue;
+                    v1P = positiveSeq.AdjustedValue;
                     double v2N = negativeSeq.AdjustedValue;

                     if (v1P != 0.0D)
@@ -571,7 +601,7 @@
                 }
                 if (hasP && hasZ)
                 {
-                    double v1P = positiveSeq.AdjustedValue;
+                    v1P = positiveSeq.AdjustedValue;
                     double v0Z = zeroSeq.AdjustedValue;

                     if (v1P != 0.0D)
@@ -580,7 +610,19 @@
                         m_lastS0S1 = s0s1;
                     }
                 }
-
+
+                // Noise Threshold
+                if (!hasP)
+                    continue;
+
+                double threshold = NoiseThreshhold * (UseNominalThreshhold ? set.BaseVoltage: 1.0D);
+                if (v1P < threshold)
+                {
+                    m_skipped++;
+                    continue;
+                }
+
+
                 Measurement s2s1Measurement = new Measurement { Metadata = MeasurementKey.LookUpBySignalID(set.S0S1).Metadata };
                 outputmeasurements.Add(Measurement.Clone(s2s1Measurement, s2s1, frame.Timestamp));


CHANGED: Unity.Common - Scaling cheat console to better use it on mobile devices. Button to enable/disable console is optional.

--- Source/Slash.Unity.Common/Source/Diagnostics/CheatConsole.cs
+++ Source/Slash.Unity.Common/Source/Diagnostics/CheatConsole.cs
@@ -20,6 +20,21 @@

         public string[] QuickCheats;

+        /// <summary>
+        ///   Height of UI.
+        /// </summary>
+        public float UIHeight = 600;
+
+        /// <summary>
+        ///   Width of UI.
+        /// </summary>
+        public float UIWidth = 800;
+
+        /// <summary>
+        ///   Indicates if a butotn should be shown to enable/disable cheat console.
+        /// </summary>
+        public bool UseButton = true;
+
         private readonly Rect dragRect = new Rect(0, 0, 10000, 20);

         private string cheat = string.Empty;
@@ -31,6 +46,20 @@
         private bool showConsole;

         private Rect windowRect = new Rect(10, 10, 300, 200);
+
+        #endregion
+
+        #region Public Methods and Operators
+
+        public void DisableConsole()
+        {
+            this.showConsole = false;
+        }
+
+        public void EnableConsole()
+        {
+            this.showConsole = true;
+        }

         #endregion

@@ -68,20 +97,37 @@
         private void OnGUI()
         {
             // Draw button to show/hide cheat console.
-            if (GUI.Button(this.ButtonRect, "$"))
+            if (this.UseButton)
             {
-                this.showConsole = !this.showConsole;
+                var currentMatrix = this.ScaleGUI();
+                if (GUI.Button(this.ButtonRect, "$"))
+                {
+                    this.showConsole = !this.showConsole;
+                }
+                GUI.matrix = currentMatrix;
             }

             if (this.showConsole)
             {
+                var currentMatrix = this.ScaleGUI();
                 this.windowRect = GUI.Window(0, this.windowRect, this.DrawCheatConsole, "Cheat Console");
+                GUI.matrix = currentMatrix;
             }
         }

         private void OnGameChanged(Game newGame, Game oldGame)
         {
             this.game = newGame;
+        }
+
+        private Matrix4x4 ScaleGUI()
+        {
+            // Scale window.
+            var horizRatio = Screen.width / this.UIWidth;
+            var vertRatio = Screen.height / this.UIHeight;
+            var currentMatrix = GUI.matrix;
+            GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(horizRatio, vertRatio, 1));
+            return currentMatrix;
         }

         private void Update()


After saving, the GUI is reloaded

After saving, the GUI is reloaded

--- SqlServerValidationToolkit.Configurator/MainWindowViewModel.cs
+++ SqlServerValidationToolkit.Configurator/MainWindowViewModel.cs
@@ -122,6 +122,8 @@
         public void Save()
         {
             _sourcesViewViewModel.Save();
+            //refresh after saving to update errortypes of customQuery-validationrules
+            Init();
         }


Oracle PRE Release tests

Oracle PRE Release tests

--- TableDependency.IntegrationTest/TypeChecks/Oracle/XmlType.cs
+++ TableDependency.IntegrationTest/TypeChecks/Oracle/XmlType.cs
@@ -20,7 +20,7 @@
     [TestClass]
     public class XmlAType
     {
-        private static string XML = "<names><name>Velia</name><name>Alfredina</name><name>Luciano</name><name>" + new string('*', 4000) + "</name></names>";
+        private static string XML = "<names><name>Adélaïde</name><name>这里输要读的文字或</name><name>Згинуть наші воріженьки, як роса на сонці</name><name>أبوس الأرض تحت نعالكم</name><name>" + new string('*', 4000) + "</name></names>";
         private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
         private static readonly string TableName = "AAAXMLTEST";
         private string _xml;


use the right tileid

use the right tileid

--- Nez.Portable/Assets/Tiled/TiledTypes/Tileset.cs
+++ Nez.Portable/Assets/Tiled/TiledTypes/Tileset.cs
@@ -116,7 +116,7 @@
 			{
 				foreach (var tile in Tiles.Values)
 				{
-					TileRegions.Add(tile.Id, new RectangleF(0, 0, tile.Image.Width, tile.Image.Height));
+					TileRegions.Add(firstGid + tile.Id, new RectangleF(0, 0, tile.Image.Width, tile.Image.Height));
 				}
 			}
 		}


* Added three new events to SceneGraph: - OnObjectCreate - OnObjectDuplicate - OnObjectRemove

--- OpenSim/Region/Environment/Scenes/SceneGraph.cs
+++ OpenSim/Region/Environment/Scenes/SceneGraph.cs
@@ -39,6 +39,12 @@
 {
     public delegate void PhysicsCrash();

+    public delegate void ObjectDuplicateDelegate(EntityBase original, EntityBase clone);
+
+    public delegate void ObjectCreateDelegate(EntityBase obj);
+
+    public delegate void ObjectDeleteDelegate(EntityBase obj);
+
     /// <summary>
     /// This class used to be called InnerScene and may not yet truly be a SceneGraph.  The non scene graph components
     /// should be migrated out over time.
@@ -51,6 +57,10 @@

         protected internal event PhysicsCrash UnRecoverableError;
         private PhysicsCrash handlerPhysicsCrash = null;
+
+        public event ObjectDuplicateDelegate OnObjectDuplicate;
+        public event ObjectCreateDelegate OnObjectCreate;
+        public event ObjectDeleteDelegate OnObjectRemove;

         #endregion

@@ -288,6 +298,9 @@
                     if (attachToBackup)
                         sceneObject.AttachToBackup();

+                    if (OnObjectCreate != null)
+                        OnObjectCreate(sceneObject);
+
                     return true;
                 }
             }
@@ -313,12 +326,12 @@
                     }
                 }

-
+                if (OnObjectRemove != null)
+                    OnObjectRemove(Entities[uuid]);

                 Entities.Remove(uuid);
                 //SceneObjectGroup part;
                 //((part.RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics)
-

                 return true;
             }
@@ -1694,7 +1707,7 @@
         protected internal SceneObjectGroup DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
         {
             //m_log.DebugFormat("[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", originalPrim, offset, AgentID);
-
+
             List<EntityBase> EntityList = GetEntities();

             SceneObjectGroup originPrim = null;
@@ -1739,6 +1752,10 @@

                     // required for physics to update it's position
                     copy.AbsolutePosition = copy.AbsolutePosition;
+
+                    if (OnObjectDuplicate != null)
+                        OnObjectDuplicate(originPrim, copy);
+
                     return copy;
                 }
             }


In WebStatsModule.OnMakeRootAgent(), get region ID directly from SP.Scene.RegionInfo.RegionID instead of manually looking it up from the stored scene list.

--- OpenSim/Region/UserStatistics/WebStatsModule.cs
+++ OpenSim/Region/UserStatistics/WebStatsModule.cs
@@ -319,8 +319,6 @@

         private void OnMakeRootAgent(ScenePresence agent)
         {
-            UUID regionUUID = GetRegionUUIDFromHandle(agent.RegionHandle);
-
             lock (m_sessions)
             {
                 if (!m_sessions.ContainsKey(agent.UUID))
@@ -330,7 +328,7 @@
                     UserSessionID uid = new UserSessionID();
                     uid.name_f = agent.Firstname;
                     uid.name_l = agent.Lastname;
-                    uid.region_id = regionUUID;
+                    uid.region_id = agent.Scene.RegionInfo.RegionID;
                     uid.session_id = agent.ControllingClient.SessionId;
                     uid.session_data = usd;

@@ -339,7 +337,7 @@
                 else
                 {
                     UserSessionID uid = m_sessions[agent.UUID];
-                    uid.region_id = regionUUID;
+                    uid.region_id = agent.Scene.RegionInfo.RegionID;
                     uid.session_id = agent.ControllingClient.SessionId;
                     m_sessions[agent.UUID] = uid;
                 }
@@ -393,20 +391,6 @@
             fs.Close();
             fs.Dispose();
             return encoding.GetString(buffer);
-        }
-
-        private UUID GetRegionUUIDFromHandle(ulong regionhandle)
-        {
-            lock (m_scenes)
-            {
-                foreach (Scene scene in m_scenes)
-                {
-                    if (scene.RegionInfo.RegionHandle == regionhandle)
-                        return scene.RegionInfo.RegionID;
-                }
-            }
-
-            return UUID.Zero;
         }

         /// <summary>


Mono compliant host1.csx

Mono compliant host1.csx

--- src/sample/host1.csx
+++ src/sample/host1.csx
@@ -3,6 +3,21 @@
 //   scriptcs host1.csx

 Require<NancyPack>().Host();
+
+public interface IGreeter
+{
+    string Greeting { get; }
+}
+
+public class Greeter : IGreeter
+{
+    private int count;
+
+    public string Greeting
+    {
+        get { return "Hello World! We've said hello " + (++count).ToString() + " time(s)." ; }
+    }
+}

 public class IndexModule : NancyModule
 {
@@ -20,17 +35,4 @@
     }
 }

-public interface IGreeter
-{
-    string Greeting { get; }
-}

-public class Greeter : IGreeter
-{
-    private int count;
-
-    public string Greeting
-    {
-        get { return "Hello World! We've said hello " + (++count).ToString() + " time(s)." ; }
-    }
-}


Allow sniping from the start

Allow sniping from the start

--- PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs
+++ PoGo.PokeMobBot.Logic/Tasks/SnipePokemonTask.cs
@@ -84,7 +84,7 @@
     {
         public static List<PokemonLocation> LocsVisited = new List<PokemonLocation>();
         private static readonly List<SniperInfo> SnipeLocations = new List<SniperInfo>();
-        private static DateTime _lastSnipe = DateTime.Now;
+        private static DateTime _lastSnipe = DateTime.MinValue;

         public static Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken))
         {


[OG_223] Divine Strength

[OG_223] Divine Strength

--- SabberStoneCore/CardSets/Standard/OgCardsGen.cs
+++ SabberStoneCore/CardSets/Standard/OgCardsGen.cs
@@ -761,11 +761,10 @@
 			// - REQ_TARGET_TO_PLAY = 0
 			// --------------------------------------------------------
 			cards.Add("OG_223", new List<Enchantment> {
-				// TODO [OG_223] Divine Strength && Test: Divine Strength_OG_223
-				new Enchantment
-				{
-					Activation = EnchantmentActivation.SPELL,
-					SingleTask = null,
+				new Enchantment
+				{
+					Activation = EnchantmentActivation.SPELL,
+					SingleTask = new BuffTask(Buffs.AttackHealth(1, 2), EntityType.TARGET)
 				},
 			});


Extend interface of SettingUpdateOperation to allow updates with strings and ISettingValue instances.

--- Sandra.UI.WF/Settings/SettingUpdateOperation.cs
+++ Sandra.UI.WF/Settings/SettingUpdateOperation.cs
@@ -36,7 +36,22 @@
             WorkingCopy = owner.CurrentSettings.CreateWorkingCopy();
         }

-        private SettingUpdateOperation AddOrReplace(SettingKey settingKey, ISettingValue value)
+        /// <summary>
+        /// Adds or replaces a value for a setting key.
+        /// </summary>
+        /// <param name="settingKey">
+        /// The key of the setting to add or replace.
+        /// </param>
+        /// <param name="value">
+        /// The new value of the setting to add or replace.
+        /// </param>
+        /// <returns>
+        /// This instance. See also: https://en.wikipedia.org/wiki/Builder_pattern
+        /// </returns>
+        /// <exception cref="System.ArgumentNullException">
+        /// <paramref name="settingKey"/> is null.
+        /// </exception>
+        public SettingUpdateOperation AddOrReplace(SettingKey settingKey, ISettingValue value)
         {
             WorkingCopy.KeyValueMapping[settingKey] = value;
             return this;
@@ -79,6 +94,24 @@
             => AddOrReplace(settingKey, new Int32SettingValue(value));

         /// <summary>
+        /// Adds or replaces a value for a setting key.
+        /// </summary>
+        /// <param name="settingKey">
+        /// The key of the setting to add or replace.
+        /// </param>
+        /// <param name="value">
+        /// The new value of the setting to add or replace.
+        /// </param>
+        /// <returns>
+        /// This instance. See also: https://en.wikipedia.org/wiki/Builder_pattern
+        /// </returns>
+        /// <exception cref="System.ArgumentNullException">
+        /// <paramref name="settingKey"/> is null.
+        /// </exception>
+        public SettingUpdateOperation AddOrReplace(SettingKey settingKey, string value)
+            => AddOrReplace(settingKey, new StringSettingValue(value));
+
+        /// <summary>
         /// Removes a key and its associated value.
         /// </summary>
         /// <param name="settingKey">


#546 fixed proximitydatum

#546 fixed proximitydatum

--- Sensus.Shared/Probes/Location/ProximityDatum.cs
+++ Sensus.Shared/Probes/Location/ProximityDatum.cs
@@ -51,12 +51,7 @@
             set { _maxDistance = value; }
         }

-        public string Near
-        {
-            get { return _near; }
-            set { _near = value; }
-        }
-
+

         public override string DisplayDetail


remove console log

remove console log

--- Serenity.Script.UI/PropertyGrid/PropertyGrid.cs
+++ Serenity.Script.UI/PropertyGrid/PropertyGrid.cs
@@ -184,7 +184,6 @@
             var optionsAttr = editorType.GetCustomAttributes(typeof(OptionsTypeAttribute), true);
             if (optionsAttr != null && optionsAttr.Length > 0)
             {
-                Console.WriteLine(optionsAttr.Length.ToString());
                 optionsType = optionsAttr[0].As<OptionsTypeAttribute>().OptionsType;
             }


(build) Fixing another stylecop problem

(build) Fixing another stylecop problem

--- Source/SolutionInfo.cs
+++ Source/SolutionInfo.cs
@@ -13,4 +13,4 @@
 [assembly: AssemblyInformationalVersion("0.1.0")]
 [assembly:
     AssemblyCopyright(
-        "Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC")]
+        "Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC")]


ICodeSetWide - offset

ICodeSetWide - offset

--- Source/Code/Collections/ICodeSet/CodeSetWide.cs
+++ Source/Code/Collections/ICodeSet/CodeSetWide.cs
@@ -46,21 +46,22 @@

 		}

-		internal CodeSetWide(BitSetArray bits)
+		internal CodeSetWide(BitSetArray bits, int offset = 0)
 		{
 			Contract.Requires<ArgumentNullException> (!bits.Is(null));
 			Contract.Requires<ArgumentOutOfRangeException> (bits.Length <= Code.MaxCount || bits.Last <= Code.MaxValue);
+			Contract.Requires<ArgumentException> (((int)bits.First + offset).HasCodeValue() && ((int)bits.Last + offset).HasCodeValue());
 			Contract.Requires<ArgumentException> (bits.Count > ICodeSetService.PairCount);
 			Contract.Requires<ArgumentException> (bits.Count < (bits.Last - bits.First));
-			Contract.Requires<ArgumentException> (((Code)bits.First).UnicodePlane() != ((Code)bits.Last).UnicodePlane());
-
-			Contract.Ensures (Theory.Construct (bits, this));
-
-			this.start = (Code)bits.First;
-			this.final = (Code)bits.Last;
+			Contract.Requires<ArgumentException> (((Code)(bits.First + offset)).UnicodePlane() != ((Code)(bits.Last + offset)).UnicodePlane());
+
+			Contract.Ensures (Theory.Construct (bits, offset, this));
+
+			this.start = (Code)(bits.First + offset);
+			this.final = (Code)(bits.Last + offset);

 			this.init (ref this.startPlane, ref this.finalPlane, ref this.planes);
-			this.init (bits);
+			this.init (bits, offset);
 			foreach (ICodeSet codeSet in this.planes) {
 				this.count += codeSet.Count;
 			}
@@ -80,34 +81,26 @@
 			thisPlanes = new ICodeSet[1 + thisFinalPlane - thisStartPlane];
 		}

-		void init (IEnumerable<int> bits) {
+		void init (IEnumerable<int> bits, int offset) {
 			var bitPlanes = getBitPlanes();
-			int currentPlane;
-			int currentValue;
 			foreach (var item in bits) {
-				currentPlane = item >> 16;
-				currentValue = item & 0xFFFF;
-				bitPlanes[currentPlane - this.startPlane].Set(currentValue);
-			}
-			initPlanes(bitPlanes);
+				bitPlanes[(item >> 16) - this.startPlane].Set(item & 0xFFFF);
+			}
+			initPlanes(bitPlanes, offset);
 		}

 		void init (IEnumerable<Code> codes) {
 			var bitPlanes = getBitPlanes();
-			int currentPlane;
-			int currentValue;
 			foreach (Code code in codes) {
-				currentPlane = code >> 16;
-				currentValue = code & 0xFFFF;
-				bitPlanes[currentPlane - this.startPlane].Set(currentValue);
+				bitPlanes[(code >> 16) - this.startPlane].Set(code & 0xFFFF);
 			}
 			initPlanes(bitPlanes);
 		}

-		void initPlanes (BitSetArray[] bitPlanes) {
+		void initPlanes (BitSetArray[] bitPlanes, int offset = 0) {
 			int index = 0;
 			foreach (var bitPlane in bitPlanes) {
-				this.planes[index] = bitPlane.Reduce();
+				this.planes[index] = bitPlane.Reduce(offset + ((index + this.startPlane) << 16));
 				++index;
 			}
 		}
@@ -130,10 +123,8 @@
 		[Pure] public override bool this[Code code] {
 			get {
 				int currentPlane = code.UnicodePlane();
-				if (currentPlane.InRange (this.startPlane, this.finalPlane)) {
-					return planes[currentPlane-this.startPlane][code&0xFFFF];
-				}
-				return false;
+				return currentPlane.InRange(this.startPlane, this.finalPlane)
+					&& planes[currentPlane - this.startPlane][code];
 			}
 		}

@@ -162,12 +153,10 @@
 		}

 		[Pure] public override IEnumerator<Code> GetEnumerator () {
-			int currentPlane = startPlane;
 			foreach (ICodeSet codeSet in this.planes) {
 				foreach ( Code code in codeSet ) {
-					yield return code + (currentPlane << 16);
-				}
-				++currentPlane;
+					yield return code;
+				}
 			}
 		}

@@ -195,13 +184,13 @@
 				foreach (var item in codes.Distinct().OrderBy(code => (code))) {
 					e.MoveNext();
 					success.Assert (item == e.Current); // => SequenceEqual
-					success.Assert (self.planes[item.UnicodePlane()][item & 0xFFFF]);
+					success.Assert (self.planes[item.UnicodePlane()][item]);
 				}

 				return success;
 			}

-			[Pure] public static bool Construct (BitSetArray bits, CodeSetWide self) {
+			[Pure] public static bool Construct (BitSetArray bits, int offset, CodeSetWide self) {

 				// disable once ConvertToConstant.Local
 				Success success = true;
@@ -211,8 +200,8 @@
 				var e = self.GetEnumerator();
 				foreach (Code item in bits) {
 					e.MoveNext();
-					success.Assert (item.Value == e.Current); // => SequenceEqual
-					success.Assert (self.planes[item.UnicodePlane()][item & 0xFFFF]);
+					success.Assert ((item.Value + offset) == e.Current); // => SequenceEqual
+					success.Assert (self.planes[item.UnicodePlane()][item + offset]);
 				}

 				return success;
@@ -235,16 +224,16 @@
 				var finalPlane = self.planes.LastOrDefault();
 				success.Assert (startPlane.Count != 0);
 				success.Assert (finalPlane.Count != 0);
-				success.Assert (startPlane[self.start & 0xFFFF]);
-				success.Assert (finalPlane[self.final & 0xFFFF]);
+				success.Assert (startPlane[self.start]);
+				success.Assert (finalPlane[self.final]);

 				int counter = 0;
 				foreach (ICodeSet iCodeSet in self.planes) {
 					counter += iCodeSet.Count;
 				}
 				success.Assert (self.count == counter);
-				success.Assert ((self.start & 0xFFFF) == startPlane.First);
-				success.Assert ((self.final & 0xFFFF) == finalPlane.Last);
+				success.Assert ((self.start) == startPlane.First);
+				success.Assert ((self.final) == finalPlane.Last);
 				success.Assert (self.count > ICodeSetService.PairCount);// not Null-Pair
 				success.Assert (self.count < (self.final - self.start));// not Full-Pair


Fixed a bug where an exception would occur when trying to submit multiple new events.

--- Source/Core/Pipeline/010_AssignToStackAction.cs
+++ Source/Core/Pipeline/010_AssignToStackAction.cs
@@ -93,7 +93,11 @@
                     }

                     ctx.SignatureHash = ctx.Stack.SignatureHash;
-                    stacks.Add(ctx.Stack.SignatureHash, Tuple.Create(false, ctx.Stack));
+
+                    if (!stacks.ContainsKey(ctx.Stack.SignatureHash))
+                        stacks.Add(ctx.Stack.SignatureHash, Tuple.Create(false, ctx.Stack));
+                    else
+                        stacks[ctx.Stack.SignatureHash] = Tuple.Create(false, ctx.Stack);
                 }

                 if (!ctx.IsNew && ctx.Event.Tags != null && ctx.Event.Tags.Count > 0) {


StandardBody updates

StandardBody updates

SetOutfit() now ignores forceRelease if there is no current outfit.
SetOutfit() now performs an outfit destroyed check.
Most overrides have been sealed.
Fixed access modifier on AccessoriesLocal property.
Documentation updates.

--- Source/Plugins/Lizitt/Outfitter/StandardBody.cs
+++ Source/Plugins/Lizitt/Outfitter/StandardBody.cs
@@ -27,6 +27,30 @@
     ///
     /// Implements all standard <see cref="Body"/> features.
     ///
+    /// <remarks>
+    /// <para>
+    /// The body expectes that it will retain control of its outfit until the outfit is removed using
+    /// <see cref="SetOutfit"/>.  If it detects a loss of control, then it will behave as follows:
+    /// </para>
+    /// <para>
+    /// If the outfit bake event is received the body will perform a forced release.  (See the <see cref="SetOutfit"/>
+    /// documentation.)
+    /// </para>
+    /// <para>
+    /// If a non-bake outfit destroy event is received, the body will attempt a normal release in order to recover
+    /// its assets as best it can.
+    /// </para>
+    /// <para>
+    /// If the body loses ownership of its outfit, or the outfit transtions to the 'stored' or 'unmanaged' state, the
+    /// body will perform a normal release.
+    /// </para>
+    /// <para>
+    /// If the body detects that the outfit was destroyed improperly using Object.Destroy() instead of
+    /// <see cref="Outfit.Destroy"/> then it will perform a forced release in order to clean itself up.  Observers
+    /// will receive the event so they also have a chance to cleanup. What is permanently lost depends on the steps used
+    /// to destroy the outfit.
+    /// </para>
+    /// </remarks>
     [RequireComponent(typeof(BodyAccessoryManager))]
     [AddComponentMenu(LizittUtil.LizittMenu + "StandardBody", OutfitterUtil.BaseMenuOrder + 3)]
     public class StandardBody
@@ -37,17 +61,16 @@
         [Space]

         [SerializeField]
-        [Tooltip("The motion root when there is no outfit assigned.  The body's transform will be used if not assigned"
-            + " prior to initialization.")]
+        [Tooltip("The motion root when there is no outfit assigned.  (Defaults to the body's transform.)")]
         [LocalComponentPopupAttribute(typeof(Transform), true)]
         private Transform m_DefaultMotionRoot = null;

         ///
-        /// The motion root to use when there is no outfit assigned.
+        /// The motion root when there is no outfit assigned.
         ///
         /// <remarks>
         /// <para>
-        /// The body's transform will be used if not assigned prior to initialization.
+        /// Defaults to the body's transform.
         /// </para>
         /// </remarks>
         public Transform DefaultMotionRoot
@@ -63,18 +86,18 @@
             set { m_DefaultMotionRoot = value ? value : transform; }
         }

-        public override Transform MotionRoot
+        public sealed override Transform MotionRoot
         {
             // Must always be avaiable, even in editor mode.
             get { return Outfit ? Outfit.MotionRoot : DefaultMotionRoot; }
         }

-        public override Collider PrimaryCollider
+        public sealed override Collider PrimaryCollider
         {
             get { return Outfit ? Outfit.PrimaryCollider : null; }
         }

-        public override Rigidbody PrimaryRigidBody
+        public sealed override Rigidbody PrimaryRigidBody
         {
             get { return Outfit ? Outfit.PrimaryRigidbody : null; }
         }
@@ -91,7 +114,7 @@
         [HideInInspector]
         private bool m_HasOutfit;  // Used to detect if the outfit has been improperly destroyed.

-        public override Outfit Outfit
+        public sealed override Outfit Outfit
         {
             get
             {
@@ -102,7 +125,7 @@

         public sealed override Outfit SetOutfit(Outfit outfit, bool forceRelease)
         {
-            // Warning: This method can be called by CheckOutfitLost().  So make sure not code paths trigger that
+            // Warning: This method can be called by CheckOutfitLost().  So make sure no code paths trigger that
             // method.

             if (outfit)
@@ -122,7 +145,15 @@
                 }
             }

-            var origOutfit = m_Outfit ? m_Outfit : null;
+            if (forceRelease && !m_HasOutfit)
+            {
+                Debug.LogWarning("Force release ignored.  Body has no outfit to release.", this);
+                forceRelease = false;
+            }
+
+            forceRelease = forceRelease || (m_HasOutfit && !m_Outfit);
+
+            var origOutfit = m_Outfit ? m_Outfit : null;  // Get rid of potential destoryed reference early.

             if (m_Outfit)
             {
@@ -202,8 +233,8 @@
         {
             if (sender.Owner != gameObject)
             {
-                Debug.LogErrorFormat(this, "Unexpected outfit ownership change.  Soft reset"
-                    + " performed: Outfit: {0}, New owner: {1}", sender.name,
+                Debug.LogWarningFormat(this, "Unexpected loss of outfit ownership.  Outfit auto-released."
+                    + " Outfit: {0}, New owner: {1}", sender.name,
                     sender.Owner ? sender.Owner.name : "None");

                 sender.RemoveObserver(this);
@@ -217,8 +248,8 @@
                 case OutfitStatus.Stored:
                 case OutfitStatus.Unmanaged:

-                    Debug.LogErrorFormat(this, "Unsupported outfit status change.  Soft reset"
-                        + " performed: Outfit: {0}, Status: {1}", sender.name, sender.Status);
+                    Debug.LogErrorFormat(this, "Unsupported outfit status change.   Outfit auto-released."
+                        + " Outfit: {0}, Status: {1}", sender.name, sender.Status);

                     sender.RemoveObserver(this);
                     SetOutfit(null);
@@ -239,14 +270,14 @@

         #endregion

-        #region Outfit Utilities
+        #region Outfit Utilities Members

         ///
-        /// Do not call this method from <see cref="SetOutfit"/>!!!!! It can cause reversion.
+        /// Do not call this method from <see cref="SetOutfit"/>!!!!! It can result in an infinite loop.
         ///
         private void CheckOutfitLost()
         {
-            // Don't worry about losing ownership.  That is non-fatal and much less likely to occur.
+            // Don't worry about losing ownership.  That is detected by an event.
             if (m_HasOutfit && !m_Outfit)
             {
                 Debug.LogError("Outfit was improperly destroyed after assignment to body."
@@ -259,9 +290,15 @@

         #region Accessories

+        ///
+        /// Do not access directly.  Use <see cref="AccessoriesLocal"/>.
+        ///
         private BodyAccessoryManager m_Accessories;

-        public BodyAccessoryManager AccessoriesLocal
+        ///
+        /// The accessory manager.
+        ///
+        protected BodyAccessoryManager AccessoriesLocal
         {
             get
             {
@@ -272,7 +309,7 @@
             }
         }

-        public override IBodyAccessoryManager Accessories
+        public sealed override IBodyAccessoryManager Accessories
         {
             get { return AccessoriesLocal; }
         }
@@ -326,6 +363,26 @@
             Observers.SendOutfitChange(this, previous, wasForced);
         }

+        ///
+        /// Called at the end of an outfit change operation.
+        ///
+        /// <remarks>
+        /// <para>
+        /// There are three situations when a forced release is performed:
+        /// </para>
+        /// <para>
+        ///

+        ///
<see cref="SetOutfit"/> was used to initiate the forced release.

+        ///
A bake event was received from the outfit.

+        ///

+        /// The body detected that the outfit was improperly destroyed using Object.Destory() directly, instead of
+        /// through <see cref="Outfit.Destory"/>.
+        ///

+        ///

+        /// </para>
+        /// </remarks>
+        /// <param name="previous">The previous outfit, or null if there is none.</param>
+        /// <param name="wasForced">True if a forced release was performed.</param>
         protected virtual void OnOutfitChange(Outfit previous, bool wasForced)
         {
             // Do nothing.


Fix failing test due to early lifetime end

--- osu.Game.Rulesets.Osu/Objects/Drawables/Connections/FollowPointRenderer.cs
+++ osu.Game.Rulesets.Osu/Objects/Drawables/Connections/FollowPointRenderer.cs
@@ -143,8 +143,7 @@
             public FollowPointLifetimeEntry(OsuHitObject start)
             {
                 Start = start;
-
-                LifetimeStart = LifetimeEnd = Start.StartTime;
+                LifetimeStart = Start.StartTime;
             }

             private OsuHitObject end;
@@ -178,6 +177,7 @@
                 double fadeInTime = fadeOutTime - FollowPointConnection.PREEMPT;

                 LifetimeStart = fadeInTime;
+                LifetimeEnd = double.MaxValue; // This will be set by the connection.
             }
         }
     }


Blueprints - Use IList instead of List for Blueprint.ComponentTypes property

--- Source/Slash.ECS.Blueprints/Source/Blueprint.cs
+++ Source/Slash.ECS.Blueprints/Source/Blueprint.cs
@@ -99,7 +99,7 @@
         ///   this blueprint.
         /// </summary>
         [XmlIgnore]
-        public List<Type> ComponentTypes { get; set; }
+        public IList<Type> ComponentTypes { get; set; }

         /// <summary>
         ///   Wrapper for ComponentTypes property for xml serialization.
@@ -345,7 +345,7 @@
         /// <returns>True if it should be serialized; otherwise, false.</returns>
         public bool ShouldSerializeComponentTypesSerialized()
         {
-            return this.ComponentTypes != null && this.ComponentTypes.Count > 0;
+            return this.ComponentTypes != null && this.ComponentTypes.Any();
         }

         /// <summary>
@@ -399,7 +399,7 @@
                 writer.WriteEndElement();
             }

-            if (this.ComponentTypes.Count > 0)
+            if (this.ComponentTypesSerialized.Length > 0)
             {
                 writer.WriteStartElement(ComponentTypesElementName);
                 foreach (string componentType in this.ComponentTypesSerialized)


InputBox now uses OpenTK's Color4 class to represent colors.

--- SpaceTradingGame/Engine/UI/Controls/InputBox.cs
+++ SpaceTradingGame/Engine/UI/Controls/InputBox.cs
@@ -3,6 +3,7 @@
 using System.Collections.Generic;
 using OpenTK;
 using OpenTK.Input;
+using OpenTK.Graphics;

 namespace SpaceTradingGame.Engine.UI.Controls
 {
@@ -132,8 +133,8 @@
         }

         private string text;
-        private Color textColor = Color.White;
-        private Color fillColor = Color.Black;
+        private Color4 textColor = Color4.White;
+        private Color4 fillColor = Color4.Black;

         private bool hasFocus = false;
         private bool isMultiline = false;
@@ -150,8 +151,8 @@

         #region Properties
         public string Text { get { return this.text; } set { this.text = value; } }
-        public Color TextColor { get { return this.textColor; } set { this.textColor = value; } }
-        public Color FillColor { get { return this.fillColor; } set { this.fillColor = value; } }
+        public Color4 TextColor { get { return this.textColor; } set { this.textColor = value; } }
+        public Color4 FillColor { get { return this.fillColor; } set { this.fillColor = value; } }
         public bool HasFocus { get { return this.hasFocus; } set { this.hasFocus = value; } }
         //public bool IsMultiline { get { return this.isMultiline; } set { this.isMultiline = value; } }
         public bool ShowCursor { get { return this.showCursor; } set { this.showCursor = value; } }


#refactor, extract method + extract variable

--- StringDistance/LevenshteinDistanceCalculator.cs
+++ StringDistance/LevenshteinDistanceCalculator.cs
@@ -5,40 +5,62 @@
 {
     public class LevenshteinDistanceCalculator
     {
-        public int Distance (string source, string target)
+        public int Distance(string source, string target)
         {
-            if (AnyStringIsNullOrEmpty (source, target))
-                return LengthOfTheLongestString (source, target);
+            if (AnyStringIsNullOrEmpty(source, target))
+                return LengthOfTheLongestString(source, target);

-            var n = source.Length;
-            var m = target.Length;
-            var score = new int[n + 1, m + 1];
+            var score = PrepareScoreMatrix(source, target);

-            for (var i = 0; i <= n; score[i, 0] = i++) {
-            }
-            for (var j = 0; j <= m; score[0, j] = j++) {
-            }
-            for (var i = 1; i <= n; i++) {
-                for (var j = 1; j <= m; j++) {
-                    var cost = (target [j - 1] == source [i - 1]) ? 0 : 1;
-                    score [i, j] = Math.Min (Math.Min (score [i - 1, j] + 1, score [i, j - 1] + 1), score [i - 1, j - 1] + cost);
+            for (var i = 1; i <= source.Length; i++)
+            {
+                for (var j = 1; j <= target.Length; j++)
+                {
+                    var cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
+
+                    var delete = score[i - 1, j] + 1;
+                    var insert = score[i, j - 1] + 1;
+                    var replace = score[i - 1, j - 1] + cost;
+
+                    score[i, j] = Minimum(delete, insert, replace);
                 }
             }

-            return score [n, m];
+            return score[source.Length, target.Length];
         }

-        private bool AnyStringIsNullOrEmpty (string string1, string string2)
+        private int[,] PrepareScoreMatrix(string source, string target)
         {
-            return String.IsNullOrEmpty (string1)
-                || String.IsNullOrEmpty (string2);
+            var sourceLength = source.Length;
+            var targetLength = target.Length;
+            var score = new int[sourceLength + 1, targetLength + 1];
+
+            for (var i = 0; i <= sourceLength; score[i, 0] = i++)
+            {
+            }
+            for (var j = 0; j <= targetLength; score[0, j] = j++)
+            {
+            }
+
+            return score;
         }

-        private int LengthOfTheLongestString (params string[] strings)
+        private int Minimum(int int1, int int2, int int3)
+        {
+            return Math.Min(Math.Min(int1, int2), int3);
+        }
+
+        private bool AnyStringIsNullOrEmpty(string string1, string string2)
+        {
+            return String.IsNullOrEmpty(string1)
+                || String.IsNullOrEmpty(string2);
+        }
+
+        private int LengthOfTheLongestString(params string[] strings)
         {
             return strings
-                .Select (word => word ?? string.Empty)
-                    .Max (word => word.Length);
+                .Select(word => word ?? string.Empty)
+                .Max(word => word.Length);
         }
     }
 }