Fixup test to actually work

Fixup test to actually work

--- src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs
+++ src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs
@@ -19,12 +19,10 @@
 using Microsoft.CodeAnalysis.Remote.DebugUtil;
 using Microsoft.CodeAnalysis.Remote.Shared;
 using Microsoft.CodeAnalysis.Serialization;
-using Microsoft.CodeAnalysis.SolutionCrawler;
 using Microsoft.CodeAnalysis.Test.Utilities;
 using Microsoft.CodeAnalysis.Text;
 using Microsoft.CodeAnalysis.TodoComments;
 using Microsoft.CodeAnalysis.UnitTests;
-using Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute;
 using Nerdbank;
 using Roslyn.Test.Utilities.Remote;
 using Roslyn.Utilities;
@@ -136,23 +134,69 @@
         [Fact, Trait(Traits.Feature, Traits.Features.RemoteHost)]
         public async Task TestTodoComments()
         {
-            var code = @"// TODO: Test";
-
-            using (var workspace = TestWorkspace.CreateCSharp(code))
-            {
-                var client = (InProcRemoteHostClient)(await InProcRemoteHostClient.CreateAsync(workspace, runCacheCleanup: false));
-
-                var solution = workspace.CurrentSolution;
-
-                var comments = await client.TryRunRemoteAsync<IList<TodoComment>>(
-                    WellKnownServiceHubServices.CodeAnalysisService,
-                    nameof(IRemoteTodoCommentsService.ComputeTodoCommentsAsync),
-                    solution,
-                    new object[] { solution.Projects.First().DocumentIds.First(), ImmutableArray.Create(new TodoCommentDescriptor("TODO", 0)) },
-                    callbackTarget: null,
-                    CancellationToken.None);
-
-                Assert.Equal(1, comments.Value.Count);
+            using var workspace = TestWorkspace.CreateCSharp(@"
+
+// TODO: Test");
+
+            var cancellationTokenSource = new CancellationTokenSource();
+
+            var solution = workspace.CurrentSolution;
+
+            // Ensure remote workspace is in sync with normal workspace.
+            var solutionService = await GetSolutionServiceAsync(solution);
+            var solutionChecksum = await solution.State.GetChecksumAsync(CancellationToken.None);
+            await solutionService.UpdatePrimaryWorkspaceAsync(solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);
+
+            var callback = new TodoCommentsListener();
+
+            using var client = await InProcRemoteHostClient.CreateAsync(workspace, runCacheCleanup: false);
+            var session = await client.TryCreateKeepAliveSessionAsync(
+                WellKnownServiceHubServices.RemoteTodoCommentsService,
+                callback,
+                cancellationTokenSource.Token);
+
+            var invokeTask = session.TryInvokeAsync(
+                nameof(IRemoteTodoCommentsService.ComputeTodoCommentsAsync),
+                solution: null,
+                arguments: Array.Empty<object>(),
+                cancellationTokenSource.Token);
+
+            var data = await callback.Data;
+            Assert.Equal(solution.Projects.Single().Documents.Single().Id, data.Item1);
+            Assert.Equal(1, data.Item2.Count);
+
+            var commentInfo = data.Item2[0];
+            Assert.Equal(new TodoCommentData
+            {
+                DocumentId = solution.Projects.Single().Documents.Single().Id,
+                Priority = 1,
+                Message = "TODO: Test",
+                MappedFilePath = null,
+                OriginalFilePath = "test1.cs",
+                OriginalLine = 2,
+                MappedLine = 2,
+                OriginalColumn = 3,
+                MappedColumn = 3,
+            }, commentInfo);
+
+            cancellationTokenSource.Cancel();
+
+            await invokeTask;
+        }
+
+        private class TodoCommentsListener : ITodoCommentsListener
+        {
+            private readonly TaskCompletionSource<(DocumentId, List<TodoCommentData>)> _dataSource
+                = new TaskCompletionSource<(DocumentId, List<TodoCommentData>)>();
+            public Task<(DocumentId, List<TodoCommentData>)> Data => _dataSource.Task;
+
+            public Task OnDocumentRemovedAsync(DocumentId documentId, CancellationToken cancellationToken)
+                => Task.CompletedTask;
+
+            public Task ReportTodoCommentDataAsync(DocumentId documentId, List<TodoCommentData> data, CancellationToken cancellationToken)
+            {
+                _dataSource.SetResult((documentId, data));
+                return Task.CompletedTask;
             }
         }

@@ -175,7 +219,6 @@
         [Fact, Trait(Traits.Feature, Traits.Features.RemoteHost)]
         public async Task TestDesignerAttributes()
         {
-
             using var workspace = TestWorkspace.CreateCSharp(
 @"[System.ComponentModel.DesignerCategory(""Form"")]
 class Test { }");
@@ -189,7 +232,7 @@
             var solutionChecksum = await solution.State.GetChecksumAsync(CancellationToken.None);
             await solutionService.UpdatePrimaryWorkspaceAsync(solutionChecksum, solution.WorkspaceVersion, CancellationToken.None);

-            var callback = new DesignerListener();
+            var callback = new DesignerAttributeListener();

             using var client = await InProcRemoteHostClient.CreateAsync(workspace, runCacheCleanup: false);
             var session = await client.TryCreateKeepAliveSessionAsync(
@@ -215,10 +258,13 @@
             await invokeTask;
         }

-        private class DesignerListener : IDesignerAttributeListener
+        private class DesignerAttributeListener : IDesignerAttributeListener
         {
             private readonly TaskCompletionSource<IList<DesignerAttributeData>> _infosSource = new TaskCompletionSource<IList<DesignerAttributeData>>();
             public Task<IList<DesignerAttributeData>> Infos => _infosSource.Task;
+
+            public Task OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken)
+                => Task.CompletedTask;

             public Task ReportDesignerAttributeDataAsync(IList<DesignerAttributeData> infos, CancellationToken cancellationToken)
             {


GetInvoiceRaw used its own dbContext  while calling code used a different one which causes the calling context not to track changes - thus nothing is saved. (#2197)

Co-authored-by: Salie Hendricks <1007b136b8abd512bfc9a810120434d4af89cf2b@safarinow.com>

--- BTCPayServer/Services/Invoices/InvoiceRepository.cs
+++ BTCPayServer/Services/Invoices/InvoiceRepository.cs
@@ -413,7 +413,7 @@
         {
             using (var context = _ContextFactory.CreateContext())
             {
-                var invoiceData = await GetInvoiceRaw(invoiceId);
+                var invoiceData = await GetInvoiceRaw(invoiceId, context);
                 if (invoiceData == null || (storeId != null &&
                                             !invoiceData.StoreDataId.Equals(storeId,
                                                 StringComparison.InvariantCultureIgnoreCase)))
@@ -429,7 +429,7 @@
         {
             using (var context = _ContextFactory.CreateContext())
             {
-                var invoiceData = await GetInvoiceRaw(invoiceId);
+                var invoiceData = await GetInvoiceRaw(invoiceId, context);
                 if (invoiceData == null)
                 {
                     return false;
@@ -472,8 +472,11 @@

         public async Task<InvoiceEntity> GetInvoice(string id, bool inludeAddressData = false)
         {
-            var res = await GetInvoiceRaw(id, inludeAddressData);
-            return res == null ? null : ToEntity(res);
+            using (var context = _ContextFactory.CreateContext())
+            {
+                var res = await GetInvoiceRaw(id, context, inludeAddressData);
+                return res == null ? null : ToEntity(res);
+            }
         }
         public async Task<InvoiceEntity[]> GetInvoices(string[] invoiceIds)
         {
@@ -490,24 +493,21 @@
             }
         }

-        private async Task<InvoiceData> GetInvoiceRaw(string id, bool inludeAddressData = false)
-        {
-            using (var context = _ContextFactory.CreateContext())
-            {
-                IQueryable<Data.InvoiceData> query =
-                    context
+        private async Task<InvoiceData> GetInvoiceRaw(string id, ApplicationDbContext dbContext, bool inludeAddressData = false)
+        {
+            IQueryable<Data.InvoiceData> query =
+                    dbContext
                     .Invoices
                     .Include(o => o.Payments);
-                if (inludeAddressData)
-                    query = query.Include(o => o.HistoricalAddressInvoices).Include(o => o.AddressInvoices);
-                query = query.Where(i => i.Id == id);
-
-                var invoice = (await query.ToListAsync()).FirstOrDefault();
-                if (invoice == null)
-                    return null;
-
-                return invoice;
-            }
+            if (inludeAddressData)
+                query = query.Include(o => o.HistoricalAddressInvoices).Include(o => o.AddressInvoices);
+            query = query.Where(i => i.Id == id);
+
+            var invoice = (await query.ToListAsync()).FirstOrDefault();
+            if (invoice == null)
+                return null;
+
+            return invoice;
         }

         private InvoiceEntity ToEntity(Data.InvoiceData invoice)


Refactoring

Refactoring

--- src/AsimovDeploy.WinAgent/Framework/Heartbeat/HeartbeatService.cs
+++ src/AsimovDeploy.WinAgent/Framework/Heartbeat/HeartbeatService.cs
@@ -142,7 +142,7 @@
             }
             catch (WebException e)
             {
-                Log.Warn("Error sending heartbeat to NodeFront", e);
+                Log.Warn($"Error sending heartbeat to NodeFront ({uri})", e);
             }
         }
     }


Added support for uninstalling several add-ins at once.

--- Mono.Addins.Setup/Mono.Addins.Setup/SetupService.cs
+++ Mono.Addins.Setup/Mono.Addins.Setup/SetupService.cs
@@ -270,6 +270,20 @@
 		}

 		/// <summary>
+		/// Uninstalls a set of add-ins
+		/// </summary>
+		/// <param name='statusMonitor'>
+		/// Progress monitor where to show progress status
+		/// </param>
+		/// <param name='ids'>
+		/// Full identifiers of the add-ins to uninstall.
+		/// </param>
+		public void Uninstall (IProgressStatus statusMonitor, IEnumerable<string> ids)
+		{
+			store.Uninstall (statusMonitor, ids);
+		}
+
+		/// <summary>
 		/// Gets information about an add-in
 		/// </summary>
 		/// <param name="addin">


Remove device collection before adding submission

--- MusicPickerService/Controllers/DevicesController.cs
+++ MusicPickerService/Controllers/DevicesController.cs
@@ -124,6 +124,19 @@
         [HttpPost]
         public IHttpActionResult SubmitMusic(int id, List<DeviceSubmission> submissions)
         {
+            Device device = db.Devices.Find(id);
+            if (device == null)
+            {
+                return NotFound();
+            }
+
+            if (!isDeviceOwner(device))
+            {
+                return Unauthorized();
+            }
+
+            db.DeviceTracks.RemoveRange(db.DeviceTracks.Where(e => e.DeviceId == id));
+
             foreach (DeviceSubmission submission in submissions)
             {
                 Artist artist;


Better handling of missing parameters and erroneous parameters in EtlCatalogRunner

--- NBi.Core/Etl/IntegrationService/EtlCatalogRunner.cs
+++ NBi.Core/Etl/IntegrationService/EtlCatalogRunner.cs
@@ -11,7 +11,21 @@
         public EtlCatalogRunner(IEtl etl)
             : base(etl)
         {
+            var argumentNullExceptionSentence = "You must specify a value for parameter '{0}' when using an EtlCatalogRunner";
+            if (string.IsNullOrEmpty(Etl.Server))
+                throw new ArgumentNullException("Server", string.Format(argumentNullExceptionSentence, "Server"));

+            if (string.IsNullOrEmpty(Etl.Catalog))
+                throw new ArgumentNullException("Catalog", string.Format(argumentNullExceptionSentence, "Catalog"));
+
+            if (string.IsNullOrEmpty(Etl.Folder))
+                throw new ArgumentNullException("Folder", string.Format(argumentNullExceptionSentence, "Folder"));
+
+            if (string.IsNullOrEmpty(Etl.Project))
+                throw new ArgumentNullException("Project", string.Format(argumentNullExceptionSentence, "Project"));
+
+            if (string.IsNullOrEmpty(Etl.Name))
+                throw new ArgumentNullException("Name", string.Format(argumentNullExceptionSentence, "Name"));
         }

         public override IExecutionResult Run()
@@ -19,10 +33,9 @@
             var connection = new SqlConnection(string.Format(@"Data Source={0};Initial Catalog=master;Integrated Security=SSPI;", Etl.Server));
             var integrationServices = new IntegrationServices(connection);

-            var catalog = integrationServices.Catalogs[Etl.Catalog];
-            var folder  = catalog.Folders[Etl.Folder];
-            var project = folder.Projects[Etl.Project];
-            var package = project.Packages[Etl.Name];
+            Catalog catalog;
+            PackageInfo package;
+            GetPackage(integrationServices, out catalog, out package);

             var setValueParameters = new Collection<PackageInfo.ExecutionValueParameterSet>();
             setValueParameters.Add(new PackageInfo.ExecutionValueParameterSet
@@ -46,6 +59,45 @@

         }

+        private void GetPackage(IntegrationServices integrationServices, out Catalog catalog, out PackageInfo package)
+        {
+
+            if (integrationServices.Catalogs.Contains(Etl.Catalog))
+                catalog = integrationServices.Catalogs[Etl.Catalog];
+            else
+            {
+                var names = String.Join(", ",integrationServices.Catalogs.Select(c => c.Name));
+                throw new ArgumentOutOfRangeException("Catalog", String.Format("The catalog named '{0}' hasn't been found on the server '{1}'. List of existing catalogs: {2}.", Etl.Catalog, Etl.Server, names));
+            }
+
+
+            CatalogFolder folder;
+            if (catalog.Folders.Contains(Etl.Folder))
+                folder = catalog.Folders[Etl.Folder];
+            else
+            {
+                var names = String.Join(", ", catalog.Folders.Select(f => f.Name));
+                throw new ArgumentOutOfRangeException("Folder", String.Format("The folder named '{0}' hasn't been found on the catalog '{1}'. List of existing folders: {2}.", Etl.Folder, Etl.Catalog, names));
+            }
+
+            ProjectInfo project;
+            if (folder.Projects.Contains(Etl.Project))
+                project = folder.Projects[Etl.Project];
+            else
+            {
+                var names = String.Join(", ", folder.Projects.Select(p => p.Name));
+                throw new ArgumentOutOfRangeException("Project", String.Format("The project named '{0}' hasn't been found on the catalog '{1}'. List of existing projects: {2}.", Etl.Project, Etl.Folder, names));
+            }
+
+            if (project.Packages.Contains(Etl.Name))
+                package = project.Packages[Etl.Name];
+            else
+            {
+                var names = String.Join(", ", project.Packages.Select(p => p.Name));
+                throw new ArgumentOutOfRangeException("Name", String.Format("The package named '{0}' hasn't been found on the project '{1}'. List of existing packages: {2}.", Etl.Name, Etl.Project, names));
+            }
+        }
+
     }
 }


ABCP Weight Chart

ABCP Weight Chart

Fixes #64

--- Battery-Commander.Web/Views/Soldiers/Details.cshtml
+++ Battery-Commander.Web/Views/Soldiers/Details.cshtml
@@ -130,6 +130,11 @@
                 }

+
+        @if (Model.ABCPs.Count > 1)
+        {
+

+        }

@@ -144,7 +149,7 @@
 @section Scripts
 {
     @{
-        var chart_data =
+        var apft_data =
             Model
             .APFTs
             .OrderBy(apft => apft.Date)
@@ -152,6 +157,17 @@
             {
                 date = apft.Date.ToString("yyyy-MM-dd"),
                 score = apft.TotalScore
+            })
+            .ToList();
+
+        var abcp_data =
+            Model
+            .ABCPs
+            .OrderBy(abcp => abcp.Date)
+            .Select(abcp => new
+            {
+                date = abcp.Date.ToString("yyyy-MM-dd"),
+                weight = abcp.Weight
             })
             .ToList();
     }
@@ -163,30 +179,49 @@
         google.charts.load('current', { 'packages': ['corechart'] });

         // Set a callback to run when the Google Visualization API is loaded.
-        google.charts.setOnLoadCallback(drawChart);
-
-        var result = JSON.parse('@Json.Serialize(chart_data)');
-
-        function drawChart() {
+        google.charts.setOnLoadCallback(draw_apft_chart);
+
+        var apft_data = JSON.parse('@Json.Serialize(apft_data)');
+
+        var abcp_data = JSON.parse('@Json.Serialize(abcp_data)');
+
+        function draw_apft_chart() {
             // Create the data table.
             var data = new google.visualization.DataTable();

             data.addColumn('date', 'Date');
             data.addColumn('number', 'Score');

-            for (var i = 0; i < result.length; i++)
-            {
-                data.addRow([new Date(result[i].date), result[i].score]);
+            for (var i = 0; i < apft_data.length; i++)
+            {
+                data.addRow([new Date(apft_data[i].date), apft_data[i].score]);
             }

-            var options = {
+            var chart = new google.visualization.LineChart(document.getElementById('apft_chart'));
+
+            chart.draw(data, {
                 title: 'APFT Scores',
                 legend: { position: 'bottom' }
-            };
-
-            var chart = new google.visualization.LineChart(document.getElementById('apft_chart'));
-
-            chart.draw(data, options);
+            });
+        }
+
+        function draw_abcp_chart() {
+            // Create the data table.
+            var data = new google.visualization.DataTable();
+
+            data.addColumn('date', 'Date');
+            data.addColumn('number', 'Weight');
+
+            for (var i = 0; i < abcp_data.length; i++) {
+                data.addRow([new Date(abcp_data[i].date), abcp_data[i].weight]);
+            }
+
+            var chart = new google.visualization.LineChart(document.getElementById('abcp_chart'));
+
+            chart.draw(data, {
+                title: 'ACBP - Weight',
+                legend: { position: 'bottom' }
+            });
         }
     </script>
 }


Add test for rebinding ISolrConnection with multiple cores

--- Ninject.Integration.SolrNet.Tests/MultiCoreTests.cs
+++ Ninject.Integration.SolrNet.Tests/MultiCoreTests.cs
@@ -16,9 +16,12 @@

 using System;
 using MbUnit.Framework;
+using Moroco;
 using Ninject.Integration.SolrNet.Config;
 using SolrNet;
 using System.Configuration;
+using SolrNet.Exceptions;
+using SolrNet.Tests.Mocks;

 namespace Ninject.Integration.SolrNet.Tests {
     [TestFixture]
@@ -145,5 +148,45 @@
             var solr2 = kernel.Get<ISolrOperations<Entity>>("core-1");
             Assert.IsNotNull(solr2);
         }
+
+        [Test]
+        public void MultiCore_Rebind_IConnection()
+        {
+            var solrServers = new SolrServers {
+                new SolrServerElement {
+                    Id = "core-0",
+                    Url = "http://localhost:8983/solr/core0",
+                    DocumentType = typeof(Entity).AssemblyQualifiedName,
+                },
+                new SolrServerElement {
+                    Id = "core-1",
+                    Url = "http://localhost:8983/solr/core1",
+                    DocumentType = typeof(Entity).AssemblyQualifiedName,
+                }
+            };
+            kernel.Load(new SolrNetModule(solrServers));
+
+            const string Response = @"<?xml version=""1.0"" encoding=""UTF-8""?>
+<response>
+<lst name=""responseHeader""><int name=""status"">0</int><int name=""QTime"">0</int><lst name=""params""><str name=""q"">id:123456</str><str name=""?""/><str name=""version"">2.2</str></lst></lst><result name=""response"" numFound=""1"" start=""0""><doc></doc></result>
+</response>
+";
+
+            var solr1 = kernel.Get<ISolrOperations<Entity>>("core-0");
+            Assert.IsNotNull(solr1);
+
+            Assert.Throws<SolrConnectionException>(() => solr1.Query("SomeField:Value"));
+
+            MSolrConnection conn = new MSolrConnection();
+            conn.get &= x => x.Return(Response);
+            kernel.Rebind<ISolrConnection>().ToConstant(conn).WithMetadata("CoreId", "core-0");
+            kernel.Rebind<ISolrConnection>().ToConstant(conn).WithMetadata("CoreId", "core-1");
+
+            var solr2 = kernel.Get<ISolrOperations<Entity>>("core-1");
+            Assert.IsNotNull(solr2);
+
+            var r = solr2.Query("SomeField:Value");
+            Assert.AreEqual(1, r.NumFound);
+        }
     }
 }


Fixed movement to portals Replaced autoConnect references with config.AutoConnect Fixed some InvalidOperationExceptions Changed CalculateMovement method slightly

--- FameBot/Core/Plugin.cs
+++ FameBot/Core/Plugin.cs
@@ -140,6 +140,9 @@

             config = ConfigManager.GetConfiguration();

+            if (config.AutoConnect)
+                Start();
+
             Process[] processes = Process.GetProcessesByName("flash");
             if (processes.Length == 1)
             {
@@ -231,7 +234,7 @@
         {
             Log("Starting bot");
             targets.Clear();
-            if (!autoConnect)
+            if (!config.AutoConnect)
                 followTarget = true;
             enabled = true;
         }
@@ -280,7 +283,7 @@
                             var strArray = data.StringValue.Split(' ');
                             var strCount = strArray[1].Split('/')[0].Remove(0, 1);
                             var name = strArray[0].Split('.')[1];
-                            var portal = new Portal(obj.Status.ObjectId, int.Parse(strCount), name);
+                            var portal = new Portal(obj.Status.ObjectId, int.Parse(strCount), name, obj.Status.Position);
                             if (portals.Exists(ptl => ptl.ObjectId == obj.Status.ObjectId))
                                 portals.Remove(portals.Find(ptl => ptl.ObjectId == obj.Status.ObjectId));
                             portals.Add(portal);
@@ -323,8 +326,11 @@
             {
                 await Task.Delay(TimeSpan.FromSeconds(10));
                 portals.Clear();
-                if (packet.Name == "Nexus" && autoConnect)
+                if (packet.Name == "Nexus" && config.AutoConnect)
+                {
                     gotoRealm = true;
+                    MoveToRealms(client);
+                }
                 else
                 {
                     gotoRealm = false;
@@ -353,14 +359,9 @@
             float healthPercentage = (float)client.PlayerData.Health / (float)client.PlayerData.MaxHealth;
             healthChanged?.Invoke(this, new HealthChangedEventArgs(healthPercentage * 100f));

-            if(autoConnect && gotoRealm)
-            {
-                MoveToRealms(client, healthPercentage);
-            }
-
             if(tickCount % config.TickCountThreshold == 0)
             {
-                if (followTarget && playerPosisions.Count > 0)
+                if (followTarget && playerPosisions.Count > 0 && !gotoRealm)
                 {
                     List<Target> newTargets = D36n4.Invoke(playerPosisions.Values.ToList(), config.Epsilon, config.MinPoints, config.FindClustersNearCenter);
                     if(newTargets == null)
@@ -421,26 +422,42 @@
                     client.SendToServer(tpPacket);
                 }

-                CalculateMovement(client, targetPosition);
+                CalculateMovement(client, targetPosition, config.FollowDistanceThreshold);
             }
         }
         #endregion

-        private void MoveToRealms(Client client, float healthPercentage)
+        private async void MoveToRealms(Client client)
         {
             Location target = new Location(134, 109);
+            var healthPercentage = (float)client.PlayerData.Health / (float)client.PlayerData.MaxHealth;
+            var callAgain = true;
             if (healthPercentage < 0.95f)
                 target = new Location(134, 134);

-            CalculateMovement(client, target);
-
-            if(client.PlayerData.Pos.Y <= 109 && client.PlayerData.Pos.Y != 0)
+            if(client.PlayerData.Pos.Y <= 115 && client.PlayerData.Pos.Y != 0)
+            {
+                if (portals.Count != 0)
+                    target = portals.OrderByDescending(p => p.PlayerCount).First().Location;
+                else
+                    target = new Location(134, 109);
+            }
+
+            CalculateMovement(client, target, 0.5f);
+
+            if(client.PlayerData.Pos.DistanceTo(target) < 1f && portals.Count != 0)
             {
                 gotoRealm = false;
-                Task.Factory.StartNew(() =>
-                {
-                    AttemptConnection(client, portals.OrderByDescending(p => p.PlayerCount).First());
-                });
+                callAgain = false;
+                AttemptConnection(client, portals.OrderByDescending(p => p.PlayerCount).First());
+            }
+            await Task.Delay(15);
+            if (callAgain)
+            {
+                MoveToRealms(client);
+            } else
+            {
+                Log("Finished moving to realm. Attempting connection");
             }
         }

@@ -448,18 +465,19 @@
         {
             UsePortalPacket packet = (UsePortalPacket)Packet.Create(PacketType.USEPORTAL);
             packet.ObjectId = portal.ObjectId;
-            client.SendToServer(packet);
-            if(client.Connected)
-            {
-                await Task.Delay(TimeSpan.FromSeconds(0.2));
+            if (client.Connected)
+                client.SendToServer(packet);
+            await Task.Delay(TimeSpan.FromSeconds(0.1));
+            if (client.Connected)
                 AttemptConnection(client, portal);
-            }
-        }
-
-        private void CalculateMovement(Client client, Location targetPosition)
+            else
+                Log("Connection successful");
+        }
+
+        private void CalculateMovement(Client client, Location targetPosition, float tolerance)
         {
             // Left or right
-            if (client.PlayerData.Pos.X < targetPosition.X - config.FollowDistanceThreshold)
+            if (client.PlayerData.Pos.X < targetPosition.X - tolerance)
             {
                 // Move right
                 if (!D_PRESSED)
@@ -473,7 +491,7 @@
                     A_PRESSED = false;
                 }
             }
-            else if (client.PlayerData.Pos.X <= targetPosition.X + config.FollowDistanceThreshold)
+            else if (client.PlayerData.Pos.X <= targetPosition.X + tolerance)
             {
                 if (D_PRESSED)
                 {
@@ -481,7 +499,7 @@
                     D_PRESSED = false;
                 }
             }
-            if (client.PlayerData.Pos.X > targetPosition.X + config.FollowDistanceThreshold)
+            if (client.PlayerData.Pos.X > targetPosition.X + tolerance)
             {
                 // Move left
                 if (!A_PRESSED)
@@ -495,7 +513,7 @@
                     D_PRESSED = false;
                 }
             }
-            else if (client.PlayerData.Pos.X >= targetPosition.X - config.FollowDistanceThreshold)
+            else if (client.PlayerData.Pos.X >= targetPosition.X - tolerance)
             {
                 if (A_PRESSED)
                 {
@@ -505,7 +523,7 @@
             }

             // Up or down
-            if (client.PlayerData.Pos.Y < targetPosition.Y - config.FollowDistanceThreshold)
+            if (client.PlayerData.Pos.Y < targetPosition.Y - tolerance)
             {
                 // Move down
                 if (!S_PRESSED)
@@ -519,7 +537,7 @@
                     W_PRESSED = false;
                 }
             }
-            else if (client.PlayerData.Pos.Y <= targetPosition.Y + config.FollowDistanceThreshold)
+            else if (client.PlayerData.Pos.Y <= targetPosition.Y + tolerance)
             {
                 if (S_PRESSED)
                 {
@@ -527,7 +545,7 @@
                     S_PRESSED = false;
                 }
             }
-            if (client.PlayerData.Pos.Y > targetPosition.Y + config.FollowDistanceThreshold)
+            if (client.PlayerData.Pos.Y > targetPosition.Y + tolerance)
             {
                 // Move up
                 if (!W_PRESSED)
@@ -541,7 +559,7 @@
                     S_PRESSED = false;
                 }
             }
-            else if (client.PlayerData.Pos.Y >= targetPosition.Y - config.FollowDistanceThreshold)
+            else if (client.PlayerData.Pos.Y >= targetPosition.Y - tolerance)
             {
                 if (W_PRESSED)
                 {


Renderer is intancable

Renderer is intancable

--- CSharpGL/ModernRendering/ModernRenderer/Renderer.cs
+++ CSharpGL/ModernRendering/ModernRenderer/Renderer.cs
@@ -9,7 +9,7 @@
     /// <summary>
     /// 用Shader+VBO(VAO)进行渲染。
     /// </summary>
-    public abstract partial class Renderer : RendererBase
+    public partial class Renderer : RendererBase
     {
         protected string positionNameInIBufferable;
         internal PropertyBufferPtr positionBufferPtr;


fixed a small bug in DeferredFog

fixed a small bug in DeferredFog

--- Cat/PostProcessing/CatDeferredFog/CatDeferredFog.cs
+++ Cat/PostProcessing/CatDeferredFog/CatDeferredFog.cs
@@ -23,7 +23,7 @@
 			get { return DepthTextureMode.Depth; }
 		}
 		override public bool isActive {
-			get { return true; }
+			get { return RenderSettings.fog; }
 		}

 		static class PropertyIDs {


added new unit tests

added new unit tests

--- Octokit.Tests/Clients/RepositoryPagesClientTests.cs
+++ Octokit.Tests/Clients/RepositoryPagesClientTests.cs
@@ -49,6 +49,9 @@

                 await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name"));
                 await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null));
+
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("", "name"));
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", ""));
             }
         }

@@ -161,6 +164,47 @@

                 await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetLatest(null, "name"));
                 await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetLatest("owner", null));
+
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetLatest("", "name"));
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetLatest("owner", ""));
+            }
+        }
+
+        public class TheRequestPageBuildMethod
+        {
+            [Fact]
+            public async Task PostsToCorrectUrl()
+            {
+                var connection = Substitute.For<IApiConnection>();
+                var client = new RepositoryPagesClient(connection);
+
+                await client.RequestPageBuild("fake", "repo");
+
+                connection.Received().Post<PagesBuild>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/pages/builds"), "application/vnd.github.mister-fantastic-preview+json");
+            }
+
+            [Fact]
+            public async Task PostsToCorrectUrlWithRepositoryId()
+            {
+                var connection = Substitute.For<IApiConnection>();
+                var client = new RepositoryPagesClient(connection);
+
+                await client.RequestPageBuild(1);
+
+                connection.Received().Post<PagesBuild>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/pages/builds"), "application/vnd.github.mister-fantastic-preview+json");
+            }
+
+            [Fact]
+            public async Task EnsuresNonNullArguments()
+            {
+                var connection = Substitute.For<IApiConnection>();
+                var client = new RepositoryPagesClient(connection);
+
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.RequestPageBuild(null, "name"));
+                await Assert.ThrowsAsync<ArgumentNullException>(() => client.RequestPageBuild("owner", null));
+
+                await Assert.ThrowsAsync<ArgumentException>(() => client.RequestPageBuild("", "name"));
+                await Assert.ThrowsAsync<ArgumentException>(() => client.RequestPageBuild("owner", ""));
             }
         }
     }


Add accessors to allow serializing rot and position targets

--- OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -79,14 +79,14 @@
         object_rez = 4194304
     }

-    struct scriptPosTarget
+    public struct scriptPosTarget
     {
         public Vector3 targetPos;
         public float tolerance;
         public uint handle;
     }

-    struct scriptRotTarget
+    public struct scriptRotTarget
     {
         public Quaternion targetRot;
         public float tolerance;
@@ -322,6 +322,16 @@

         private SortedDictionary<uint, scriptPosTarget> m_targets = new SortedDictionary<uint, scriptPosTarget>();
         private SortedDictionary<uint, scriptRotTarget> m_rotTargets = new SortedDictionary<uint, scriptRotTarget>();
+
+        public SortedDictionary<uint, scriptPosTarget> AtTargets
+        {
+            get { return m_targets; }
+        }
+
+        public SortedDictionary<uint, scriptRotTarget> RotTargets
+        {
+            get { return m_rotTargets; }
+        }

         private bool m_scriptListens_atTarget;
         private bool m_scriptListens_notAtTarget;


Fixed a log class

Fixed a log class

--- ClickOnceToSquirrelMigrator/RemoveStartMenuEntry.cs
+++ ClickOnceToSquirrelMigrator/RemoveStartMenuEntry.cs
@@ -48,7 +48,7 @@

                 catch (IOException ex)
                 {
-                    this.Log().Warn("Failed to remove folder " + folder, ex);
+                    this.Log().WarnException("Failed to remove folder " + folder, ex);
                 }
             }
         }


Ripristinato costruttore

Ripristinato costruttore

--- src/backend/SO115App.GeneratoreFakeRichieste/GeneratoreRichieste.cs
+++ src/backend/SO115App.GeneratoreFakeRichieste/GeneratoreRichieste.cs
@@ -17,6 +17,9 @@
 // along with this program.  If not, see http://www.gnu.org/licenses/.
 // </copyright>
 //-----------------------------------------------------------------------
+using System;
+using System.Collections.Generic;
+using System.Linq;
 using Bogus;
 using SO115App.API.Models.Classi.Autenticazione;
 using SO115App.API.Models.Classi.Condivise;
@@ -26,9 +29,6 @@

 //using MongoDB.Driver;
 using SO115App.GeneratoreRichiesteFake.AzioniSuRichiesta;
-using System;
-using System.Collections.Generic;
-using System.Linq;

 namespace SO115App.GeneratoreRichiesteFake
 {
@@ -84,7 +84,7 @@
         /// <summary>
         ///   Il numero di mezzi considerati disponibili nel parco mezzi
         /// </summary>
-        private readonly int numeroMezzi;
+        private readonly int numeroMezziDisponibili;

         /// <summary>
         ///   Pesi del numero di mezzi partecipanti ad un intervento (per es. se i pesi sono[0.75,
@@ -133,35 +133,29 @@
         ///   0.20, 0.05] significa che al 75% un intervento ha un solo mezzo, al 20% ne ha due, al
         ///   5% ne ha tre).
         /// </param>
-        public GeneratoreRichieste
-        (
-            /*             string codiceUnitaOperativa,
-                        int numeroMezziDisponibili,
-                        DateTime dataMin,
-                        DateTime dataMax,
-                        int richiesteMedieAlGiorno,
-                        int mediaSecondiPartenzaDallaSedeSuccessive,
-                        int mediaSecondiArrivoSulPosto,
-                        int mediaSecondiDurataIntervento,
-                        int mediaSecondiRientroInSede,
-                        float[] pesiNumeroMezziPartecipanti */
-            )
-        {
-            this.codiceUnitaOperativa = "RM";
-            this.numeroMezzi = 4;
-            this.dataMin = DateTime.Now.AddHours(-12);
-            this.dataMax = DateTime.Now;
-            this.richiesteMedieAlGiorno = 50;
-            this.mediaSecondiPartenzaDallaSedeSuccessive = 30 * 60;
-            this.mediaSecondiArrivoSulPosto = 15 * 60;
-            this.mediaSecondiDurataIntervento = 30 * 60;
-            this.mediaSecondiRientroInSede = 15 * 60;
-            this.pesiNumeroMezziPartecipanti = new float[] { .85F, .7F, .4F, .3F, .1F };
-
-            ListaRichieste = Genera();
-        }
-
-        public IEnumerable<RichiestaAssistenza> ListaRichieste { get; private set; }
+        public GeneratoreRichieste(
+            string codiceUnitaOperativa,
+            int numeroMezziDisponibili,
+            DateTime dataMin,
+            DateTime dataMax,
+            int richiesteMedieAlGiorno,
+            int mediaSecondiPartenzaDallaSedeSuccessive,
+            int mediaSecondiArrivoSulPosto,
+            int mediaSecondiDurataIntervento,
+            int mediaSecondiRientroInSede,
+            float[] pesiNumeroMezziPartecipanti)
+        {
+            this.codiceUnitaOperativa = codiceUnitaOperativa;
+            this.numeroMezziDisponibili = numeroMezziDisponibili;
+            this.dataMin = dataMin;
+            this.dataMax = dataMax;
+            this.richiesteMedieAlGiorno = richiesteMedieAlGiorno;
+            this.mediaSecondiPartenzaDallaSedeSuccessive = mediaSecondiPartenzaDallaSedeSuccessive;
+            this.mediaSecondiArrivoSulPosto = mediaSecondiArrivoSulPosto;
+            this.mediaSecondiDurataIntervento = mediaSecondiDurataIntervento;
+            this.mediaSecondiRientroInSede = mediaSecondiRientroInSede;
+            this.pesiNumeroMezziPartecipanti = pesiNumeroMezziPartecipanti;
+        }

         /// <summary>
         ///   Genera le richieste secondo i parametri specificati nel costruttore della classe.
@@ -241,7 +235,7 @@
                     .Generate();
             }

-            var parcoMezzi = new ParcoMezzi(this.numeroMezzi, this.codiceUnitaOperativa);
+            var parcoMezzi = new ParcoMezzi(this.numeroMezziDisponibili, this.codiceUnitaOperativa);
             var azioni = richiesteConParametri
                 .SelectMany(r => this.GetAzioni(r, parcoMezzi))
                 .Where(a => a.IstantePrevisto <= this.dataMax)


send a full update on GroupResize, not a terse

--- OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -3930,7 +3930,7 @@

                 HasGroupChanged = true;
                 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
-                ScheduleGroupForTerseUpdate();
+                ScheduleGroupForFullUpdate();
             }
         }


Revert "Whitespace change to trigger ircbot"

This reverts commit ca30559b05bd44995277c270ec19a92d8170e587.

--- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
+++ OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
@@ -24,7 +24,6 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-
 using System;
 using System.Collections.Generic;
 using System.Reflection;


Preview update

Preview update

--- src/Certify.UI.Shared/Controls/ManagedCertificate/Preview.xaml.cs
+++ src/Certify.UI.Shared/Controls/ManagedCertificate/Preview.xaml.cs
@@ -60,7 +60,12 @@

                 try
                 {
+                    // save and restore changed flag as validation may autoconfigure defaults.
+                    var isChangedBeforePreview = ItemViewModel.SelectedItem.IsChanged;
+
                     var validationResult = ItemViewModel.Validate(applyAutoConfiguration: true);
+
+                    ItemViewModel.SelectedItem.IsChanged = isChangedBeforePreview;

                     if (!validationResult.IsValid)
                     {


Fix airlock hacking. (#6177)

Fix airlock hacking. (#6177)

--- Content.Server/Doors/Components/AirlockComponent.cs
+++ Content.Server/Doors/Components/AirlockComponent.cs
@@ -144,7 +144,7 @@

         public void UpdateWiresStatus()
         {
-            if (_entityManager.TryGetComponent<WiresComponent>(Owner, out var wiresComponent)) return;
+            if (!_entityManager.TryGetComponent<WiresComponent>(Owner, out var wiresComponent)) return;

             var mainPowerCut = wiresComponent.IsWireCut(Wires.MainPower);
             var backupPowerCut = wiresComponent.IsWireCut(Wires.BackupPower);


Prevent recursion in primitive types

Prevent recursion in primitive types

Primitive valuetypes are allowed to have recursion in their fields (e.g.
Char type can have a field of the same type). We need to check for that.

--- src/Common/src/TypeSystem/IL/Stubs/PInvokeMarshallingILEmitter.cs
+++ src/Common/src/TypeSystem/IL/Stubs/PInvokeMarshallingILEmitter.cs
@@ -48,12 +48,12 @@
             // TODO: true if SetLastError is true

             TypeDesc returnType = method.Signature.ReturnType;
-            if (!IsSimpleType(returnType) && !returnType.IsVoid)
+            if (!IsBlittableType(returnType) && !returnType.IsVoid)
                 return true;

             for (int i = 0; i < method.Signature.Length; i++)
             {
-                if (!IsSimpleType(method.Signature[i]))
+                if (!IsBlittableType(method.Signature[i]))
                 {
                     return true;
                 }
@@ -63,56 +63,40 @@
         }

         /// <summary>
-        /// Returns true if <paramref name="type"/> doesn't require marshalling and can be directly passed
-        /// to native code.
+        /// Returns true if this is a type that doesn't require marshalling.
         /// </summary>
-        private static bool IsSimpleType(TypeDesc type)
+        private static bool IsBlittableType(TypeDesc type)
         {
             type = type.UnderlyingType;

-            switch (type.Category)
-            {
-                case TypeFlags.Byte:
-                case TypeFlags.SByte:
-                case TypeFlags.UInt16:
-                case TypeFlags.Int16:
-                case TypeFlags.UInt32:
-                case TypeFlags.Int32:
-                case TypeFlags.UInt64:
-                case TypeFlags.Int64:
-                case TypeFlags.Double:
-                case TypeFlags.Single:
-                case TypeFlags.UIntPtr:
-                case TypeFlags.IntPtr:
+            if (type.IsValueType)
+            {
+                if (type.IsPrimitive)
+                {
+                    // All primitive types except char and bool are blittable
+                    TypeFlags category = type.Category;
+                    if (category == TypeFlags.Boolean || category == TypeFlags.Char)
+                        return false;
+
                     return true;
+                }
+
+                foreach (FieldDesc field in type.GetFields())
+                {
+                    if (field.IsStatic)
+                        continue;
+
+                    TypeDesc fieldType = field.FieldType;
+
+                    // TODO: we should also reject fields that specify custom marshalling
+                    if (!IsBlittableType(fieldType))
+                        return false;
+                }
+                return true;
             }

             if (type.IsPointer)
                 return true;
-
-            return false;
-        }
-
-        /// <summary>
-        /// Returns true if struct doesn't have fields that require marshalling.
-        /// </summary>
-        private static bool IsBlittableStruct(TypeDesc type)
-        {
-            if (type.IsValueType)
-            {
-                foreach (FieldDesc field in type.GetFields())
-                {
-                    if (field.IsStatic)
-                        continue;
-
-                    TypeDesc fieldType = field.FieldType;
-
-                    // TODO: we should also reject fields that specify custom marshalling
-                    if (!IsSimpleType(fieldType) && !IsBlittableStruct(fieldType))
-                        return false;
-                }
-                return true;
-            }

             return false;
         }
@@ -127,7 +111,7 @@
         {
             Debug.Assert(arrayType.IsSzArray);

-            if (!IsSimpleType(arrayType.ParameterType) && !IsBlittableStruct(arrayType.ParameterType))
+            if (!IsBlittableType(arrayType.ParameterType))
                 throw new NotSupportedException();

             ILLocalVariable vPinnedFirstElement = _emitter.NewLocal(arrayType.ParameterType.MakeByRefType(), true);
@@ -163,7 +147,7 @@
         /// <returns>Type the ByRef was marshalled into.</returns>
         private TypeDesc EmitByRefMarshalling(ByRefType byRefType)
         {
-            if (!IsSimpleType(byRefType.ParameterType) && !IsBlittableStruct(byRefType.ParameterType))
+            if (!IsBlittableType(byRefType.ParameterType))
                 throw new NotSupportedException();

             ILLocalVariable vPinnedByRef = _emitter.NewLocal(byRefType, true);
@@ -315,7 +299,7 @@
             // TODO: throw if SetLastError is true
             // TODO: throw if there's custom marshalling
             TypeDesc nativeReturnType = _targetMethod.Signature.ReturnType;
-            if (!IsSimpleType(nativeReturnType) && !nativeReturnType.IsVoid)
+            if (!IsBlittableType(nativeReturnType) && !nativeReturnType.IsVoid)
                 throw new NotSupportedException();

             TypeDesc[] nativeParameterTypes = new TypeDesc[_targetMethod.Signature.Length];
@@ -346,10 +330,10 @@
                 }
                 else
                 {
-                    if (!IsSimpleType(parameterType))
+                    if (!IsBlittableType(parameterType))
                         throw new NotSupportedException();

-                    nativeType = parameterType;
+                    nativeType = parameterType.UnderlyingType;
                 }

                 nativeParameterTypes[i] = nativeType;


Small comment clarification

Small comment clarification

I have a tool suggesting to make this field readonly.
I pressume the tool sees that it is only used in the constructor.
However it fails to recognize that the field is static and is being used
in not static constructors.

--- Core/System/Threading/ReaderWriterLockSlim.net35.cs
+++ Core/System/Threading/ReaderWriterLockSlim.net35.cs
@@ -27,6 +27,7 @@
         // This Stopwatch instance is used for all threads since .Elapsed is thread-safe
         private static readonly Stopwatch _stopwatch;

+        // Incremented when a new object is created, should not be readonly
         private static int _idPool;

         private readonly LockRecursionPolicy _recursionPolicy;


BucketHelper will now take IBucket

BucketHelper will now take IBucket

--- Core/Theraot/Collections/ThreadSafe/BucketHelper.cs
+++ Core/Theraot/Collections/ThreadSafe/BucketHelper.cs
@@ -38,7 +38,7 @@
         /// <remarks>
         /// The operation will be attempted as long as check returns true - this operation may starve.
         /// </remarks>
-        public static bool InsertOrUpdate<T>(this Bucket<T> bucket, int index, T item, Func<T, T> itemUpdateFactory, Predicate<T> check, out T stored, out bool isNew)
+        public static bool InsertOrUpdate<T>(this IBucket<T> bucket, int index, T item, Func<T, T> itemUpdateFactory, Predicate<T> check, out T stored, out bool isNew)
         {
             if (index < 0 || index >= bucket.Capacity)
             {
@@ -51,7 +51,7 @@
                 if (isNew)
                 {
                     var result = item;
-                    if (bucket.InsertInternal(index, result, out stored))
+                    if (bucket.Insert(index, result, out stored))
                     {
                         return true;
                     }
@@ -62,7 +62,7 @@
                     if (check(stored))
                     {
                         var result = itemUpdateFactory.Invoke(stored);
-                        if (bucket.UpdateInternal(index, result, stored, out stored, out isNew))
+                        if (bucket.Update(index, result, stored, out stored, out isNew))
                         {
                             stored = result;
                             return true;
@@ -93,7 +93,7 @@
         /// <remarks>
         /// The operation will be attempted as long as check returns true - this operation may starve.
         /// </remarks>
-        public static bool InsertOrUpdate<T>(this Bucket<T> bucket, int index, Func<T> itemFactory, Func<T, T> itemUpdateFactory, Predicate<T> check, out T stored, out bool isNew)
+        public static bool InsertOrUpdate<T>(this IBucket<T> bucket, int index, Func<T> itemFactory, Func<T, T> itemUpdateFactory, Predicate<T> check, out T stored, out bool isNew)
         {
             if (index < 0 || index >= bucket.Capacity)
             {
@@ -107,7 +107,7 @@
                 {
                     var result = itemFactory.Invoke();
                     itemFactory = () => result;
-                    if (bucket.InsertInternal(index, result, out stored))
+                    if (bucket.Insert(index, result, out stored))
                     {
                         return true;
                     }
@@ -118,7 +118,7 @@
                     if (check(stored))
                     {
                         var result = itemUpdateFactory.Invoke(stored);
-                        if (bucket.UpdateInternal(index, result, stored, out stored, out isNew))
+                        if (bucket.Update(index, result, stored, out stored, out isNew))
                         {
                             stored = result;
                             return true;
@@ -149,14 +149,14 @@
         /// The insertion can fail if the index is already used or is being written by another thread.
         /// If the index is being written it can be understood that the insert operation happened before but the item was overwritten or removed.
         /// </remarks>
-        public static bool Update<T>(this Bucket<T> bucket, int index, T item, Predicate<T> check, out T previous, out bool isNew)
+        public static bool Update<T>(this IBucket<T> bucket, int index, T item, Predicate<T> check, out T previous, out bool isNew)
         {
             if (index < 0 || index >= bucket.Capacity)
             {
                 throw new ArgumentOutOfRangeException("index", "index must be greater or equal to 0 and less than capacity.");
             }
             isNew = false;
-            if (!bucket.TryGetInternal(index, out previous))
+            if (!bucket.TryGet(index, out previous))
             {
                 // There was not an item
                 return false;
@@ -170,7 +170,7 @@
                     return false;
                 }
                 // The item passes the check
-                if (bucket.UpdateInternal(index, item, previous, out previous, out isNew))
+                if (bucket.Update(index, item, previous, out previous, out isNew))
                 {
                     // The item was replaced
                     return true;


AddonWindowBase: simplified ToggleWithButton logic

--- GUI/WindowsFramework/AddonWindowBase.cs
+++ GUI/WindowsFramework/AddonWindowBase.cs
@@ -49,8 +49,8 @@

         public static void ToggleWithButton(ApplicationLauncherButton button)
         {
-            if(button == null) ToggleInstance();
-            else if(Instance) ShowWithButton(!Instance.window_enabled, button);
+            if(Instance != null)
+                ShowWithButton(!Instance.window_enabled, button);
         }

         readonly ActionDamper save_timer = new ActionDamper(10);


chore: Refactor the proto testing

chore: Refactor the proto testing

- Separate protoc options into a collection for simplicity
- Remove now-unnecessary option for protoc about "optional"
- Refactor tests to move knowledge of Showcase to its own test method

--- Google.Api.Generator.Tests/ProtoTest.cs
+++ Google.Api.Generator.Tests/ProtoTest.cs
@@ -33,9 +33,17 @@
             var protoPaths = protoFilenames.Select(x => Path.Combine(Invoker.GeneratorTestsDir, x));
             using (var desc = Invoker.TempFile())
             {
-                var args = $"-o {desc} --experimental_allow_proto3_optional --include_imports --include_source_info " +
-                           $"-I{Invoker.CommonProtosDir} -I{Invoker.ProtobufDir} -I{Invoker.GeneratorTestsDir} {string.Join(" ", protoPaths)}";
-                Invoker.Protoc(args);
+                var args = new[]
+                {
+                    "-o", desc.Path,
+                    "--include_imports",
+                    "--include_source_info",
+                    $"-I{Invoker.CommonProtosDir}",
+                    $"-I{Invoker.ProtobufDir}",
+                    $"-I{Invoker.GeneratorTestsDir}",
+                }.Concat(protoPaths);
+                Invoker.Protoc(string.Join(" ", args));
+
                 var descriptorBytes = File.ReadAllBytes(desc.Path);
                 FileDescriptorSet descriptorSet = FileDescriptorSet.Parser.ParseFrom(descriptorBytes);
                 return CodeGenerator.Generate(descriptorSet, package, clock, grpcServiceConfigPath, serviceConfigPath, commonResourcesConfigPaths);
@@ -55,6 +63,10 @@
             string grpcServiceConfigPath = null, string serviceConfigPath = null, IEnumerable<string> commonResourcesConfigPaths = null, bool ignoreMetadataFile = true) =>
             ProtoTestSingle(
                 new[] { testProtoName },
+                // The following three don't need to be customized for simple cases
+                sourceDir: null,
+                outputDir: null,
+                package: null,
                 ignoreCsProj,
                 ignoreSnippets,
                 ignoreUnitTests,
@@ -64,23 +76,17 @@
                 ignoreMetadataFile
             );

-        private void ProtoTestSingle(IEnumerable<string> testProtoNames,
+        private void ProtoTestSingle(IEnumerable<string> testProtoNames, string sourceDir = null, string outputDir = null, string package = null,
             bool ignoreCsProj = false, bool ignoreSnippets = false, bool ignoreUnitTests = false,
             string grpcServiceConfigPath = null, string serviceConfigPath = null, IEnumerable<string> commonResourcesConfigPaths = null, bool ignoreMetadataFile = true)
         {
             // Confirm each generated file is identical to the expected output.
             // Use `// TEST_START` and `// TEST_END` lines in the expected file to test subsets of output files.
             // Or include `// TEST_DISABLE` to disable testing of the entire file.
-            var dirName = testProtoNames.First();
-            var protoPaths = testProtoNames.Select(x => Path.Combine("ProtoTests", dirName, $"{x}.proto"));
-
-            var package = $"testing.{dirName.ToLowerInvariant()}";
-            if (testProtoNames.Count() == 1 && testProtoNames.Single() == "Showcase")
-            {
-                protoPaths = new[] {"compliance.proto", "echo.proto", "identity.proto", "messaging.proto", "sequence.proto", "testing.proto"}
-                    .Select(f => Path.Combine("ProtoTests", "Showcase", "google", "showcase", "v1beta1", $"{f}"));
-                package = "google.showcase.v1beta1";
-            }
+            sourceDir = sourceDir ?? testProtoNames.First();
+            outputDir = outputDir ?? sourceDir;
+            var protoPaths = testProtoNames.Select(x => Path.Combine("ProtoTests", sourceDir, $"{x}.proto"));
+            package = package ?? $"testing.{sourceDir.ToLowerInvariant()}";

             var files = Run(protoPaths, package,
                 grpcServiceConfigPath, serviceConfigPath, commonResourcesConfigPaths);
@@ -91,7 +97,7 @@
             // This makes it easier to see the complete set of outputs.
             foreach (var file in files)
             {
-                var pathToWriteTo = Path.Combine(Invoker.ActualGeneratedFilesDir, dirName, file.RelativePath);
+                var pathToWriteTo = Path.Combine(Invoker.ActualGeneratedFilesDir, outputDir, file.RelativePath);
                 Directory.CreateDirectory(Path.GetDirectoryName(pathToWriteTo));
                 File.WriteAllText(pathToWriteTo, file.Content);
             }
@@ -107,7 +113,7 @@
                 {
                     continue;
                 }
-                var expectedFilePath = Path.Combine(Invoker.GeneratorTestsDir, "ProtoTests", dirName, file.RelativePath);
+                var expectedFilePath = Path.Combine(Invoker.GeneratorTestsDir, "ProtoTests", outputDir, file.RelativePath);
                 TextComparer.CompareText(expectedFilePath, file);
             }
         }
@@ -135,7 +141,6 @@
             {
                 Assert.True(Directory.Exists(path), $"Test directory doesn't exist: '{path}'");
                 // TODO: Use Roslyn directly, rather than invoking `dotnet`.
-                var errors = new List<string>();
                 try
                 {
                     Invoker.Dotnet("build", path);
@@ -248,7 +253,11 @@
             serviceConfigPath: Path.Combine(Invoker.GeneratorTestsDir, "ProtoTests", "Mixins", "Mixins.yaml"));

         [Fact]
-        public void Showcase() => ProtoTestSingle("Showcase", ignoreUnitTests: true, ignoreSnippets: true);
+        public void Showcase() => ProtoTestSingle(testProtoNames: new[] { "compliance", "echo", "identity", "messaging", "sequence", "testing" },
+            sourceDir: "Showcase/google/showcase/v1beta1",
+            outputDir: "Showcase",
+            package: "google.showcase.v1beta1",
+            ignoreUnitTests: true, ignoreSnippets: true);

         // Build tests are testing `csproj` file generation only.
         // All other generated code is effectively "build tested" when this test project is built.


Default the messages to String.Empty, not null.

svn path=/trunk/bitsharp/; revision=76041

--- src/MonoTorrent.Client/Tracker.cs
+++ src/MonoTorrent.Client/Tracker.cs
@@ -208,6 +208,8 @@
             this.scrapeCallback = scrapeCallback;
             int indexOfAnnounce = announceUrl.LastIndexOf('/') + 1;
             this.engineSettings = engineSettings;
+            this.warningMessage = string.Empty;
+            this.failureMessage = string.Empty;

             if ((indexOfAnnounce + 8) <= announceUrl.Length && announceUrl.Substring(indexOfAnnounce, 8) == "announce")
             {


Fix code inspection warnings

Fix code inspection warnings

--- R7.University/components/Utils.cs
+++ R7.University/components/Utils.cs
@@ -27,7 +27,7 @@
 		Error = DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError
 	}

-	public class Utils
+	public static class Utils
 	{
 		public static string GetUserDisplayName (int userId)
 		{
@@ -48,8 +48,8 @@
 			if (!string.IsNullOrWhiteSpace (fileName))
 				return Globals.glbImageFileTypes.Contains (
 					Path.GetExtension (fileName).Substring (1).ToLowerInvariant ());
-			else
-				return false;
+
+			return false;
 		}

 		/// <summary>
@@ -61,7 +61,7 @@
 		/// <param name="trackClicks">If set to <c>true</c> then track clicks.</param>
 		public static string FormatURL (IModuleControl module, string link, bool trackClicks)
 		{
-			return DotNetNuke.Common.Globals.LinkClick
+			return Globals.LinkClick
 				(link, module.ModuleContext.TabId, module.ModuleContext.ModuleId, trackClicks);
 		}

@@ -145,7 +145,7 @@
 				(DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType)messageType);
 		}

-		public static bool IsNull<T> (Nullable<T> n) where T: struct
+		public static bool IsNull<T> (T? n) where T: struct
 		{
 			// NOTE: n.HasValue is equvalent to n != null
 			if (n.HasValue && !Null.IsNull (n.Value))
@@ -154,9 +154,9 @@
 			return true;
 		}

-		public static Nullable<T> ToNullable<T>(T n) where T: struct
-		{
-			return Null.IsNull (n)? null : (Nullable<T>) n;
+		public static T? ToNullable<T>(T n) where T: struct
+		{
+			return Null.IsNull (n)? null : (T?) n;
 		}

 		/// <summary>
@@ -173,8 +173,8 @@

 			if (int.TryParse (value, out n))
 				return Null.IsNull (n)? null : (int?) n;
-			else
-				return null;
+
+			return null;
 		}

 		/*
@@ -220,8 +220,8 @@
 					return s.ToUpper();
 				else
 					return s.ToUpper()[0].ToString () + s.Substring (1);
-			else
-				return s;
+
+			return s;
 		}

 		public static string FirstCharToUpperInvariant(string s)
@@ -231,8 +231,7 @@
 					return s.ToUpperInvariant();
 				else
 					return s.ToUpperInvariant()[0].ToString () + s.Substring (1);
-			else
-				return s;
+			return s;
 		}

 		public static void SynchronizeModule(IModuleControl module)


Correct class name. Was Mapping

Correct class name. Was Mapping

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@29

--- src/NHibernate/Engine/IMapping.cs
+++ src/NHibernate/Engine/IMapping.cs
@@ -6,7 +6,7 @@
 	/// Defines operations common to "compiled" mappings (ie. <c>SessionFactory</c>) and
 	/// "uncompiled" mappings (ie <c>Configuration</c> that are used by implementors of <c>IType</c>
 	/// </summary>
-	public interface Mapping {
+	public interface IMapping {
 		IType GetIdentifierType(System.Type persistentType);
 	}
 }


xmldoc

xmldoc

--- src/NLog/Targets/ConsoleTarget.cs
+++ src/NLog/Targets/ConsoleTarget.cs
@@ -114,15 +114,19 @@
             this.Output(this.Layout.Render(logEvent));
         }

-        private void Output(string s)
+        /// <summary>
+        /// Write to output
+        /// </summary>
+        /// <param name="textLine">text to be written.</param>
+        private void Output(string textLine)
         {
             if (this.Error)
             {
-                Console.Error.WriteLine(s);
+                Console.Error.WriteLine(textLine);
             }
             else
             {
-                Console.Out.WriteLine(s);
+                Console.Out.WriteLine(textLine);
             }
         }
     }


Remove description

Remove description

--- src/NSwag.Core/SwaggerDocument.cs
+++ src/NSwag.Core/SwaggerDocument.cs
@@ -41,8 +41,7 @@
             Paths = paths;
             Info = new SwaggerInfo
             {
-                Title = string.Empty,
-                Description = string.Empty
+                Title = string.Empty
             };
         }


Make a convenience mixin to do everything

--- src/NSync.Client/UpdateManager.cs
+++ src/NSync.Client/UpdateManager.cs
@@ -445,6 +445,31 @@
         }
     }

+    public static class UpdateManagerMixins
+    {
+        public static IObservable<Unit> UpdateApp(this IUpdateManager This)
+        {
+            IDisposable theLock;
+
+            try {
+                theLock = This.AcquireUpdateLock();
+            } catch (TimeoutException _) {
+                return Observable.Return(Unit.Default);
+            } catch (Exception ex) {
+                return Observable.Throw<Unit>(ex);
+            }
+
+            var ret = This.CheckForUpdate()
+                .SelectMany(x => This.DownloadReleases(x.ReleasesToApply).Select(_ => x))
+                .SelectMany(x => This.ApplyReleases(x))
+                .Finally(() => theLock.Dispose())
+                .Multicast(new AsyncSubject<Unit>());
+
+            ret.Connect();
+            return ret;
+        }
+    }
+
     public class UpdateInfo
     {
         public Version Version { get; protected set; }


Appease FxCop

Appease FxCop

--- src/NuGetGallery/UrlExtensions.cs
+++ src/NuGetGallery/UrlExtensions.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Globalization;
 using System.Web;
 using System.Web.Mvc;
 using System.Web.Routing;
@@ -142,7 +143,7 @@

             urlResult = EnsureTrailingSlash(urlResult);

-            return string.Format(PackageExplorerDeepLink, urlResult, id, version);
+            return String.Format(CultureInfo.InvariantCulture, PackageExplorerDeepLink, urlResult, id, version);
         }

         public static string LogOn(this UrlHelper url)


fix slight formatting issue

fix slight formatting issue

--- src/DotNet.Globals.Core/PackageResolvers/FolderPackageResolver.cs
+++ src/DotNet.Globals.Core/PackageResolvers/FolderPackageResolver.cs
@@ -7,7 +7,6 @@
 {
     internal class FolderPackageResolver : PackageResolver
     {
-
         public FolderPackageResolver(DirectoryInfo packagesFolder, string source, Options options) : base(packagesFolder, source, options) { }

         protected override void Acquire()


Enable redirect url & cc emails params in Api Call

* Enable setting signing_redirect_url(string) in Api call
* Enable setting cc_email_addresses(array of string) in Api call

--- HelloSignNet.Core/HelloSignApiClient.cs
+++ HelloSignNet.Core/HelloSignApiClient.cs
@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Globalization;
 using System.IO;
+using System.Linq;
 using System.Net.Http;
 using System.Net.Http.Headers;
 using System.Threading.Tasks;
@@ -148,8 +149,10 @@
                 formData.AddStringContent("subject", request.Subject);
             if (!string.IsNullOrEmpty(request.Message))
                 formData.AddStringContent("message", request.Message);
-
-            for (int i = 0; i < request.Signers.Count; i++)
+            if (!string.IsNullOrEmpty(request.SigningRedirectUrl))
+                formData.AddStringContent("signing_redirect_url", request.SigningRedirectUrl);
+
+            for (var i = 0; i < request.Signers.Count; i++)
             {
                 formData.AddStringContent(string.Format("signers[{0}][name]", i), request.Signers[i].Name);
                 formData.AddStringContent(string.Format("signers[{0}][email_address]", i),
@@ -160,6 +163,11 @@
                     formData.AddStringContent(string.Format("signers[{0}][pin]", i), request.Signers[i].Pin);
             }

+            for (var i = 0; request.CcEmailAddresses != null && i < request.CcEmailAddresses.Count; i++)
+            {
+                formData.AddStringContent(string.Format("cc_email_addresses[{0}]", i), request.Signers[i].Name);
+            }
+
             for (var i = 0; request.Files != null && i < request.Files.Count; i++)
             {
                 formData.AddFileStreamContent(i, request.Files[i].FullName, request.Files[i].Name);


add test to DbAdapter ExistsColumn

add test to DbAdapter ExistsColumn

--- DataTableWriter.UnitTests/Adapters/DbAdapterTest.cs
+++ DataTableWriter.UnitTests/Adapters/DbAdapterTest.cs
@@ -369,6 +369,49 @@
         }

         [TestClass]
+        public class MethodExistsColumn
+        {
+            [TestMethod]
+            public void ShouldReturnTrueWhenColumnExists()
+            {
+                var tableName = "TABLE";
+                var table = new DataTable(tableName);
+                table.Columns.Add("col1", typeof(string));
+                table.Columns.Add("col2", typeof(string));
+                table.Columns.Add("col3", typeof(string));
+                var driver = Substitute.For<IDbDriver>();
+                var connectionInfo = Substitute.For<IDbConnectionInfo>();
+                var connection = Substitute.For<IDbConnection>();
+                driver.BuildConnection(connectionInfo).Returns(connection);
+
+                var adapter = new DbAdapter(driver, connectionInfo);
+                Isolate.WhenCalled(() => adapter.GetSchema(null)).WillReturn(table);
+                var col = new DataColumn("col1");
+                Assert.IsTrue(adapter.ExistsColumn(tableName, col));
+            }
+
+            [TestMethod]
+            public void ShouldReturnFalseWhenColumnDoesNotExist()
+            {
+                var tableName = "TABLE";
+                var table = new DataTable(tableName);
+                table.Columns.Add("col1", typeof(string));
+                table.Columns.Add("col2", typeof(string));
+                table.Columns.Add("col3", typeof(string));
+                var driver = Substitute.For<IDbDriver>();
+                var connectionInfo = Substitute.For<IDbConnectionInfo>();
+                var connection = Substitute.For<IDbConnection>();
+                driver.BuildConnection(connectionInfo).Returns(connection);
+
+                var adapter = new DbAdapter(driver, connectionInfo);
+                Isolate.WhenCalled(() => adapter.GetSchema(null)).WillReturn(table);
+                var col = new DataColumn("col1");
+                Assert.IsFalse(adapter.ExistsColumn(tableName, col));
+            }
+        }
+
+
+        [TestClass]
         public class MethodIsConnectionOpen
         {


catch exceptions

catch exceptions

--- EADatabaseTransformer/EADatabaseTransformerAddin.cs
+++ EADatabaseTransformer/EADatabaseTransformerAddin.cs
@@ -198,25 +198,33 @@
         /// <param name="ItemName">the name of the selected menu item</param>
         public override void EA_MenuClick(EA.Repository Repository, string Location, string MenuName, string ItemName)
         {
-            switch (ItemName)
-            {
-                case menuComparetoDatabase:
-                	this.compareDatabase();
-                	if (debugMode)
-                		new debugForm(_dbCompareControl).Show();
-                	else
-                		Repository.ActivateTab(compareControlName);
-                    break;
-                   case menuCompleteDBwithDLL:
-                    this.completeDBwithDLL();
-                    break;
-		        case menuAbout :
-		            new AboutWindow().ShowDialog();
-		            break;
-	            case menuSettings:
-	                new EADatabaseTransformerSettingsForm(this.settings).ShowDialog();
-	                break;
-            }
+        	try
+        	{
+	            switch (ItemName)
+	            {
+	                case menuComparetoDatabase:
+	                	this.compareDatabase();
+	                	if (debugMode)
+	                		new debugForm(_dbCompareControl).Show();
+	                	else
+	                		Repository.ActivateTab(compareControlName);
+	                    break;
+	                   case menuCompleteDBwithDLL:
+	                    this.completeDBwithDLL();
+	                    break;
+			        case menuAbout :
+			            new AboutWindow().ShowDialog();
+			            break;
+		            case menuSettings:
+		                new EADatabaseTransformerSettingsForm(this.settings).ShowDialog();
+		                break;
+	            }
+        	}
+        	catch(Exception e)
+        	{
+        		//log exception to output window
+        		EAOutputLogger.log(string.Format("Exception occured: {0} \n Stacktrace: {1}",e.Message, e.StackTrace));
+        	}
         }

 		/// <summary>


Convert shopping list warning to material cap

--- EDDiscovery/UserControls/UserControlShoppingList.cs
+++ EDDiscovery/UserControls/UserControlShoppingList.cs
@@ -46,6 +46,7 @@
         private string DBUseEDSMForSystemAvailability { get { return "ShoppingListUseEDSM" + ((displaynumber > 0) ? displaynumber.ToString() : ""); } }
         const int PhysicalInventoryCapacity = 1000;
         const int DataInventoryCapacity = 500;
+        const int PerMaterialCap = 100;

         #region Init

@@ -163,6 +164,7 @@
                 {
                     double available;
                     wantedList.Append("Needed Mats:\n");
+                    List<string> capExceededMats = new List<string>();
                     foreach (MaterialCommodities c in shoppinglist.OrderBy(mat => mat.name))      // and add new..
                     {
                         string present = "";
@@ -179,6 +181,10 @@
                             }
                         }
                         wantedList.Append($"  {c.scratchpad} {c.name}{present}");
+                        if (c.scratchpad + mcl.Where(m => m.shortname == c.shortname).FirstOrDefault()?.count > PerMaterialCap)
+                        {
+                            capExceededMats.Add(c.name);
+                        }
                         if (!last_he.IsLanded && last_sn != null)
                         {
                             var landables = last_sn.Bodies.Where(b => b.ScanData != null && (!b.ScanData.IsEDSMBody || useEDSMForSystemAvailability) &&
@@ -205,26 +211,35 @@
                         wantedList.Append("\n");
                     }

-                    int currentMats = mcl.Where(m => m.category == MaterialCommodityDB.MaterialManufacturedCategory || m.category == MaterialCommodityDB.MaterialRawCategory)
-                                         .Sum(i => i.count);
-                    int currentData = mcl.Where(m => m.category == MaterialCommodityDB.MaterialEncodedCategory).Sum(i => i.count);
-                    int neededMats = shoppinglist.Where(m => m.category == MaterialCommodityDB.MaterialManufacturedCategory || m.category == MaterialCommodityDB.MaterialRawCategory)
-                                                 .Sum(i => i.scratchpad);
-                    int neededData = shoppinglist.Where(m => m.category == MaterialCommodityDB.MaterialEncodedCategory).Sum(i => i.scratchpad);
-
-                    if (currentMats + neededMats > PhysicalInventoryCapacity || currentData + neededData > DataInventoryCapacity)
+                    if(capExceededMats.Any())
                     {
-                        wantedList.Append("\nCapacity Warning:");
-                        if (currentMats + neededMats > PhysicalInventoryCapacity)
+                        wantedList.Append("\nFilling Shopping List would exceed capacity for:");
+                        foreach(string mat in capExceededMats)
                         {
-                            wantedList.Append($"\n  {PhysicalInventoryCapacity - currentMats}/{neededMats} materials space free");
+                            wantedList.Append($"\n  {mat}");
                         }
-                        if (currentData + neededData > DataInventoryCapacity)
-                        {
-                            wantedList.Append($"\n  {DataInventoryCapacity - currentData}/{neededData} data space free");
-                        }
-                        wantedList.Append("\n");
                     }
+
+                    //int currentMats = mcl.Where(m => m.category == MaterialCommodityDB.MaterialManufacturedCategory || m.category == MaterialCommodityDB.MaterialRawCategory)
+                    //                     .Sum(i => i.count);
+                    //int currentData = mcl.Where(m => m.category == MaterialCommodityDB.MaterialEncodedCategory).Sum(i => i.count);
+                    //int neededMats = shoppinglist.Where(m => m.category == MaterialCommodityDB.MaterialManufacturedCategory || m.category == MaterialCommodityDB.MaterialRawCategory)
+                    //                             .Sum(i => i.scratchpad);
+                    //int neededData = shoppinglist.Where(m => m.category == MaterialCommodityDB.MaterialEncodedCategory).Sum(i => i.scratchpad);
+
+                    //if (currentMats + neededMats > PhysicalInventoryCapacity || currentData + neededData > DataInventoryCapacity)
+                    //{
+                    //    wantedList.Append("\nCapacity Warning:");
+                    //    if (currentMats + neededMats > PhysicalInventoryCapacity)
+                    //    {
+                    //        wantedList.Append($"\n  {PhysicalInventoryCapacity - currentMats}/{neededMats} materials space free");
+                    //    }
+                    //    if (currentData + neededData > DataInventoryCapacity)
+                    //    {
+                    //        wantedList.Append($"\n  {DataInventoryCapacity - currentData}/{neededData} data space free");
+                    //    }
+                    //    wantedList.Append("\n");
+                    //}
                 }
                 else
                 {


Fixed Mac context creation in Release mode.

--- EmotionCore/src/Engine/Hosting/Desktop/OtkWindow.cs
+++ EmotionCore/src/Engine/Hosting/Desktop/OtkWindow.cs
@@ -80,6 +80,7 @@
                     _openGLMajorVersion = 3;
                     _openGLMinorVersion = 3;
                 }
+#endif

             // Mac doesn't create highest possible context when passing 1.0 :(
             if (CurrentPlatform.OS == PlatformName.Mac)
@@ -87,7 +88,6 @@
                 _openGLMajorVersion = 3;
                 _openGLMinorVersion = 3;
             }
-#endif
         }

         /// <summary>


Add AssemblyInformationalVersion to AssemblyInfo

--- Hudl.Mjolnir/Properties/AssemblyInfo.cs
+++ Hudl.Mjolnir/Properties/AssemblyInfo.cs
@@ -35,5 +35,6 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyInformationalVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
 [assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]


NativeMethodsShared.OSName: Fix the case of OSX

OSX is also a Unix, so check for the less generic kind first. So, change

    return IsUnix ? "Unix" : (IsOSX ? "OSX" : "Windows_NT")
to
    return IsOSX ? "OSX" : (IsUnix ? "Unix" : "Windows_NT")

--- src/Shared/NativeMethodsShared.cs
+++ src/Shared/NativeMethodsShared.cs
@@ -535,7 +535,7 @@
         {
             get
             {
-                return IsUnix ? "Unix" : (IsOSX ? "OSX" : "Windows_NT");
+                return IsOSX ? "OSX" : (IsUnix ? "Unix" : "Windows_NT");
             }
         }


fix deserialize node

fix deserialize node

--- src/Sir.Store/VectorOperations.cs
+++ src/Sir.Store/VectorOperations.cs
@@ -20,17 +20,17 @@
             (float identicalAngle, float foldAngle) similarity)
         {
             var buf = new byte[VectorNode.BlockSize];
-            int read = indexStream.Read(buf); // skip first node in file (it's a null node)
+            int read = indexStream.Read(buf);

             while (read == VectorNode.BlockSize)
             {
-                indexStream.Read(buf);
-
                 var terminator = new byte();
                 var node = DeserializeNode(buf, vectorStream, ref terminator);

                 if (node.VectorOffset > -1)
                     root.Add(node, similarity);
+
+                read = indexStream.Read(buf);
             }
         }


Fix vertical layout + linebreak

Fix vertical layout + linebreak

--- src/SixLabors.Fonts/TextLayout.cs
+++ src/SixLabors.Fonts/TextLayout.cs
@@ -408,24 +408,16 @@
             float scaledMaxDescender = textLine.ScaledMaxDescender();
             float scaledMaxLineHeight = textLine.ScaledMaxLineHeight();

-            TextLine.GlyphLayoutData first = textLine[0];
-            float firstMaxLineGap = first.ScaledLineGap;
-            float firstMaxAscender = first.ScaledAscender;
-            float firstMaxDescender = first.ScaledDescender;
-            float firstMaxLineHeight = first.ScaledLineHeight;
-
             switch (options.VerticalAlignment)
             {
                 case VerticalAlignment.Top:
-                    offsetY = firstMaxAscender + firstMaxLineGap;
+                    offsetY = 0;
                     break;
                 case VerticalAlignment.Center:
-                    offsetY = ((firstMaxAscender + firstMaxLineGap) * .5F) - (firstMaxDescender * .5F);
-                    offsetY -= (maxScaledAdvance - firstMaxLineHeight) * .5F;
+                    offsetY -= maxScaledAdvance * .5F;
                     break;
                 case VerticalAlignment.Bottom:
-                    offsetY = -firstMaxDescender;
-                    offsetY -= maxScaledAdvance - firstMaxLineHeight;
+                    offsetY -= maxScaledAdvance;
                     break;
             }

@@ -464,16 +456,15 @@
                 switch (options.HorizontalAlignment)
                 {
                     case HorizontalAlignment.Right:
-                        offsetX = -(scaledMaxLineHeight * options.LineSpacing);
-                        for (int i = textBox.TextLines.Count - 1; i > 0; i--)
+                        // The textline methods are memoized so we're safe to call them multiple times.
+                        for (int i = 0; i < textBox.TextLines.Count; i++)
                         {
                             offsetX -= textBox.TextLines[i].ScaledMaxLineHeight() * options.LineSpacing;
                         }

                         break;
                     case HorizontalAlignment.Center:
-                        offsetX = -(scaledMaxLineHeight * options.LineSpacing * .5F);
-                        for (int i = textBox.TextLines.Count - 1; i > 0; i--)
+                        for (int i = 0; i < textBox.TextLines.Count; i++)
                         {
                             offsetX -= textBox.TextLines[i].ScaledMaxLineHeight() * options.LineSpacing * .5F;
                         }
@@ -495,19 +486,19 @@

             for (int i = 0; i < textLine.Count; i++)
             {
-                TextLine.GlyphLayoutData info = textLine[i];
-                if (info.IsNewLine)
+                TextLine.GlyphLayoutData data = textLine[i];
+                if (data.IsNewLine)
                 {
                     location.X += xLineAdvance;
                     location.Y = originY;
                     continue;
                 }

-                foreach (GlyphMetrics metric in info.Metrics)
-                {
-                    Vector2 scale = new Vector2(info.PointSize) / metric.ScaleFactor;
+                foreach (GlyphMetrics metric in data.Metrics)
+                {
+                    Vector2 scale = new Vector2(data.PointSize) / metric.ScaleFactor;
                     float advanceX = xLineAdvance;
-                    float advanceY = info.ScaledAdvance;
+                    float advanceY = data.ScaledAdvance;

                     // Advance Width & Height can be 0 which is fine for layout but not for measuring.
                     if (advanceX == 0)
@@ -521,8 +512,8 @@
                     }

                     glyphs.Add(new GlyphLayout(
-                        new Glyph(metric, info.PointSize),
-                        location + new Vector2((xWidth - (metric.AdvanceWidth * scale.X)) * .5F, 0),
+                        new Glyph(metric, data.PointSize),
+                        location + new Vector2((xWidth - (metric.AdvanceWidth * scale.X)) * .5F, data.ScaledAscender),
                         scaledMaxAscender,
                         scaledMaxDescender,
                         scaledMaxLineGap,
@@ -532,7 +523,7 @@
                         i == 0));
                 }

-                location.Y += info.ScaledAdvance;
+                location.Y += data.ScaledAdvance;
             }

             location.Y = originY;
@@ -788,6 +779,17 @@
                                 glyphCount += textLine.Count;
                                 textLine = new();
                                 lineAdvance = 0;
+                            }
+                            else if (currentLineBreak.PositionWrap == codePointIndex)
+                            {
+                                // Split the current textline into two at the current wrapping point.
+                                TextLine split = textLine.SplitAt(currentLineBreak, keepAll);
+                                if (split != textLine)
+                                {
+                                    textLines.Add(textLine.BidiReOrder());
+                                    textLine = split;
+                                    lineAdvance = split.ScaledLineAdvance();
+                                }
                             }
                             else if (currentLineBreak.PositionMeasure == codePointIndex)
                             {


Added new UnderscoreToCamelCase utility method + some XML documentation

--- src/Skybrud.Social/SocialUtils.cs
+++ src/Skybrud.Social/SocialUtils.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.Diagnostics;
 using System.IO;
@@ -171,12 +172,40 @@

         #region Other

+        /// <summary>
+        /// Converts a camel cased reprenstation of an enum to a lower case string where words are separated with underscore.
+        /// </summary>
+        /// <param name="e">The enum to be converted.</param>
+        /// <returns>Returns the converted string.</returns>
         public static string CamelCaseToUnderscore(Enum e) {
             return CamelCaseToUnderscore(e.ToString());
         }
-
+
+        /// <summary>
+        /// Converts a camel cased string to a lower case string where words are separated with underscore.
+        /// </summary>
+        /// <param name="str">The camel cased string to be converted.</param>
+        /// <returns>Returns the converted string.</returns>
         public static string CamelCaseToUnderscore(string str) {
             return Regex.Replace(str, @"(\p{Ll})(\p{Lu})", "$1_$2").ToLower();
+        }
+
+        /// <summary>
+        /// Converts a string separated by underscoes to a upper camel cased string.
+        /// </summary>
+        /// <param name="str">The camel cased string to be converted.</param>
+        /// <returns>Returns the converted string.</returns>
+        public static string UnderscoreToCamelCase(string str) {
+            if (String.IsNullOrWhiteSpace(str)) return str;
+            List<string> temp = new List<string>();
+            foreach (string piece in str.Split(new [] {'_'}, StringSplitOptions.RemoveEmptyEntries)) {
+                if (piece.Length == 1) {
+                    temp.Add(piece.ToUpper());
+                } else if (piece.Length > 1) {
+                    temp.Add(piece.Substring(0, 1).ToUpper() + piece.Substring(1));
+                }
+            }
+            return String.Join("", temp);
         }

         /// <summary>


Removed <img /> attr for missing fhir-logo.png

--- src/Spark/Views/Home/Index.cshtml
+++ src/Spark/Views/Home/Index.cshtml
@@ -38,7 +38,6 @@

-

             FHIR is the latest Health communication standard from HL7.
             FHIR aims to be a lot simpler than HL7v3, without sacrificing information integrity.


Added the Vector2D cross product

Added the Vector2D cross product

Though not a true cross product in the mathematical sense, the faked cross product (acting as if the 2D vectors had a 0.0 magnitude in Z and returning the scalar magnitude of the resulting 3D cross product) is a commonly used operation in 2D geometry for determining the relationship between vectors and computing the area of 2D shapes.

--- src/Spatial/Euclidean/Vector2D.cs
+++ src/Spatial/Euclidean/Vector2D.cs
@@ -296,6 +296,14 @@
             return (this.X*other.X) + (this.Y*other.Y);
         }

+        public double CrossProduct(Vector2D other)
+        {
+            // Perform the 2D "cross product" as if the 2D vectors were really 3D vectors on the z=0 plane, returning the
+            // scalar magnitude of the resulting vector.  Though the cross product is undefined in 2D space, this is
+            // a useful mathematical operation to determine direction and compute the area of 2D shapes
+            return this.X*other.Y - this.Y*other.X;
+        }
+
         public Vector2D Normalize()
         {
             var l = this.Length;


To ternary

To ternary

--- ExpressionToCodeLib/Internal/ObjectStringifyImpl.cs
+++ ExpressionToCodeLib/Internal/ObjectStringifyImpl.cs
@@ -21,11 +21,7 @@
             if (val == null) {
                 return type == null || type == typeof(object) ? "null" : "default(" + TypeNameToCode(type) + ")";
             } else if (val is string str) {
-                if (PreferLiteralSyntax(str)) {
-                    return "@\"" + str.Replace("\"", "\"\"") + "\"";
-                } else {
-                    return "\"" + EscapeStringChars(str) + "\"";
-                }
+                return PreferLiteralSyntax(str) ? "@\"" + str.Replace("\"", "\"\"") + "\"" : "\"" + EscapeStringChars(str) + "\"";
             } else if (val is char charVal) {
                 return "'" + EscapeCharForString(charVal) + "'";
             } else if (val is decimal) {


ReverseStringBuilder reworked to use ArrayReservoir

--- Framework.Core/Theraot/Core/ReverseStringBuilder.cs
+++ Framework.Core/Theraot/Core/ReverseStringBuilder.cs
@@ -1,32 +1,47 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using Theraot.Collections.ThreadSafe;
+using Theraot.Threading;

 namespace Theraot.Core
 {
     public class ReverseStringBuilder : IEnumerable<char>
     {
-        private readonly char[] _buffer;
+        private char[] _buffer;
+        private readonly int _capacity;
         private int _start;

         public ReverseStringBuilder(int capacity)
         {
-            try
-            {
-                _buffer = new char[capacity];
-                _start = _buffer.Length;
-            }
-            catch
+            if (capacity < 0)
             {
                 throw new ArgumentOutOfRangeException(nameof(capacity));
             }
+            _buffer = ArrayReservoir<char>.GetArray(capacity);
+            _capacity = capacity;
+            _start = capacity;
         }

-        public int Length => _buffer.Length - _start;
+        ~ReverseStringBuilder()
+        {
+            // Assume anything could have been set to null, start no sync operation, this could be running during DomainUnload
+            if (!GCMonitor.FinalizingForUnload)
+            {
+                var buffer = _buffer;
+                if (buffer != null)
+                {
+                    ArrayReservoir<char>.DonateArray(buffer);
+                    _buffer = null;
+                }
+            }
+        }
+
+        public int Length => _capacity - _start;

         public IEnumerator<char> GetEnumerator()
         {
-            for (var position = _buffer.Length - 1; position >= 0; position--)
+            for (var position = _capacity - 1; position >= 0; position--)
             {
                 yield return _buffer[position];
             }
@@ -51,27 +66,31 @@

         public override string ToString()
         {
-            return new string(_buffer, _start, _buffer.Length - _start);
+            return new string(_buffer, _start, _capacity - _start);
         }

         public string ToString(int maxLength)
         {
-            var length = _buffer.Length - _start;
+            var length = _capacity - _start;
             if (length > maxLength)
             {
                 length = maxLength;
             }
-            return new string(_buffer, _buffer.Length - length, length);
+            return new string(_buffer, _capacity - length, length);
         }

         public string ToString(int backIndex, int maxLength)
         {
-            var length = _buffer.Length - _start;
+            if (backIndex < 0)
+            {
+                throw new ArgumentOutOfRangeException(nameof(backIndex));
+            }
+            var length = _capacity - _start;
             if (length > maxLength)
             {
                 length = maxLength;
             }
-            return new string(_buffer, _buffer.Length - backIndex, length);
+            return new string(_buffer, _capacity - backIndex, length);
         }
     }
 }


Include the unknown field of the ability info in the output.

--- PlayOnline.FFXI.Utils.DataBrowser/FileScanDialog.cs
+++ PlayOnline.FFXI.Utils.DataBrowser/FileScanDialog.cs
@@ -41,6 +41,8 @@
     }

     #region Scanners
+
+    #region Main Scanning Functionality

     private void ScanFile() {
       if (FileName != null && File.Exists(FileName)) {
@@ -141,6 +143,8 @@
       return true;
     }

+    #endregion
+
     #region Abilities

     private void ScanAbilityFile(BinaryReader BR) {
@@ -149,7 +153,7 @@
       BR.BaseStream.Seek(0, SeekOrigin.Begin);
       if ((BR.BaseStream.Length % 0x400) != 0)
 	return;
-    ColumnHeader[] InfoColumns = new ColumnHeader[5];
+    ColumnHeader[] InfoColumns = new ColumnHeader[6];
       InfoColumns[0]           = new ColumnHeader();
       InfoColumns[0].Text      = I18N.GetText("ColumnHeader:Name");
       InfoColumns[0].TextAlign = HorizontalAlignment.Left;
@@ -170,6 +174,10 @@
       InfoColumns[4].Text      = I18N.GetText("ColumnHeader:Description");
       InfoColumns[4].TextAlign = HorizontalAlignment.Left;
       InfoColumns[4].Width     = 120;
+      InfoColumns[5]           = new ColumnHeader();
+      InfoColumns[5].Text      = I18N.GetText("ColumnHeader:Unknown");
+      InfoColumns[5].TextAlign = HorizontalAlignment.Left;
+      InfoColumns[5].Width     = 120;
       this.StringTableEntries.Add(InfoColumns);
     long EntryCount = BR.BaseStream.Length / 0x400;
     Encoding E = new FFXIEncoding();
@@ -179,8 +187,7 @@
       // 002-003 U16 Unknown
       // 004-005 U16 MP Cost
       // 006-007 U16 Cooldown
-      // 008-008 U8  Target (1 = Self, 5 = PT Member, 20 = Monster)
-      // 009-009 U8  Unknown (NUL?)
+      // 008-009 U16 Valid Targets
       // 00a-029 TXT Name
       // 02a-129 TXT Description (exact length unknown)
       // 12a-3fe U8  Padding (NULs)
@@ -195,6 +202,7 @@
 	Fields.Add(String.Format("{0}", new TimeSpan(0, 0, Bytes[0x06] + (Bytes[0x07] << 8))));
 	Fields.Add(String.Format("{0}", (ValidTarget) Bytes[8]));
 	Fields.Add(E.GetString(Bytes, 42, 256).TrimEnd('\0'));
+	Fields.Add(String.Format("{0} ({0:X2})", Bytes[0x02] + (Bytes[0x03] << 8)));
 	this.StringTableEntries.Add(Fields.ToArray());
 	if (FileScanDialog.ShowProgressDetails)
 	  this.lblScanProgress.Text = String.Format(I18N.GetText("AbilityLoadProgress"), i + 1, EntryCount);


Making :thumbsdown: racially inclusive

Making :thumbsdown: racially inclusive

--- PokemonGoRaidBot/Services/Discord/MessageHandler.cs
+++ PokemonGoRaidBot/Services/Discord/MessageHandler.cs
@@ -24,6 +24,8 @@
         private IServiceProvider map;
         private IStatMapper Mapper;

+        private List<string> DeleteEmojis = new List<string>(new string[] { "👎", "👎🏻", "👎🏽", "👎🏾", "👎🏿" });
+
         public ConsoleLogger Logger;
         public readonly BotConfiguration Config;

@@ -88,7 +90,7 @@
             if (arg3.UserId == bot.CurrentUser.Id) return;

             var message = await arg2.GetMessageAsync(arg1.Id);
-            if (message == null || string.IsNullOrEmpty(message.Content) || !(arg2 is SocketGuildChannel) || arg3.Emote.Name == "👎") return;
+            if (message == null || string.IsNullOrEmpty(message.Content) || !(arg2 is SocketGuildChannel) || DeleteEmojis.Contains(arg3.Emote.Name)) return;
             var guildConfig = Config.GetGuildConfig(((SocketGuildChannel)arg2).Guild.Id);
             var channel = (SocketGuildChannel)arg2;

@@ -139,7 +141,7 @@

             if (post != null && user != null)
             {
-                if (arg3.Emote.Name == "👎")//thumbs down will be quick way to delete a raid by poster/admin
+                if (DeleteEmojis.Contains(arg3.Emote.Name))//thumbs down will be quick way to delete a raid by poster/admin
                 {
                     await DeletePost(post, user.Id, user.GuildPermissions.Administrator || user.GuildPermissions.ManageGuild);
                 }