skipped chars consumption (eol and spaces)

--- sly/lexer/fsm/FSMLexer.cs
+++ sly/lexer/fsm/FSMLexer.cs
@@ -195,55 +195,63 @@
             if (CurrentPosition < source.Length)
             {
                 char currentToken = source[CurrentPosition];
-
+
                 while (CurrentPosition < source.Length && currentNode != null)
                 {
                     currentToken = source[CurrentPosition];

-                    // TODO : if WS && ignoreWS => next column ++
-                    if (IgnoreWhiteSpace && WhiteSpaces.Contains(currentToken))
+                    bool consumeSkipped = true;
+
+                    while (consumeSkipped)
                     {
+                        // TODO : if WS && ignoreWS => next column ++
+                        if (IgnoreWhiteSpace && WhiteSpaces.Contains(currentToken))
+                        {
+                            CurrentPosition++;
+                            CurrentColumn++;
+                        }
+                        else
+                        {
+                            string subSource = source.Substring(Math.Max(CurrentPosition, 0));
+                            if (IgnoreEOL && subSource.StartsWith(EOL))
+                            {
+                                CurrentPosition += EOL.Length;
+                                CurrentColumn = 0;
+                                CurrentLine++;
+                            }
+                            else
+                            {
+                                consumeSkipped = false;
+                            }
+                        }
+                    }
+
+                    currentNode = Move(currentNode, currentToken);
+                    if (currentNode != null)
+                    {
+                        lastNode = currentNode.Id;
+                        value += currentToken;
+                        if (!tokenStarted)
+                        {
+                            tokenStarted = true;
+                            tokenPosition = CurrentPosition;
+                            tokenColumn = CurrentColumn;
+                            tokenLine = CurrentLine;
+                        }
+                        if (currentNode.IsEnd)
+                        {
+                            var resultInter = new FSMMatch<N>(true, currentNode.Value, value, tokenPosition, tokenLine, tokenColumn);
+                            successes.Push(resultInter);
+                            //successes.Push((CurrentPosition,CurrentLine, CurrentColumn, currentNode.Value));
+                        }
                         CurrentPosition++;
-                        CurrentColumn++;
-                    }
-                    else
-                    {
-                        string subSource = source.Substring(Math.Max(CurrentPosition,0));
-                        if (IgnoreEOL && subSource.StartsWith(EOL))
-                        {
-                            CurrentPosition += EOL.Length;
-                            CurrentColumn = 0;
-                            CurrentLine++;
-
-                        }
-                        else
-                        {
-                            currentNode = Move(currentNode, currentToken);
-                            if (currentNode != null)
-                            {
-                                lastNode = currentNode.Id;
-                                value += currentToken;
-                                if (!tokenStarted)
-                                {
-                                    tokenStarted = true;
-                                    tokenPosition = CurrentPosition;
-                                    tokenColumn = CurrentColumn;
-                                    tokenLine = CurrentLine;
-                                }
-                                if (currentNode.IsEnd)
-                                {
-                                    var resultInter = new FSMMatch<N>(true, currentNode.Value, value, tokenPosition, tokenLine, tokenColumn);
-                                    successes.Push(resultInter);
-                                    //successes.Push((CurrentPosition,CurrentLine, CurrentColumn, currentNode.Value));
-                                }
-                                CurrentPosition++;
-                                CurrentColumn+= value.Length ;
-                            }
-                        }
-                    }
-                }
-            }
-
+                        CurrentColumn += value.Length;
+                    }
+
+                }
+            }
+
+
             if (successes.Any())
             {
                 result = successes.Pop(); // TODO get line and column
@@ -283,6 +291,8 @@
             return next;
         }

+
+
         #endregion

     }


plugin: update CE Offset for CN 5.35 (#2459)

--- plugin/CactbotEventSource/FateWatcher.cs
+++ plugin/CactbotEventSource/FateWatcher.cs
@@ -46,6 +46,11 @@
       0x30,
       0x299
     );
+
+    private static readonly CEDirectorOPCodes cedirector_v5_35_cn = new CEDirectorOPCodes(
+      0x30,
+      0x144
+    );

     private static readonly CEDirectorOPCodes cedirector_v5_35_hotfix = new CEDirectorOPCodes(
       0x30,
@@ -141,6 +146,7 @@
       cedirectoropcodes = new Dictionary<string, CEDirectorOPCodes>();
       cedirectoropcodes.Add("intl", cedirector_v5_45);

+      cedirectoropcodes.Add("cn", cedirector_v5_35_cn);
       fates = new Dictionary<int, int>();
       ces = new Dictionary<int, CEDirectorData>();


master - Fix tcsPurchase Bugs

master - Fix tcsPurchase Bugs

This commit fixes bugs surrounding tcsPurchase in the Andorid
InAppBillingImplementation class.

1. HandleActivityResult uses null-conditional operator to access
tcsPurcahse to avoid NullReferenceException.
2. HandleActivityResult now invokes TrySetException rather than
SetException to avoid InvalidOperationException.
3. ConnectAsync() now invokes TryCancel() and sets tcsPurcahse to null.
This was done to prevent tcsPurcahse from being stuck in a
WaitingForActivation TaskStatus state when the activity is destroyed in
recreated while the purchase modal is being presented to the user. This
was causing all future purchase attempts to return null when invoking
PurchaseAsync().

--- src/Plugin.InAppBilling.Android/InAppBillingImplementation.cs
+++ src/Plugin.InAppBilling.Android/InAppBillingImplementation.cs
@@ -365,6 +365,8 @@
         public override Task<bool> ConnectAsync(ItemType itemType = ItemType.InAppPurchase)
         {
             serviceConnection = new InAppBillingServiceConnection(Context, itemType);
+            tcsPurchase?.TrySetCanceled();
+            tcsPurchase = null;
             return serviceConnection.ConnectAsync();
         }

@@ -522,38 +524,38 @@

             switch (responseCode)
             {
-                case 0:
-                    //Reponse returned OK
-                    var purchaseData = data.GetStringExtra(RESPONSE_IAP_DATA);
-                    var dataSignature = data.GetStringExtra(RESPONSE_IAP_DATA_SIGNATURE);
-
-                    tcsPurchase?.TrySetResult(new PurchaseResponse
-                    {
-                        PurchaseData = purchaseData,
-                        DataSignature = dataSignature
-                    });
-                    break;
-                case RESPONSE_CODE_RESULT_USER_CANCELED:
-                    tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.UserCancelled));
-                    break;
-                case RESPONSE_CODE_RESULT_SERVICE_UNAVAILABLE:
-                    tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable));
-                    break;
-				case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
-					tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.ItemUnavailable));
-					break;
-				case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR:
-					tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.DeveloperError));
-					break;
-				case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED:
-					tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.AlreadyOwned));
-					break;
-				case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED:
-					tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.NotOwned));
-					break;
-				default:
-                    tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.GeneralError, responseCode.ToString()));
-                    break;
+	            case 0:
+		            //Reponse returned OK
+		            var purchaseData = data.GetStringExtra(RESPONSE_IAP_DATA);
+		            var dataSignature = data.GetStringExtra(RESPONSE_IAP_DATA_SIGNATURE);
+
+		            tcsPurchase?.TrySetResult(new PurchaseResponse
+		            {
+			            PurchaseData = purchaseData, DataSignature = dataSignature
+		            });
+		            break;
+	            case RESPONSE_CODE_RESULT_USER_CANCELED:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.UserCancelled));
+		            break;
+	            case RESPONSE_CODE_RESULT_SERVICE_UNAVAILABLE:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable));
+		            break;
+	            case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.ItemUnavailable));
+		            break;
+	            case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.DeveloperError));
+		            break;
+	            case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.AlreadyOwned));
+		            break;
+	            case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED:
+		            tcsPurchase?.TrySetException(new InAppBillingPurchaseException(PurchaseError.NotOwned));
+		            break;
+	            default:
+		            tcsPurchase?.TrySetException(
+			            new InAppBillingPurchaseException(PurchaseError.GeneralError, responseCode.ToString()));
+		            break;
             }
         }


Unit test was destroying config on disk.

Meant a rebuilt was required between running unit and integration tests. This solves it for now, although re-writing config files on disk might be a shit idea #hindsight.

--- src/QuartzNET-DynamoDB.Tests/Unit/DynamoConfigurationTests.cs
+++ src/QuartzNET-DynamoDB.Tests/Unit/DynamoConfigurationTests.cs
@@ -12,7 +12,7 @@
         {
             var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             config.AppSettings.Settings.Remove("BootstrapRetryDelayMilliseconds");
-            config.Save(ConfigurationSaveMode.Modified);
+            config.Save(ConfigurationSaveMode.Full);

             Assert.Equal(500, DynamoConfiguration.BootstrapRetryDelayMilliseconds);
         }


renamed date param to correctly reflect its perpose

was FromDate now ToDate

--- src/SFA.DAS.EAS.Api/Controllers/EmployerAccountsController.cs
+++ src/SFA.DAS.EAS.Api/Controllers/EmployerAccountsController.cs
@@ -20,10 +20,11 @@
         }

         [Route("", Name = "AccountsIndex")]
-        [HttpGet]
-        public async Task<IHttpActionResult> Index(string fromDate = null, int pageSize = 1000, int pageNumber = 1)
+        [Authorize(Roles = "ReadAllEmployerAccountBalances")]
+        [HttpGet]
+        public async Task<IHttpActionResult> Index(string toDate = null, int pageSize = 1000, int pageNumber = 1)
         {
-            var result = await _orchestrator.GetAllAccountsWithBalances(fromDate, pageSize, pageNumber);
+            var result = await _orchestrator.GetAllAccountsWithBalances(toDate, pageSize, pageNumber);

             if (result.Status == HttpStatusCode.OK)
             {


BreadCrumbs.cs - now pageUrl must be equal to the current request

--- BreadCrumbs.cs
+++ BreadCrumbs.cs
@@ -27,7 +27,7 @@

                 foreach (var k in x.pages)
                 {
-                    if (Page.ResolveUrl(k.pageUrl.ToString()).Contains(HttpContext.Current.Request.FilePath))
+                    if (Page.ResolveUrl(k.pageUrl.ToString()).Equals(HttpContext.Current.Request.FilePath))
                     {
                         list.Add(new BreadCrumbItem { PageUrl = k.pageUrl, PageIco = k.pageIco, PageName = k.pageLabel });
                     }
@@ -35,7 +35,7 @@
                     {
                         foreach (var h in k.subpages)
                         {
-                            if (Page.ResolveUrl(h.pageUrl.ToString()).Contains(HttpContext.Current.Request.FilePath))
+                            if (Page.ResolveUrl(h.pageUrl.ToString()).Equals(HttpContext.Current.Request.FilePath))
                             {
                                 list.Add(new BreadCrumbItem { PageUrl = k.pageUrl, PageIco = k.pageIco, PageName = k.pageLabel });
                                 list.Add(new BreadCrumbItem { PageUrl = h.pageUrl, PageIco = h.pageIco, PageName = h.pageLabel });
@@ -44,7 +44,7 @@
                             {
                                 foreach (var t in h.subpages)
                                 {
-                                    if (Page.ResolveUrl(t.pageUrl.ToString()).Contains(HttpContext.Current.Request.FilePath))
+                                    if (Page.ResolveUrl(t.pageUrl.ToString()).Equals(HttpContext.Current.Request.FilePath))
                                     {
                                         list.Add(new BreadCrumbItem { PageUrl = k.pageUrl, PageIco = k.pageIco, PageName = k.pageLabel });
                                         list.Add(new BreadCrumbItem { PageUrl = h.pageUrl, PageIco = h.pageIco, PageName = h.pageLabel });
@@ -54,7 +54,7 @@
                                     {
                                         foreach (var tt in t.subpages)
                                         {
-                                            if (Page.ResolveUrl(tt.pageUrl.ToString()).Contains(HttpContext.Current.Request.FilePath))
+                                            if (Page.ResolveUrl(tt.pageUrl.ToString()).Equals(HttpContext.Current.Request.FilePath))
                                             {
                                                 list.Add(new BreadCrumbItem { PageUrl = k.pageUrl, PageIco = k.pageIco, PageName = k.pageLabel });
                                                 list.Add(new BreadCrumbItem { PageUrl = h.pageUrl, PageIco = h.pageIco, PageName = h.pageLabel });


Added generic overloads for the StringExtensions.Join methods

The two methods aren't really that useful if not generic. The two existing methods should have been generic in the first place, but are now kept for backwards compatibility - although no one is probably use them 🤔

--- src/Skybrud.Essentials/Strings/Extensions/StringExtensions.cs
+++ src/Skybrud.Essentials/Strings/Extensions/StringExtensions.cs
@@ -239,6 +239,32 @@
         }

         /// <summary>
+        /// Concatenates the string representations of each item in <paramref name="values"/>, using the specified
+        /// <paramref name="separator"/> between each member.
+        /// </summary>
+        /// <param name="values">A collection of objects whose string representations will be concatenated.</param>
+        /// <param name="separator">The character to use as a separator. <paramref name="separator"/> is included in
+        /// the returned string only if value has more than one element.</param>
+        /// <returns>A string that consists of the elements of <paramref name="values"/> delimited by the
+        /// <paramref name="separator"/> character, <see cref="string.Empty"/> if values has zero elements.</returns>
+        public static string Join<T>(this IEnumerable<T> values, string separator) {
+            return string.Join(separator, values);
+        }
+
+        /// <summary>
+        /// Concatenates the string representations of each item in <paramref name="values"/>, using the specified
+        /// <paramref name="separator"/> between each member.
+        /// </summary>
+        /// <param name="values">A collection of objects whose string representations will be concatenated.</param>
+        /// <param name="separator">The character to use as a separator. <paramref name="separator"/> is included in
+        /// the returned string only if value has more than one element.</param>
+        /// <returns>A string that consists of the elements of <paramref name="values"/> delimited by the
+        /// <paramref name="separator"/> character, <see cref="string.Empty"/> if values has zero elements.</returns>
+        public static string Join<T>(this IEnumerable<T> values, char separator) {
+            return string.Join(separator.ToString(), values);
+        }
+
+        /// <summary>
         /// Converts a singular word to the plural counterpart (for English words only).
         /// </summary>
         /// <param name="word">The singular word.</param>


Exclude StringSyntaxAttribute from code coverage

--- Build/Build.cs
+++ Build/Build.cs
@@ -163,6 +163,7 @@
                 .SetTargetDirectory(RootDirectory / "TestResults" / "reports")
                 .AddReports(RootDirectory / "TestResults/**/coverage.cobertura.xml")
                 .AddReportTypes("HtmlInline_AzurePipelines_Dark", "lcov")
+                .SetClassFilters("-System.Diagnostics.CodeAnalysis.StringSyntaxAttribute")
                 .SetAssemblyFilters("+FluentAssertions"));

             string link = RootDirectory / "TestResults" / "reports" / "index.html";


chore(Smart Answers): remove un-needed logging

--- src/StockportWebapp/QuestionBuilder/BaseQuestionController.cs
+++ src/StockportWebapp/QuestionBuilder/BaseQuestionController.cs
@@ -172,25 +172,16 @@
                         page.AddAnswers(allAnswers);
                         break;
                     case EQuestionType.HandOffData:
-                        _logger.LogInformation("------Before config");
                         var authenticationKey = _config["DTSHandOffAuthenticationKey"];
-                        _logger.LogInformation($"------Authentication key: {authenticationKey}");
-
-                        _logger.LogInformation($"------{behaviour.Value}");
-
-                        _logger.LogWarning($"------{behaviour.Value}");
                         try
                         {
-                            _logger.LogWarning($"------- {page.PreviousAnswersJson}");
                             var guid = await _client.PostAsyncMessage($"{behaviour.Value}", new StringContent(page.PreviousAnswersJson, Encoding.UTF8, "application/json"), new Dictionary<string, string> { { "DTSHandOffAuthenticationKey", authenticationKey } });
-                            _logger.LogInformation($"------{guid ?? null}");
                             if (string.IsNullOrEmpty(guid.Content.ReadAsStringAsync().Result))
                             {
-                                _logger.LogInformation($"Guid not set");
+                                _logger.LogWarning($"Guid not set");
                             }
                             else
                             {
-                                //_logger.LogInformation($"Redirect url ==== {behaviour.Value}date?guid={JsonConvert.DeserializeObject(guid.Content.ReadAsStringAsync().Result)}");
                                 return Redirect($"{behaviour.RedirectValue}?guid={JsonConvert.DeserializeObject(guid.Content.ReadAsStringAsync().Result)}");
                             }


Change ActiveIssue test for 5965 to accept the current behaviour.

Closes #5965

--- src/System.Linq.Expressions/tests/MemberInit/ListBindTests.cs
+++ src/System.Linq.Expressions/tests/MemberInit/ListBindTests.cs
@@ -15,19 +15,24 @@
             public static List<T> StaticListField = new List<T>();
             public static List<T> StaticListProperty { get; set; }
             public readonly List<T> ListField = new List<T>();
+
             public List<T> ListProperty
             {
                 get { return ListField; }
             }
+
             public HashSet<T> HashSetField = new HashSet<T>();
+
             public List<T> WriteOnlyList
             {
-                set {  }
-            }
+                set { }
+            }
+
             public List<T> GetList()
             {
                 return ListField;
             }
+
             public IEnumerable<T> EnumerableProperty
             {
                 get { return ListField; }
@@ -84,16 +89,26 @@
             Assert.Throws<ArgumentException>(null, () => Expression.ListBind(member, Enumerable.Empty<ElementInit>()));
         }

-        [Fact]
-        [ActiveIssue(5965)]
-        public void NonAddableListType()
+        private static IEnumerable<object> NonAddableListExpressions()
         {
             PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.EnumerableProperty));
             MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.EnumerableProperty))[0];
-            Assert.Throws<ArgumentException>(null, () => Expression.ListBind(property, new ElementInit[0]));
-            Assert.Throws<ArgumentException>(null, () => Expression.ListBind(property, Enumerable.Empty<ElementInit>()));
-            Assert.Throws<ArgumentException>(null, () => Expression.ListBind(member, new ElementInit[0]));
-            Assert.Throws<ArgumentException>(null, () => Expression.ListBind(member, Enumerable.Empty<ElementInit>()));
+            yield return new object[] {Expression.ListBind(property)};
+            yield return new object[] {Expression.ListBind(property, Enumerable.Empty<ElementInit>())};
+            yield return new object[] {Expression.ListBind(member)};
+            yield return new object[] {Expression.ListBind(member, Enumerable.Empty<ElementInit>())};
+        }
+
+        [Theory, PerCompilationType(nameof(NonAddableListExpressions))]
+        public void NonAddableListType(MemberListBinding listBinding, bool useInterpreter)
+        {
+            Func<ListWrapper<int>> func = Expression.Lambda<Func<ListWrapper<int>>>(
+                            Expression.MemberInit(
+                                Expression.New(typeof(ListWrapper<int>)),
+                                listBinding
+                                )
+                            ).Compile(useInterpreter);
+            Assert.Empty(func().EnumerableProperty);
         }

         [Fact]
@@ -105,7 +120,7 @@
         [Fact]
         public void MismatchingElement()
         {
-            Assert.Throws<ArgumentException>(() => Expression.ListBind(typeof(ListWrapper<int>).GetMethod(nameof(ListWrapper<int>.GetList)), Expression.ElementInit(typeof(HashSet<int>).GetMethod("Add"), Expression.Constant(1)) ));
+            Assert.Throws<ArgumentException>(() => Expression.ListBind(typeof(ListWrapper<int>).GetMethod(nameof(ListWrapper<int>.GetList)), Expression.ElementInit(typeof(HashSet<int>).GetMethod("Add"), Expression.Constant(1))));
         }

         [Fact]
@@ -124,12 +139,12 @@
             PropertyInfo property = typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty));
             MemberInfo member = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.ListProperty))[0];
             MemberInfo fieldMember = typeof(ListWrapper<int>).GetMember(nameof(ListWrapper<int>.ListField))[0];
-            yield return new object[] { Expression.ListBind(property) };
-            yield return new object[] { Expression.ListBind(property, Enumerable.Empty<ElementInit>()) };
-            yield return new object[] { Expression.ListBind(member) };
-            yield return new object[] { Expression.ListBind(member, Enumerable.Empty<ElementInit>()) };
-            yield return new object[] { Expression.ListBind(fieldMember) };
-            yield return new object[] { Expression.ListBind(fieldMember, Enumerable.Empty<ElementInit>()) };
+            yield return new object[] {Expression.ListBind(property)};
+            yield return new object[] {Expression.ListBind(property, Enumerable.Empty<ElementInit>())};
+            yield return new object[] {Expression.ListBind(member)};
+            yield return new object[] {Expression.ListBind(member, Enumerable.Empty<ElementInit>())};
+            yield return new object[] {Expression.ListBind(fieldMember)};
+            yield return new object[] {Expression.ListBind(fieldMember, Enumerable.Empty<ElementInit>())};
         }

         [Theory]
@@ -180,24 +195,24 @@
         [Theory, ClassData(typeof(CompilationTypes))]
         public void InitializeVoidAdd(bool useInterperter)
         {
-            Expression<Func<ListWrapper<int>>> listInit = () => new ListWrapper<int> { ListProperty = { 1, 4, 9, 16 } };
+            Expression<Func<ListWrapper<int>>> listInit = () => new ListWrapper<int> {ListProperty = {1, 4, 9, 16}};
             Func<ListWrapper<int>> func = listInit.Compile(useInterperter);
-            Assert.Equal(new[] { 1, 4, 9, 16 }, func().ListProperty);
+            Assert.Equal(new[] {1, 4, 9, 16}, func().ListProperty);
         }

         [Theory, ClassData(typeof(CompilationTypes))]
         public void InitializeNonVoidAdd(bool useInterpreter)
         {
-            Expression<Func<ListWrapper<int>>> hashInit = () => new ListWrapper<int> { HashSetField = { 1, 4, 9, 16 } };
+            Expression<Func<ListWrapper<int>>> hashInit = () => new ListWrapper<int> {HashSetField = {1, 4, 9, 16}};
             Func<ListWrapper<int>> func = hashInit.Compile(useInterpreter);
-            Assert.Equal(new[] { 1, 4, 9, 16 }, func().HashSetField.OrderBy(i => i));
+            Assert.Equal(new[] {1, 4, 9, 16}, func().HashSetField.OrderBy(i => i));
         }

         [Fact]
         public void UpdateDifferentReturnsDifferent()
         {
             MemberListBinding binding = Expression.ListBind(typeof(ListWrapper<int>).GetProperty(nameof(ListWrapper<int>.ListProperty)), Enumerable.Range(0, 3).Select(i => Expression.ElementInit(typeof(List<int>).GetMethod("Add"), Expression.Constant(i))));
-            Assert.NotSame(binding, binding.Update(new[] { Expression.ElementInit(typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(1)) }));
+            Assert.NotSame(binding, binding.Update(new[] {Expression.ElementInit(typeof(List<int>).GetMethod(nameof(List<int>.Add)), Expression.Constant(1))}));
         }

         [Fact]


Disable unreliable Http diagnostics logging test (#23977)

The Http test, SendAsync_ExpectedDiagnosticCancelledLogging, has been
failing at times.

I am going to disable this test until it can be made more robust. It is
not a reliable test because cancellation cannot be guaranteed to occur
with a certain time especially on a busy machine.

#23209

--- src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs
+++ src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs
@@ -258,6 +258,7 @@
             }).Dispose();
         }

+        [ActiveIssue(23209)]
         [OuterLoop] // TODO: Issue #11345
         [Fact]
         public void SendAsync_ExpectedDiagnosticCancelledLogging()


Disabled two more tests on AppVeyor because the tests are shit Both tests have a high failure rate, even on my local machine, presumably because I didn't write them properly (or maybe the tests are right and the tested code is defect), either way those two tests shouldn't be part of AppVeyor just yet...

--- src/Tailviewer.AcceptanceTests/SingleApplicationHelperTest.cs
+++ src/Tailviewer.AcceptanceTests/SingleApplicationHelperTest.cs
@@ -2,6 +2,7 @@
 using System.Threading;
 using Moq;
 using NUnit.Framework;
+using Tailviewer.Test;

 namespace Tailviewer.AcceptanceTests
 {
@@ -9,6 +10,7 @@
 	public sealed class SingleApplicationHelperTest
 	{
 		[Test]
+		[LocalTest("This test fails 50% of the time and is thus unsuited to run on AppVeyor until it's fixed")]
 		public void TestOpenFile1()
 		{
 			using (var mutex = SingleApplicationHelper.AcquireMutex())
@@ -23,6 +25,7 @@
 		}

 		[Test]
+		[LocalTest("This test fails 50% of the time and is thus unsuited to run on AppVeyor until it's fixed")]
 		public void TestBringToFront()
 		{
 			using (var mutex = SingleApplicationHelper.AcquireMutex(TimeSpan.FromSeconds(1)))


Disable CA1506 for DeploymentProcess

Disable CA1506 for DeploymentProcess

--- src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs
+++ src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs
@@ -531,6 +531,7 @@
 		}

 		/// <inheritdoc />
+		#pragma warning disable CA1506
 		public async Task DeploymentProcess(
 			Models.Job job,
 			IDatabaseContext databaseContext,
@@ -670,6 +671,7 @@
 				cancellationToken)
 				.ConfigureAwait(false);
 		}
+		#pragma warning restore CA1506

 		/// <summary>
 		/// Calculate the average length of a deployment using a given <paramref name="databaseContext"/>.


Fix downloading image without quality parameter.

--- src/WebCamImageCollector.Background/Background/Application.cs
+++ src/WebCamImageCollector.Background/Background/Application.cs
@@ -134,8 +134,8 @@

         private ImageQuality GetImageQuality(HttpRequest request)
         {
-            string rawValue = request.QueryString["quality"];
-            if (String.IsNullOrEmpty(rawValue))
+            string rawValue;
+            if (!request.QueryString.TryGetValue("quality", out rawValue) || String.IsNullOrEmpty(rawValue))
                 return ImageQuality.Full;

             ImageQuality value;


Refactor: Reformat

Refactor: Reformat

--- src/reni2/Context/ContextBase.cs
+++ src/reni2/Context/ContextBase.cs
@@ -36,10 +36,7 @@
         internal readonly Cache CacheObject;

         protected ContextBase()
-            : base(_nextId++)
-        {
-            CacheObject = new Cache(this);
-        }
+            : base(_nextId++) { CacheObject = new Cache(this); }

         public abstract string GetContextIdentificationDump();

@@ -106,8 +103,8 @@
         {
             [EnableDumpExcept(false)]
             readonly bool AsReference;
-            readonly ContextBase Context;
-            readonly CompileSyntax Syntax;
+            internal readonly ContextBase Context;
+            internal readonly CompileSyntax Syntax;
             static int _nextObjectId;

             internal ResultProvider


bug fixes: 1. When a parameter's default value is different from the parameter's type (such in GUID), convert the default value to the required type. 2. When generating the help string, there was a double string.format call which caused an exception if the default value contains '{ }', such in a GUID. 3. The help string was always generated even when no help was required.

--- CLAP/Parser.cs
+++ CLAP/Parser.cs
@@ -173,6 +173,13 @@
                     // the default is the value
                     //
                     value = parameter.Default;
+
+                    // convert the default value, if different from parameter's value (guid, for example)
+                    //
+                    if (value is string && !(p.ParameterType == typeof(string)))
+                    {
+                        value = GetValueForParameter(p.ParameterType, "{DEFAULT}", (string)value);
+                    }
                 }
                 else
                 {
@@ -515,7 +522,7 @@
                 }
                 else if (type == typeof(Guid))
                 {
-                    return (String.IsNullOrEmpty(value) ? null : (Object)new Guid(value));
+                    return string.IsNullOrEmpty(value) ? (object)null : new Guid(value);
                 }
                 else
                 {
@@ -545,7 +552,7 @@
             }
             if (p.Default != null)
             {
-                sb.AppendFormat(", Default = {0}".FormatWith(p.Default));
+                sb.AppendFormat(", Default = {0}", p.Default);
             }

             var validationAttributes = p.ParameterInfo.GetAttributes<ValidationAttribute>();
@@ -748,11 +755,14 @@

             Action<string> helpHandler = GetHelpHandler(arg);

-            var help = GetHelpString();
+            string help = null;
+
             var helpHandled = false;

             if (helpHandler != null)
             {
+                help = GetHelpString();
+
                 helpHandler(help);

                 helpHandled = true;
@@ -785,6 +795,11 @@

                         var obj = method.IsStatic ? null : target;

+                        if (help == null)
+                        {
+                            help = GetHelpString();
+                        }
+
                         method.Invoke(obj, new[] { help });

                         helpHandled = true;


Test for appending with wrong expected version.

--- src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.AppendStream..cs
+++ src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.AppendStream..cs
@@ -22,5 +22,22 @@
                 }
             }
         }
+
+        [Fact]
+        public async Task When_append_with_wrong_expected_version_then_should_throw()
+        {
+            using (var fixture = GetFixture())
+            {
+                using (var eventStore = await fixture.GetEventStore())
+                {
+                    await eventStore
+                        .AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamEvents(1, 2, 3));
+
+                    await eventStore
+                        .AppendToStream("stream-1", 1, CreateNewStreamEvents(4, 5, 6))
+                        .ShouldThrow<WrongExpectedVersionException>();
+                }
+            }
+        }
     }
 }


Fix error messages

Fix error messages

--- src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/DraftApprenticeship.cs
+++ src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/DraftApprenticeship.cs
@@ -171,7 +171,7 @@
         {
             if (!recognisePriorLearning.HasValue)
             {
-                throw new DomainException(nameof(RecognisePriorLearning), "Recognise prior learning must be set");
+                throw new DomainException("IsTherePriorLearning", "You must select yes or no");
             }

             RecognisePriorLearning = recognisePriorLearning;
@@ -187,11 +187,19 @@
         {
             if (!durationReducedBy.HasValue)
             {
-                throw new DomainException(nameof(PriorLearning.DurationReducedBy), "Duration reduction must be set");
+                throw new DomainException("ReducedDuration", "Duration reduction must be set");
+            }
+            if (durationReducedBy.HasValue && durationReducedBy.Value < 0)
+            {
+                throw new DomainException("ReducedDuration", "Duration reduction must not be negative");
             }
             if (!priceReducedBy.HasValue)
             {
-                throw new DomainException(nameof(PriorLearning.PriceReducedBy), "Price reduction must be set");
+                throw new DomainException("ReducedPrice", "Price reduction must be set");
+            }
+            if (priceReducedBy.HasValue && priceReducedBy.Value < 0)
+            {
+                throw new DomainException("ReducedPrice", "Price reduction must not be negative");
             }
             if (RecognisePriorLearning != true)
             {


Fixing error CA1307: Changing IndexOf to use StringComparison.Ordinal

--- src/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingTypeInfo.cs
+++ src/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingTypeInfo.cs
@@ -54,7 +54,7 @@
         public MissingTypeInfo(AssemblyInfo sourceAssembly, string docId, List<Version> targetStatus, string recommendedChanges)
             : base(docId)
         {
-            int pos = DocId.IndexOf("T:");
+            int pos = DocId.IndexOf("T:", StringComparison.Ordinal);
             if (pos == -1)
                 throw new ArgumentException(LocalizedStrings.MemberShouldBeDefinedOnTypeException, "docId");


Add test for flattening duplicates

Add test for flattening duplicates

--- src/NRules/Tests/NRules.Tests/Aggregators/FlatteningAggregatorTest.cs
+++ src/NRules/Tests/NRules.Tests/Aggregators/FlatteningAggregatorTest.cs
@@ -31,6 +31,28 @@
         }

         [Fact]
+        public void Add_FactsWithDuplicates_AddedDistinctResult()
+        {
+            //Arrange
+            var target = CreateTarget();
+
+            //Act
+            var facts = AsFact(new TestFact(1, "value11", "value12", "value12"), new TestFact(2, "value21", "value21", "value22"));
+            var result = target.Add(EmptyTuple(), facts).ToArray();
+
+            //Assert
+            Assert.Equal(4, result.Length);
+            Assert.Equal(AggregationAction.Added, result[0].Action);
+            Assert.Equal("value11", result[0].Aggregate);
+            Assert.Equal(AggregationAction.Added, result[1].Action);
+            Assert.Equal("value12", result[1].Aggregate);
+            Assert.Equal(AggregationAction.Added, result[2].Action);
+            Assert.Equal("value21", result[2].Aggregate);
+            Assert.Equal(AggregationAction.Added, result[3].Action);
+            Assert.Equal("value22", result[3].Aggregate);
+        }
+
+        [Fact]
         public void Add_NoFacts_EmptyResult()
         {
             //Arrange


#19098: Optimizing content item fetching in Search/AdminController
Work Item: 19098

--HG--
branch : 1.x

--- src/Orchard.Web/Modules/Orchard.Search/Controllers/AdminController.cs
+++ src/Orchard.Web/Modules/Orchard.Search/Controllers/AdminController.cs
@@ -53,7 +53,7 @@
             }

             var list = Services.New.List();
-            foreach (var contentItem in searchHits.Select(searchHit => Services.ContentManager.Get(searchHit.ContentItemId))) {
+            foreach (var contentItem in Services.ContentManager.GetMany<IContent>(searchHits.Select(x => x.ContentItemId), VersionOptions.Published, QueryHints.Empty)) {
                 // ignore search results which content item has been removed or unpublished
                 if (contentItem == null) {
                     searchHits.TotalItemCount--;


#17612: Fixing validation message in Warmup module

Work Items: 17612

--HG--
branch : 1.x

--- src/Orchard.Web/Modules/Orchard.Warmup/Controllers/AdminController.cs
+++ src/Orchard.Web/Modules/Orchard.Warmup/Controllers/AdminController.cs
@@ -63,7 +63,10 @@
                 }
             }

-            Services.Notifier.Information(T("Warmup updated successfully."));
+            if (ModelState.IsValid) {
+                Services.Notifier.Information(T("Warmup updated successfully."));
+            }
+
             return View(warmupPart);
         }


DefaultValueTests pass

DefaultValueTests pass

--- src/RestEaseUnitTests/ImplementationFactoryTests/DefaultValueTests.cs
+++ src/RestEaseUnitTests/ImplementationFactoryTests/DefaultValueTests.cs
@@ -3,20 +3,22 @@
 using RestEase.Implementation;
 using System;
 using System.Collections.Generic;
+using System.Linq;
 using System.Reflection;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
 using Xunit;
+using Xunit.Abstractions;

 namespace RestEaseUnitTests.ImplementationFactoryTests
 {
-    public class DefaultValueTests
+    public class DefaultValueTests : ImplementationFactoryTestsBase
     {
         public interface IHasDefaultValue
         {
             [Get("foo")]
-            Task GetFooAsync(string foo = "", int bar = 3);
+            Task GetFooAsync(string foo = "", int bar = 3, float? baz = null);
         }

         public interface IHasDefaultCancellationToken
@@ -25,15 +27,14 @@
             Task GetFooAsync(CancellationToken cancellationToken = default);
         }

-        private readonly Mock<IRequester> requester = new Mock<IRequester>(MockBehavior.Strict);
-        private readonly EmitImplementationFactory factory = EmitImplementationFactory.Instance;
+        public DefaultValueTests(ITestOutputHelper output) : base(output) { }

         [Fact]
         public void PreservesParameterNamesAndDefaultValues()
         {
-            var implementation = this.factory.CreateImplementation<IHasDefaultValue>(this.requester.Object);
+            var implementation = this.CreateImplementation<IHasDefaultValue>();

-            var methodInfo = implementation.GetType().GetMethod("GetFooAsync");
+            var methodInfo = implementation.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Single(x => x.Name.EndsWith(".GetFooAsync"));
             var parameters = methodInfo.GetParameters();

             Assert.Equal("foo", parameters[0].Name);
@@ -43,12 +44,16 @@
             Assert.Equal("bar", parameters[1].Name);
             Assert.Equal(ParameterAttributes.Optional | ParameterAttributes.HasDefault, parameters[1].Attributes);
             Assert.Equal(3, parameters[1].DefaultValue);
+
+            Assert.Equal("baz", parameters[2].Name);
+            Assert.Equal(ParameterAttributes.Optional | ParameterAttributes.HasDefault, parameters[2].Attributes);
+            Assert.Null(parameters[2].DefaultValue);
         }

         [Fact]
         public void HandlesDefaultStructValues()
         {
-            this.factory.CreateImplementation<IHasDefaultCancellationToken>(this.requester.Object);
+            this.CreateImplementation<IHasDefaultCancellationToken>();
         }

     }


Minor change to how the environment is determined.

--- src/SFA.DAS.EmployerUsers.Web/DependencyResolution/DefaultRegistry.cs
+++ src/SFA.DAS.EmployerUsers.Web/DependencyResolution/DefaultRegistry.cs
@@ -19,6 +19,7 @@
 using System.Web;
 using MediatR;
 using Microsoft.Owin;
+using Microsoft.WindowsAzure.ServiceRuntime;
 using SFA.DAS.Configuration;
 using SFA.DAS.Configuration.AzureTableStorage;
 using SFA.DAS.EmployerUsers.Domain.Data;
@@ -48,13 +49,19 @@

         private void AddEnvironmentSpecificRegistrations()
         {
-            var environmentVariable = Environment.GetEnvironmentVariable("DASENV");
-            var environment = string.IsNullOrEmpty(environmentVariable) || environmentVariable == "__DASENV__"
-                                ? "DEV" : environmentVariable.ToUpper();
+            //var environmentVariable = Environment.GetEnvironmentVariable("DASENV");
+            //var environment = string.IsNullOrEmpty(environmentVariable) || environmentVariable == "__DASENV__"
+            //                    ? "DEV" : environmentVariable.ToUpper();
+
+            var environment = RoleEnvironment.IsEmulated ? "DEV" : "CLOUD_DEV";
+

             var configurationService = new ConfigurationService(new AzureTableStorageConfigurationRepository(),
                 new ConfigurationOptions("SFA.DAS.EmployerUsers.Web", environment, "1.0"));
             For<IConfigurationService>().Use(configurationService);
+
+
+

             if (environment == "DEV")
             {


make shorter and more readable

make shorter and more readable

--- src/ServiceStack/WebHost.Endpoints/Support/Templates/HtmlTemplates.cs
+++ src/ServiceStack/WebHost.Endpoints/Support/Templates/HtmlTemplates.cs
@@ -88,8 +88,7 @@
         {
             for (int i = 0; i < args.Length; i++)
             {
-                var currentValue = args[i] ?? String.Empty;
-                template = template.Replace(@"{" + i + "}", currentValue.ToString());
+                template = template.Replace(@"{" + i + "}", (args[i] ?? "").ToString());
             }
             return template;
         }


Improve documentation.

Improve documentation.

--- source/Nuke.Core/Build.cs
+++ source/Nuke.Core/Build.cs
@@ -13,16 +13,14 @@
 using Nuke.Core.Utilities;
 using static Nuke.Core.EnvironmentInfo;

+// ReSharper disable VirtualMemberNeverOverridden.Global
+
 namespace Nuke.Core
 {
     /// <summary>
-    /// Base class for build definitions. Use <see cref="Target"/> properties to automate tasks.
+    /// Base class for build definitions. Derived types must declare <c>static Main</c> which calls
+    /// <see cref="Execute{T}"/> for the exit code.
     /// </summary>
-    /// <remarks>
-    /// Must declare a <c>public static Main</c> which calls <see cref="Execute{T}"/> for the exit code.
-    ///
-    /// Task classes are usually statically imported, to provide a cleaner authoring.
-    /// </remarks>
     /// <example>
     /// <code>
     /// class DefaultBuild : Build


Add SourceDirectory property.

Add SourceDirectory property.

--- source/Nuke.Core/Build.cs
+++ source/Nuke.Core/Build.cs
@@ -95,5 +95,12 @@
         }

         public virtual string OutputDirectory => Path.Combine(RootDirectory, "output");
+        public virtual string ArtifactsDirectory => Path.Combine(RootDirectory, "artifacts");
+
+        [CanBeNull]
+        public virtual string SourceDirectory
+            => new[] { "src", "source" }
+                    .SelectMany(x => Directory.GetDirectories(RootDirectory, x))
+                    .FirstOrDefault();
     }
 }


Disable XmlDictionaryWriter test (#18925)

--- src/System.Runtime.Serialization.Xml/tests/XmlDictionaryWriterTest.cs
+++ src/System.Runtime.Serialization.Xml/tests/XmlDictionaryWriterTest.cs
@@ -94,6 +94,7 @@
     }

     [Fact]
+    [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Async APIs are available on NetCore only")]
     public static void XmlBaseWriter_WriteStartEndElementAsync()
     {
         string actual;


fixed merge bug

fixed merge bug

--- src/Vibrant.QuerySearch.EntityFrameworkCore/FtsQuerySearchProvider.cs
+++ src/Vibrant.QuerySearch.EntityFrameworkCore/FtsQuerySearchProvider.cs
@@ -99,7 +99,7 @@

       private string CreateBaseQuery( string term )
       {
-         return $"SELECT * FROM {GetTableName()} AS {TableAlias} INNER JOIN {GetSearchTable()}({GetTableName()}, ({string.Join( ", ", GetSearchColumns( term ) )}), {{0}} ) AS {KeyTable} ON {TableAlias}.{GetKeyColumnName()} = {KeyTable}.[KEY]";
+         return $"SELECT {TableAlias}.* FROM {GetTableName()} AS {TableAlias} INNER JOIN {GetSearchTable()}({GetTableName()}, ({string.Join( ", ", GetSearchColumns( term ) )}), {{0}} ) AS {KeyTable} ON {TableAlias}.{GetKeyColumnName()} = {KeyTable}.[KEY]";
       }

       private string CreateOrderBy( int offset, int fetch )


Remove field

Remove field

--- src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs
+++ src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs
@@ -56,7 +56,6 @@
         private readonly Shell.IAsyncServiceProvider _asyncServiceProvider;
         private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;

-        private readonly Lazy<IVsPackageInstallerServices>? _packageInstallerServices;
         private readonly Lazy<IVsPackageInstaller2>? _packageInstaller;
         private readonly Lazy<IVsPackageUninstaller>? _packageUninstaller;
         private readonly Lazy<IVsPackageSourceProvider>? _packageSourceProvider;
@@ -97,7 +96,6 @@
             SVsServiceProvider serviceProvider,
             [Import("Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider")] object asyncServiceProvider,
             IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
-            [Import(AllowDefault = true)] Lazy<IVsPackageInstallerServices>? packageInstallerServices,
             [Import(AllowDefault = true)] Lazy<IVsPackageInstaller2>? packageInstaller,
             [Import(AllowDefault = true)] Lazy<IVsPackageUninstaller>? packageUninstaller,
             [Import(AllowDefault = true)] Lazy<IVsPackageSourceProvider>? packageSourceProvider)
@@ -116,7 +114,6 @@
             _asyncServiceProvider = (Shell.IAsyncServiceProvider)asyncServiceProvider;

             _editorAdaptersFactoryService = editorAdaptersFactoryService;
-            _packageInstallerServices = packageInstallerServices;
             _packageInstaller = packageInstaller;
             _packageUninstaller = packageUninstaller;
             _packageSourceProvider = packageSourceProvider;
@@ -180,7 +177,6 @@
             return ImmutableArray<PackageSource>.Empty;
         }

-        [MemberNotNullWhen(true, nameof(_packageInstallerServices))]
         [MemberNotNullWhen(true, nameof(_packageInstaller))]
         [MemberNotNullWhen(true, nameof(_packageUninstaller))]
         [MemberNotNullWhen(true, nameof(_packageSourceProvider))]
@@ -188,8 +184,7 @@
         {
             get
             {
-                return _packageInstallerServices != null
-                    && _packageInstaller != null
+                return _packageInstaller != null
                     && _packageUninstaller != null
                     && _packageSourceProvider != null;
             }


Improvements to LCS buffer pooling (#46807)

--- src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs
+++ src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs
@@ -9,11 +9,11 @@

 namespace Microsoft.CodeAnalysis.Differencing
 {
-    /// <summary>
-    /// Calculates Longest Common Subsequence.
-    /// </summary>
-    internal abstract class LongestCommonSubsequence<TSequence>
+    internal abstract class LongestCommonSubsequence
     {
+        // Define the pool in a non-generic base class to allow sharing among instantiations.
+        private static readonly ObjectPool<VBuffer> s_pool = new ObjectPool<VBuffer>(() => new VBuffer());
+
         /// <summary>
         /// Underlying storage for <see cref="VArray"/>s allocated on <see cref="VStack"/>.
         /// </summary>
@@ -29,7 +29,7 @@
         ///
         /// We pool a few of these linked buffers on <see cref="VStack"/> to conserve allocations.
         /// </remarks>
-        private sealed class VBuffer
+        protected sealed class VBuffer
         {
             /// <summary>
             /// The max stack depth backed by the fist buffer.
@@ -44,7 +44,12 @@

             internal const int GrowFactor = 2;

-            public VBuffer Previous { get; }
+            /// <summary>
+            /// Do not pool segments that are too large.
+            /// </summary>
+            internal const int MaxPooledBufferSize = 1024 * 1024;
+
+            public VBuffer Previous { get; private set; }
             public VBuffer Next { get; private set; }

             public readonly int MinDepth;
@@ -86,6 +91,9 @@
                 return new VArray(_array, start, length);
             }

+            public bool IsTooLargeToPool
+                => _array.Length > MaxPooledBufferSize;
+
             private static int GetVArrayLength(int depth)
                 => 2 * Math.Max(depth, 1) + 1;

@@ -96,18 +104,25 @@
             // Sum { d = previousChunkDepth..maxDepth : 2*d+1 } = (maxDepth + 1)^2 - precedingBufferMaxDepth^2
             private static int GetNextBufferLength(int precedingBufferMaxDepth, int maxDepth)
                 => (maxDepth + 1) * (maxDepth + 1) - precedingBufferMaxDepth * precedingBufferMaxDepth;
-        }
-
-        private struct VStack
-        {
-            private static readonly ObjectPool<VBuffer> s_bufferPool = new ObjectPool<VBuffer>(() => new VBuffer());
+
+            public void Unlink()
+            {
+                Previous.Next = null;
+                Previous = null;
+            }
+        }
+
+        protected struct VStack
+        {
+            private readonly ObjectPool<VBuffer> _bufferPool;

             private VBuffer _currentBuffer;
             private int _depth;

-            public VStack(bool _)
-            {
-                _currentBuffer = s_bufferPool.Allocate();
+            public VStack(ObjectPool<VBuffer> bufferPool)
+            {
+                _bufferPool = bufferPool;
+                _currentBuffer = bufferPool.Allocate();
                 _depth = 0;
             }

@@ -116,6 +131,8 @@
                 var depth = _depth++;
                 if (depth > _currentBuffer.MaxDepth)
                 {
+                    // If the buffer is not big enough add another segment to the linked list (the constructor takes care of the linking).
+                    // Note that the segments are not pooled on their own. The whole linked list of buffers is pooled.
                     _currentBuffer = _currentBuffer.Next ?? new VBuffer(_currentBuffer);
                 }

@@ -129,19 +146,27 @@
                 {
                     if (depth < buffer.MinDepth)
                     {
-                        buffer = buffer.Previous;
+                        var previousBuffer = buffer.Previous;
+
+                        // Trim large buffers from the linked list before we return the whole list back into the pool.
+                        if (buffer.IsTooLargeToPool)
+                        {
+                            buffer.Unlink();
+                        }
+
+                        buffer = previousBuffer;
                     }

                     yield return (buffer.GetVArray(depth), depth);
                 }

-                s_bufferPool.Free(_currentBuffer);
+                _bufferPool.Free(_currentBuffer);
                 _currentBuffer = null;
             }
         }

         // VArray struct enables array indexing in range [-d...d].
-        private readonly struct VArray
+        protected readonly struct VArray
         {
             private readonly int[] _buffer;
             private readonly int _start;
@@ -190,6 +215,15 @@
             private int Offset => _length / 2;
         }

+        protected static VStack CreateStack()
+            => new VStack(s_pool);
+    }
+
+    /// <summary>
+    /// Calculates Longest Common Subsequence.
+    /// </summary>
+    internal abstract class LongestCommonSubsequence<TSequence> : LongestCommonSubsequence
+    {
         protected abstract bool ItemsEqual(TSequence oldSequence, int oldIndex, TSequence newSequence, int newIndex);

         // TODO: Consolidate return types between GetMatchingPairs and GetEdit to avoid duplicated code (https://github.com/dotnet/roslyn/issues/16864)
@@ -380,7 +414,7 @@
             var reachedEnd = false;
             VArray currentV = default;

-            var stack = new VStack(default);
+            var stack = CreateStack();

             for (var d = 0; d <= oldLength + newLength && !reachedEnd; d++)
             {


Simplify

Simplify

--- src/Workspaces/Core/Portable/SymbolKey/SymbolKey.PropertySymbolKey.cs
+++ src/Workspaces/Core/Portable/SymbolKey/SymbolKey.PropertySymbolKey.cs
@@ -18,10 +18,10 @@
             public static SymbolKeyResolution Resolve(SymbolKeyReader reader)
             {
                 var metadataName = reader.ReadString();
-                var containingSymbolResolution = reader.ReadSymbolKey();
+                var containingTypeResolution = reader.ReadSymbolKey();
                 var isIndexer = reader.ReadBoolean();

-                using var refKinds = reader.ReadRefKindArray();;
+                using var refKinds = reader.ReadRefKindArray(); ;
                 using var parameterTypes = reader.ReadSymbolArray<ITypeSymbol>();

                 if (refKinds.Count != parameterTypes.Count)
@@ -29,25 +29,17 @@
                     return default;
                 }

+                using var properties = GetMembersOfNamedType<IPropertySymbol>(containingTypeResolution, metadataNameOpt: null);
                 using var result = PooledArrayBuilder<IPropertySymbol>.GetInstance();
-                foreach (var containingSymbol in containingSymbolResolution)
+                foreach (var property in properties)
                 {
-                    if (containingSymbol is INamedTypeSymbol containingNamedType)
+                    if (property.Parameters.Length == refKinds.Count &&
+                        property.MetadataName == metadataName &&
+                        property.IsIndexer == isIndexer &&
+                        ParameterRefKindsMatch(property.OriginalDefinition.Parameters, refKinds) &&
+                        reader.ParameterTypesMatch(property.OriginalDefinition.Parameters, parameterTypes))
                     {
-                        foreach (var member in containingNamedType.GetMembers())
-                        {
-                            if (member is IPropertySymbol property)
-                            {
-                                if (property.Parameters.Length == refKinds.Count &&
-                                    property.MetadataName == metadataName &&
-                                    property.IsIndexer == isIndexer &&
-                                    ParameterRefKindsMatch(property.OriginalDefinition.Parameters, refKinds) &&
-                                    reader.ParameterTypesMatch(property.OriginalDefinition.Parameters, parameterTypes))
-                                {
-                                    result.AddIfNotNull(property);
-                                }
-                            }
-                        }
+                        result.AddIfNotNull(property);
                     }
                 }


[packages,tinyxml2,4.0.1] Fixes for BAM V2's preprocessor support

--- packages/tinyxml2-4.0.1/bam/Scripts/TinyXML2.cs
+++ packages/tinyxml2-4.0.1/bam/Scripts/TinyXML2.cs
@@ -77,9 +77,9 @@

             this.PublicPatch((settings, appliedTo) =>
                 {
-                    if (settings is C.ICommonCompilerSettings compiler)
+                    if (settings is C.ICommonPreprocessorSettings preprocessor)
                     {
-                        compiler.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)"));
+                        preprocessor.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)"));
                     }
                 });
         }
@@ -101,7 +101,7 @@
             var source = this.CreateCxxSourceContainer("$(packagedir)/tinyxml2.cpp");
             source.PrivatePatch(settings =>
                 {
-                    var compiler = settings as C.ICommonCompilerSettings;
+                    var preprocessor = settings as C.ICommonPreprocessorSettings;
                     var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
                     cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
                     cxxCompiler.LanguageStandard = C.Cxx.ELanguageStandard.Cxx11;
@@ -109,7 +109,7 @@
                     if (settings is VisualCCommon.ICommonCompilerSettings visualCCompiler)
                     {
                         visualCCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level4;
-                        compiler.PreprocessorDefines.Add("TINYXML2_EXPORT");
+                        preprocessor.PreprocessorDefines.Add("TINYXML2_EXPORT");
                     }

                     if (settings is MingwCommon.ICommonCompilerSettings mingwCompiler)
@@ -117,7 +117,7 @@
                         mingwCompiler.AllWarnings = true;
                         mingwCompiler.ExtraWarnings = true;
                         mingwCompiler.Pedantic = true;
-                        compiler.PreprocessorDefines.Add("TINYXML2_EXPORT");
+                        preprocessor.PreprocessorDefines.Add("TINYXML2_EXPORT");
                     }

                     if (settings is GccCommon.ICommonCompilerSettings gccCompiler)
@@ -141,13 +141,13 @@

             this.PublicPatch((settings, appliedTo) =>
                 {
-                    if (settings is C.ICommonCompilerSettings compiler)
+                    if (settings is C.ICommonPreprocessorSettings preprocessor)
                     {
-                        compiler.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)"));
+                        preprocessor.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)"));
                         if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows) && appliedTo != this)
                         {
                             // applied everywhere it's not built
-                            compiler.PreprocessorDefines.Add("TINYXML2_IMPORT");
+                            preprocessor.PreprocessorDefines.Add("TINYXML2_IMPORT");
                         }
                     }
                 });


Fixes: U4-6796 BackOfficeIdentity gets assigned inadvertently for front-end requests if using ui.Text to localize

--- src/umbraco.businesslogic/BasePages/BasePage.cs
+++ src/umbraco.businesslogic/BasePages/BasePage.cs
@@ -6,6 +6,7 @@
 using System.Web.Mvc;
 using System.Web.Routing;
 using System.Web.Security;
+using System.Web.UI;
 using Umbraco.Core;
 using Umbraco.Core.Configuration;
 using Umbraco.Core.IO;
@@ -181,7 +182,14 @@
         /// <returns></returns>
         public static int GetUserId()
         {
-            var identity = HttpContext.Current.GetCurrentIdentity(true);
+            var identity = HttpContext.Current.GetCurrentIdentity(
+                //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS!
+                // Without this check, anything that is using this legacy API, like ui.Text will
+                // automatically log the back office user in even if it is a front-end request (if there is
+                // a back office user logged in. This can cause problems becaues the identity is changing mid
+                // request. For example: http://issues.umbraco.org/issue/U4-4010
+                HttpContext.Current.CurrentHandler is Page);
+
             if (identity == null)
                 return -1;
             return Convert.ToInt32(identity.Id);
@@ -205,7 +213,14 @@
         /// <returns></returns>
         public static bool ValidateCurrentUser()
         {
-            var identity = HttpContext.Current.GetCurrentIdentity(true);
+            var identity = HttpContext.Current.GetCurrentIdentity(
+                //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS!
+                // Without this check, anything that is using this legacy API, like ui.Text will
+                // automatically log the back office user in even if it is a front-end request (if there is
+                // a back office user logged in. This can cause problems becaues the identity is changing mid
+                // request. For example: http://issues.umbraco.org/issue/U4-4010
+                HttpContext.Current.CurrentHandler is Page);
+
             if (identity != null)
             {
                 return true;
@@ -232,7 +247,14 @@
         {
             get
             {
-                var identity = HttpContext.Current.GetCurrentIdentity(true);
+                var identity = HttpContext.Current.GetCurrentIdentity(
+                    //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS!
+                    // Without this check, anything that is using this legacy API, like ui.Text will
+                    // automatically log the back office user in even if it is a front-end request (if there is
+                    // a back office user logged in. This can cause problems becaues the identity is changing mid
+                    // request. For example: http://issues.umbraco.org/issue/U4-4010
+                    HttpContext.Current.CurrentHandler is Page);
+
                 return identity == null ? "" : identity.SessionId;
             }
             set


Fix: The redirect url of crowdfund invoices wasn't set correctly if rootpath is used (Fix #2992)

--- BTCPayServer/Controllers/AppsPublicController.cs
+++ BTCPayServer/Controllers/AppsPublicController.cs
@@ -377,7 +377,7 @@
                     ExtendedNotifications = true,
                     SupportedTransactionCurrencies = paymentMethods,
                     RedirectURL = request.RedirectUrl ??
-                                     new Uri(new Uri(new Uri(HttpContext.Request.GetAbsoluteRoot()), _BtcPayServerOptions.RootPath), $"apps/{appId}/crowdfund").ToString()
+                                     HttpContext.Request.GetAbsoluteUri($"/apps/{appId}/crowdfund")
                 }, store, HttpContext.Request.GetAbsoluteRoot(),
                     new List<string> { AppService.GetAppInternalTag(appId) },
                     cancellationToken: cancellationToken);


Remove dollar sign in textbox

Remove dollar sign in textbox

--- BTCPayServer/Views/Apps/UpdatePointOfSale.cshtml
+++ BTCPayServer/Views/Apps/UpdatePointOfSale.cshtml
@@ -154,12 +154,7 @@

                 Price*
-

-

-
-

-                    <input type="text" class="js-product-price form-control" value="{price}" />
-

+                <input type="text" class="js-product-price form-control mb-2" value="{price}" />

                 Custom price


Make more robust + use the right semantic model

--- CConst/CConst/InvocationInConstMethodAnalyzer.cs
+++ CConst/CConst/InvocationInConstMethodAnalyzer.cs
@@ -33,13 +33,16 @@
             if (containingMethod.HasConstAttribute(context.SemanticModel))
             {
                 var invokedMethod = invocation.GetInvokedMethod(context.SemanticModel);
-                var model = context.SemanticModel.Compilation.GetSemanticModel(invokedMethod.SyntaxTree);
-                if (!invokedMethod.HasConstAttribute(model))
+                if (invokedMethod != null)
                 {
-                    context.ReportDiagnostic(Diagnostic.Create(Rule,
-                        invocation.GetLocation(),
-                        context.SemanticModel.GetDeclaredSymbol(containingMethod)?.Name,
-                        model.GetSymbolInfo(invocation).Symbol?.Name));
+                    var model = context.SemanticModel.Compilation.GetSemanticModel(invokedMethod.SyntaxTree);
+                    if (!invokedMethod.HasConstAttribute(model))
+                    {
+                        context.ReportDiagnostic(Diagnostic.Create(Rule,
+                            invocation.GetLocation(),
+                            context.SemanticModel.GetDeclaredSymbol(containingMethod)?.Name,
+                            context.SemanticModel.GetSymbolInfo(invocation).Symbol?.Name));
+                    }
                 }
             }
         }


Simplified A*

Simplified A*

--- AStar/PathSeeker.cs
+++ AStar/PathSeeker.cs
@@ -7,25 +7,57 @@
 public class PathSeeker : MonoBehaviour {

 	public PathFinder _pathFinder = null;
+	public WeightedPathFinder _wPathFinder = null;
 	public int Steps = 5;
+
+	public float GridScale = 1f;
+	public Vector3 GridPosition = Vector3.zero;
+
+	public delegate void OnPathDelegate(LinkedList<Pathfinding.IPathNode<Object>> path);
+	public OnPathDelegate pathCallback;
+

 	void Reset() {
 		if (_pathFinder == null)
-			_pathFinder = GameObject.Find("Game").GetComponent<PathFinder>();
+			_pathFinder = GetComponent<PathFinder>();
+		if (_wPathFinder == null)
+			_wPathFinder = GetComponent<WeightedPathFinder>();
 	}

-	public LinkedList<Pathfinding.EPathNode> Path(Vector2i gridPos, Vector2i targetGridPos) {
-		return _pathFinder.FindPath(gridPos, targetGridPos);
-	}
+//	public LinkedList<Pathfinding.IPathNode<Object>> Path(Vector3 worldPos, Vector3 targetWorldPos) {
+//		Vector3 gp = worldPos * GridScale - GridPosition;
+//		Vector3 tgp = targetWorldPos * GridScale - GridPosition;
+//		Vector2i gridPos = new Vector2i(gp.x, gp.y);
+//		Vector2i targetGridPos = new Vector2i(tgp.x, tgp.y);
+//		return Path(gridPos, targetGridPos);
+//	}
+
+//	public LinkedList<Pathfinding.IPathNode<Object>> Path(Vector2i gridPos, Vector2i targetGridPos) {
+//		LinkedList<Pathfinding.IPathNode<Object>> path;
+//
+//		if (_wPathFinder != null)
+//			path = _wPathFinder.FindPath(gridPos, targetGridPos);
+//		else
+//			path = _pathFinder.FindPath(gridPos, targetGridPos);
+//		pathCallback(path);
+//
+//		return path;
+//	}

 	public void SetGrid(bool[,] grid) {
 		int w = grid.GetLength(0);
 		int h = grid.GetLength(1);
 		for (int x=0; x<w; ++x) {
 			for (int y=0; y<h; ++y) {
-				_pathFinder.SetPathNode(x,y,grid[x,y]);
+				if (_wPathFinder != null)
+					_wPathFinder.SetPathNode(x,y,grid[x,y]);
+				else
+					_pathFinder.SetPathNode(x,y,grid[x,y]);
 			}
 		}
-		_pathFinder.UpdateGrid();
+		if (_wPathFinder != null)
+			_wPathFinder.UpdateGrid();
+		else
+			_pathFinder.UpdateGrid();
 	}
 }


[AE-480]: We are getting refId as null in email log, so changed the data type from int to nullable int (int?).

--- Account/EmailLog.cs
+++ Account/EmailLog.cs
@@ -127,7 +127,7 @@
         public EmailTypes EmailType { get; set; }

         [JsonProperty("refId")]
-        public int RefId { get; set; }
+        public int? RefId { get; set; }

         [JsonProperty("from")]
         public string FromAddress { get; set; }


Removed if condition from error view

Removed if condition from error view

--- CmsEngine.Ui/Areas/Cms/Views/Shared/Error.cshtml
+++ CmsEngine.Ui/Areas/Cms/Views/Shared/Error.cshtml
@@ -6,13 +6,6 @@

Error.

An error occurred while processing your request.

-@if (Model.ShowRequestId)
-{
-

-      Request ID: @Model.RequestId
-

-}
-

Development Mode

   Swapping to Development environment will display more detailed information about the error that occurred.


Small performance fixes

Small performance fixes

* Use Any() instead of COunt() == 0
* Use || instead of |

--- CIV/Program.cs
+++ CIV/Program.cs
@@ -40,14 +40,14 @@
             for (int i = 0; i < moves; i++)
             {
                 var transitions = start.Transitions();
-                if (transitions.Count() == 0)
+                if (!transitions.Any())
                 {
                     break;
                 }
                 int index = rand.Next(0, transitions.Count());
                 var nextTransition = transitions.ElementAt(index);
                 start = nextTransition.Process;
-                if (nextTransition.Label != "tau" | printTau)
+                if (nextTransition.Label != "tau" || printTau)
                 {
                     Console.WriteLine(
                         String.Format("{0:000}: {1}", i, nextTransition.Label));


Rethrow all exceptions. Added comments

Rethrow all exceptions. Added comments

--- Cqrs.Portable/TapeStorage/FileAppendOnlyStore.cs
+++ Cqrs.Portable/TapeStorage/FileAppendOnlyStore.cs
@@ -120,11 +120,16 @@
             }
             catch (AppendOnlyStoreConcurrencyException)
             {
+                //store is OK when AOSCE is thrown. This is client's problem
+                // just bubble it upwards
                 throw;
             }
             catch
             {
+                // store probably corrupted. Close it and then rethrow exception
+                // so that clien will have a chance to retry.
                 Close();
+                throw;
             }
             finally
             {


adding comments to NwndSvc.cs

adding comments to NwndSvc.cs

--- App_Code/NwndSvc.cs
+++ App_Code/NwndSvc.cs
@@ -229,6 +229,11 @@
     return eList;
   }

+  /// <summary>
+  /// Add a new employee.
+  /// </summary>
+  /// <param name="employee">new employee to add</param>
+  /// <returns>updated list of employee information</returns>
   [WebMethod]
   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
   public List<DA.Employee> AddEmployee(DA.Employee employee)
@@ -294,6 +299,11 @@
     return e;
   }

+  /// <summary>
+  /// Delete the employee with the given id.
+  /// </summary>
+  /// <param name="id">employee id</param>
+  /// <returns>updated list of employee information</returns>
   [WebMethod]
   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
   public List<DA.Employee> DeleteEmployee(int id)


testing

testing

--- DSACharacterSheet.Desktop/Settings/UpdateInfo.cs
+++ DSACharacterSheet.Desktop/Settings/UpdateInfo.cs
@@ -1,4 +1,5 @@
-using System;
+using DSACharacterSheet.Desktop.Dialogs;
+using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Deployment.Application;
@@ -68,8 +69,9 @@

                 return true;
             }
-            catch (Exception)
+            catch (Exception e)
             {
+                new ExceptionMessageBox(e, "test").Show();
                 return false;
             }
         }


add available languages list

add available languages list

--- src/ApisFlorea.WebApp/Controllers/SlashCommandsController.cs
+++ src/ApisFlorea.WebApp/Controllers/SlashCommandsController.cs
@@ -33,9 +33,32 @@
             if (request.Command != "/translate")
                 return this.HttpBadRequest();

-            //--- コマンド引数解析
+            //--- 引数解析 (翻訳可能一覧)
+            var commands = request.Text.Split(' ');
+            if (commands.Any() && commands[0].ToLower() == "list")
+            {
+                return this.Json(new Message
+                {
+                    Text = "*翻訳可能な言語一覧*",
+                    IsEphemeral = true,
+                    IsMarkdown = true,
+                    Attachments = new []
+                    {
+                        new Attachment
+                        {
+                            Fields = Language.All.Select(x => new Field
+                            {
+                                Title = x.Name,
+                                Value = x.ShortName,
+                                IsShort = true,
+                            })
+                            .ToArray(),
+                        },
+                    },
+                }, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
+            }
+
             const int MinLength = 2;
-            var commands = request.Text.Split(' ');
             if (commands.Length < MinLength)
                 return this.HttpBadRequest();

@@ -123,5 +146,12 @@
             }, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
         }
         #endregion
+
+
+        public async Task<IActionResult> Test()
+        {
+            var result = await new GoogleTranslator().TranslateAsync(Language.Japanese, "Hello");
+            return this.Json(result);
+        }
     }
 }


be strict to call AspNetCoreHttpContext.Current.

--- src/AspNetCoreCurrentRequestContext/AspNetCoreHttpContext.cs
+++ src/AspNetCoreCurrentRequestContext/AspNetCoreHttpContext.cs
@@ -1,4 +1,5 @@
 using Microsoft.AspNetCore.Http;
+using System;
 using System.Threading;

 namespace AspNetCoreCurrentRequestContext
@@ -15,7 +16,15 @@
         /// </summary>
         public static HttpContext Current
         {
-            get { return _context.Value; }
+            get
+            {
+                if (_context.Value == null)
+                {
+                    throw new InvalidOperationException($"Could not acuire {nameof(HttpContext)} in the current request. You may not add {nameof(CurrentRequestContextMiddleware)} in Startup.");
+                }
+
+                return _context.Value;
+            }
             internal set { _context.Value = value; }
         }
     }


Fixing more broken field_values.

Fixing more broken field_values.

--- eFormCore/Infrastructure/SqlController.cs
+++ eFormCore/Infrastructure/SqlController.cs
@@ -1463,6 +1463,16 @@
                                 _field.FieldValues = new List<Models.FieldValue>();
                                 _field.Label = fieldTranslation.Text;
                                 _field.Description = new CDataValue {InderValue = fieldTranslation.Description};
+                                if (!db.FieldValues.Any(x => x.FieldId == field.Id && x.CaseId == theCase.Id))
+                                {
+                                    FieldValue fieldValue = new FieldValue()
+                                    {
+                                        FieldId = field.Id,
+                                        CaseId = theCase.Id,
+                                        DoneAt = theCase.DoneAt
+                                    };
+                                    await fieldValue.Create(db);
+                                }
                                 foreach (FieldValue fieldValue in await db.FieldValues.Where(x =>
                                     x.FieldId == subField.Id && x.CaseId == theCase.Id).ToListAsync())
                                 {


Updated DocIDPriorityQueue.cs to 4.0.2 compatibility.

--- src/BoboBrowse.Net/BoboBrowse.Net/Sort/DocIDPriorityQueue.cs
+++ src/BoboBrowse.Net/BoboBrowse.Net/Sort/DocIDPriorityQueue.cs
@@ -17,16 +17,14 @@
 //* See the License for the specific language governing permissions and
 //* limitations under the License.

-// Version compatibility level: 3.2.0
+// Version compatibility level: 4.0.2
 namespace BoboBrowse.Net.Sort
 {
-    using Common.Logging;
     using Lucene.Net.Search;
     using System;

     public class DocIDPriorityQueue
     {
-        private static readonly ILog logger = LogManager.GetLogger(typeof(DocIDPriorityQueue));
         public int size;
         protected readonly ScoreDoc[] heap;
         public readonly int @base;


Remove vestigial name code

Remove vestigial name code

--- AimlPlugin.cs
+++ AimlPlugin.cs
@@ -53,7 +53,7 @@
                     return "Good talk, " + line.User;
                 }
             }
-            else if(Enumerable.Any(_config.StartTriggers, trigger => trigger.Matches(line.Raw)))
+            else if(_config.StartTriggers.Any(trigger => trigger.Matches(line.Raw)))
             {
                 _conversing = true;
                 return _bot.Respond(line.Raw, _users[line.User]) + " [By the way, if my chattering starts to get annoying, you can type 'Stop Talking' and I might.]";
@@ -61,8 +61,6 @@

             if(_conversing)
             {
-                _bot.DefaultPredicates.updateSetting("name", line.User);
-
                 return _bot.Respond(line.Raw, _users[line.User]);
             }


Fix bug which throws exception when writing to stream journal with SingleTransferCheckpoint under updating.

--- lib/TransferJobs/SingleObjectCheckpoint.cs
+++ lib/TransferJobs/SingleObjectCheckpoint.cs
@@ -46,11 +46,29 @@
         }

 #if !BINARY_SERIALIZATION
+        [DataMember]
+        private long entryTransferOffset = 0;
+
+        [DataMember]
+        private List<long> transferWindow = new List<long>();
+
+        [OnSerializing]
+        private void OnSerializingCallback(StreamingContext context)
+        {
+            lock (this.TransferWindowLock)
+            {
+                entryTransferOffset = this.EntryTransferOffset;
+                transferWindow = new List<long>(this.TransferWindow);
+            }
+        }
+
         [OnDeserialized]
         private void OnDeserializedCallback(StreamingContext context)
         {
             // Constructors aren't called by DCS, so initialize non-serialized members here
             this.TransferWindowLock = new object();
+            this.EntryTransferOffset = this.entryTransferOffset;
+            this.TransferWindow = new List<long>(this.transferWindow);
         }
 #endif

@@ -58,9 +76,6 @@
         /// Gets or sets transferred offset of this transfer entry.
         /// </summary>
         /// <value>Transferred offset of this transfer entry.</value>
-#if !BINARY_SERIALIZATION
-        [DataMember]
-#endif
         public long EntryTransferOffset
         {
             get;
@@ -71,9 +86,6 @@
         /// Gets or sets transfer window of this transfer entry.
         /// </summary>
         /// <value>Transfer window of this transfer entry.</value>
-#if !BINARY_SERIALIZATION
-        [DataMember]
-#endif
         public List<long> TransferWindow
         {
             get;


Added files via upload

Added files via upload

--- AutoBudget.cs
+++ AutoBudget.cs
@@ -1,262 +1,257 @@
-using System;
+using ColossalFramework;
+using ICities;
+using System;
 using System.Diagnostics;
-
-using ColossalFramework;
-using ColossalFramework.Plugins;
-
-using ICities;
-
 using UnityEngine;
-
 using Debug = UnityEngine.Debug;

 namespace AutoBudget
-{
-	public class BudgetMod : IUserMod
-	{
-		#region Implementation of IUserMod
-
-		public string Name { get { return "AutoBudget"; } }
-		public string Description { get { return "Automatically sets budgets to the lowest possible value to maintain a 'green' status for electricity and water/sewage."; } }
-
-		#endregion
-	}
-
-	public class AutoBudget : ThreadingExtensionBase
-	{
-		public static int GetProductionRate(int productionRate, int budget)
-		{
-			if (budget < 100)
-				budget = (budget * budget + 99) / 100;
-			else if (budget > 150)
-				budget = 125;
-			else if (budget > 100)
-				budget -= (100 - budget) * (100 - budget) / 100;
-			return (productionRate * budget + 99) / 100;
-		}
-
-		private void DebugMessage(string message)
-		{
-			Debug.Log(message);
-			//DebugOutputPanel.AddMessage(PluginManager.MessageType.Warning, message);
-		}
-
-		private delegate int CapacityGetter<in TAI>(ref Building building, TAI ai);
-		int GetTotalCapacity<TAI>(ItemClass.Service service, CapacityGetter<TAI> getter) where TAI: PlayerBuildingAI
-		{
-			int capacity = 0;
-
-			var serviceBuildings = BuildingManager.instance.GetServiceBuildings(service);
-
-			if (serviceBuildings == null || serviceBuildings.m_buffer == null || serviceBuildings.m_size > serviceBuildings.m_buffer.Length)
-				return 0;
-
-			var buildings = serviceBuildings.m_buffer;
-			for (int i = 0; i < serviceBuildings.m_size; i++)
-			{
-				if (buildings[i] == 0)
-					continue;
-				var b = BuildingManager.instance.m_buildings.m_buffer[buildings[i]];
-
-				// Building is not active. Ignore it.
-				if ((b.m_flags & Building.Flags.Active) == 0)
-					continue;
-				var ai = b.Info.m_buildingAI as TAI;
-				if (ai != null)
-				{
-					capacity += getter(ref BuildingManager.instance.m_buildings.m_buffer[buildings[i]], ai);
-				}
-			}
-			return capacity;
-		}
-
-		private void UpdateBudget(EconomyManager eco, ref District district, ItemClass.Service service, ItemClass.SubService subService = ItemClass.SubService.None)
-		{
-			try
-			{
-				int capacity = 0;
-				int consumption = 0;
-				switch (service)
-				{
-					case ItemClass.Service.Electricity:
-						//capacity = (int) district.m_productionData.m_tempElectricityCapacity * 16;
-						capacity = GetTotalCapacity(ItemClass.Service.Electricity,
-							(ref Building data, PowerPlantAI ai) =>
-							{
-								int min;
-								int max;
-								ai.GetElectricityProduction(out min, out max);
-								if (ai is WindTurbineAI)
-								{
-									// Get the wind for the specific area.
-									var turbineProduction = Mathf.RoundToInt(PlayerBuildingAI.GetProductionRate(data.m_productionRate, 100) * WeatherManager.instance.SampleWindSpeed(data.m_position,true));
-									return turbineProduction * max / 100;
-								}
-								if (ai is DamPowerHouseAI)
-								{
-									var damProduction = (data.m_productionRate * 100 / 100 * data.GetLastFrameData().m_productionState + 99) / 100;
-									return damProduction * max / 100;
-								}
-								if (ai is FusionPowerPlantAI)
-								{
-									max = 1000000;
-								}
-								int a;
-								var productionRate = data.m_productionRate;
-								if ((data.m_flags & Building.Flags.Active) != Building.Flags.None)
-								{
-									a = PlayerBuildingAI.GetProductionRate(productionRate, 100);
-									if (ai.m_resourceType != TransferManager.TransferReason.None)
-									{
-										int num = (int) data.m_customBuffer1;
-										a = Mathf.Min(a, num / (ai.m_resourceCapacity / 400) + 10);
-									}
-								}
-								else
-									a = 0;
-
-								return a * max / 100;
-							}) * 16;
-
-
-						// Now check for incinerators, as they also add to our max capacity!!!
-						capacity += GetTotalCapacity(ItemClass.Service.Garbage,
-							(ref Building data, LandfillSiteAI ai) =>
-							{
-								if (ai.m_electricityProduction != 0)
-								{
-									var ret =
-										(Mathf.Min(PlayerBuildingAI.GetProductionRate(data.m_productionRate, 100),
-											(data.m_customBuffer1 * 1000 + data.m_garbageBuffer) / (ai.m_garbageCapacity / 200)) * ai.m_electricityProduction + 99) / 100;
-									return ret;
-								}
-								return 0;
-							}) * 16;
-
-						consumption = district.GetElectricityConsumption();
-						break;
-					case ItemClass.Service.Water:
-						var sewageConsumption = district.GetSewageAccumulation();
-						var waterConsumption = district.GetWaterConsumption();
-						var waterCapacity = GetTotalCapacity(ItemClass.Service.Water,
-							(ref Building data, WaterFacilityAI ai) =>
-							{
-								if (ai.m_waterIntake == 0)
-									return 0;
-
-								if (ai.m_useGroundWater || data.m_waterSource != 0)
-									return ai.m_waterIntake * data.m_productionRate / 100;
-								return 0;
-							}) * 16;
-						var sewageCapacity = GetTotalCapacity(ItemClass.Service.Water,
-							(ref Building data, WaterFacilityAI ai) =>
-							{
-								if (ai.m_sewageOutlet == 0)
-									return 0;
-
-								if (ai.m_useGroundWater || data.m_waterSource != 0)
-									return ai.m_sewageOutlet * data.m_productionRate / 100;
-								return 0;
-							}) * 16;
-
-						// Use the higher consumption here so we get accurate results
-						// The water/sewage is tied together on the same budget.
-						if (GetPercentage(waterCapacity, waterConsumption) > GetPercentage(sewageCapacity, sewageConsumption))
-						{
-							capacity = sewageCapacity;
-							consumption = sewageConsumption;
-						}
-						else
-						{
-							capacity = waterCapacity;
-							consumption = waterConsumption;
-						}
-
-						break;
-					case ItemClass.Service.Garbage:
-						capacity = (int) district.m_productionData.m_tempIncinerationCapacity * 16;
-						consumption = district.GetGarbageAccumulation();
-						break;
-				}
-
-
-				if (capacity == 0 || consumption == 0)
-					return;
-
-				int budget;
-				for (budget = 1; budget < 150; budget++)
-				{
-					if (GetProductionRate(capacity, budget) >= consumption)
-						break;
-				}
-
-				// How much of our capacity do we need to meet our demands?
-				// This is odd for water specifically.
-				var neededUsage = (int)Math.Ceiling(((float)consumption / capacity) * 100);
-				DebugMessage("Service: " + service + ", Capacity: " + capacity + ", Consumption: " + consumption + ", Budget: " + budget +", Needed: " + neededUsage);
+{
+  public class BudgetMod : IUserMod
+  {
+    #region Implementation of IUserMod
+
+    public string Name { get { return "AutoBudget"; } }
+    public string Description { get { return "Automatically sets budgets to the lowest possible value to maintain a 'green' status for electricity and water/sewage."; } }
+
+    #endregion Implementation of IUserMod
+  }
+
+  public class AutoBudget : ThreadingExtensionBase
+  {
+    public static int GetProductionRate(int productionRate, int budget)
+    {
+      if (budget < 100)
+        budget = (budget * budget + 99) / 100;
+      else if (budget > 150)
+        budget = 125;
+      else if (budget > 100)
+        budget -= (100 - budget) * (100 - budget) / 100;
+      return (productionRate * budget + 99) / 100;
+    }
+
+    private void DebugMessage(string message)
+    {
+      Debug.Log(message);
+    }
+
+    private delegate int CapacityGetter<in TAI>(ref Building building, TAI ai);
+
+    private int GetTotalCapacity<TAI>(ItemClass.Service service, CapacityGetter<TAI> getter) where TAI : PlayerBuildingAI
+    {
+      int capacity = 0;
+
+      var serviceBuildings = BuildingManager.instance.GetServiceBuildings(service);
+
+      if (serviceBuildings == null || serviceBuildings.m_buffer == null || serviceBuildings.m_size > serviceBuildings.m_buffer.Length)
+        return 0;
+
+      var buildings = serviceBuildings.m_buffer;
+      for (int i = 0; i < serviceBuildings.m_size; i++)
+      {
+        if (buildings[i] == 0)
+          continue;
+        var b = BuildingManager.instance.m_buildings.m_buffer[buildings[i]];
+
+        // Building is not active. Ignore it.
+        if ((b.m_flags & Building.Flags.Active) == 0)
+          continue;
+        var ai = b.Info.m_buildingAI as TAI;
+        if (ai != null)
+        {
+          capacity += getter(ref BuildingManager.instance.m_buildings.m_buffer[buildings[i]], ai);
+        }
+      }
+      return capacity;
+    }
+
+    private void UpdateBudget(EconomyManager eco, ref District district, ItemClass.Service service, ItemClass.SubService subService = ItemClass.SubService.None)
+    {
+      try
+      {
+        int capacity = 0;
+        int consumption = 0;
+        switch (service)
+        {
+          case ItemClass.Service.Electricity:
+            capacity = GetTotalCapacity(ItemClass.Service.Electricity,
+              (ref Building data, PowerPlantAI ai) =>
+              {
+                int min;
+                int max;
+                ai.GetElectricityProduction(out min, out max);
+                if (ai is WindTurbineAI)
+                {
+                  // Get the wind for the specific area.
+                  var turbineProduction = Mathf.RoundToInt(PlayerBuildingAI.GetProductionRate(data.m_productionRate, 100) * WeatherManager.instance.SampleWindSpeed(data.m_position, true));
+                  return turbineProduction * max / 100;
+                }
+                if (ai is DamPowerHouseAI)
+                {
+                  var damProduction = (data.m_productionRate * 100 / 100 * data.GetLastFrameData().m_productionState + 99) / 100;
+                  return damProduction * max / 100;
+                }
+                if (ai is FusionPowerPlantAI)
+                {
+                  max = 1000000;
+                }
+                int a;
+                var productionRate = data.m_productionRate;
+                if ((data.m_flags & Building.Flags.Active) != Building.Flags.None)
+                {
+                  a = PlayerBuildingAI.GetProductionRate(productionRate, 100);
+                  if (ai.m_resourceType != TransferManager.TransferReason.None)
+                  {
+                    int num = (int)data.m_customBuffer1;
+                    a = Mathf.Min(a, num / (ai.m_resourceCapacity / 400) + 10);
+                  }
+                }
+                else
+                  a = 0;
+
+                return a * max / 100;
+              }) * 16;
+
+            // Now check for incinerators, as they also add to our max capacity!!!
+            capacity += GetTotalCapacity(ItemClass.Service.Garbage,
+              (ref Building data, LandfillSiteAI ai) =>
+              {
+                if (ai.m_electricityProduction != 0)
+                {
+                  var ret =
+                    (Mathf.Min(PlayerBuildingAI.GetProductionRate(data.m_productionRate, 100),
+                      (data.m_customBuffer1 * 1000 + data.m_garbageBuffer) / (ai.m_garbageCapacity / 200)) * ai.m_electricityProduction + 99) / 100;
+                  return ret;
+                }
+                return 0;
+              }) * 16;
+
+            consumption = district.GetElectricityConsumption();
+            break;
+
+          case ItemClass.Service.Water:
+            var sewageConsumption = district.GetSewageAccumulation();
+            var waterConsumption = district.GetWaterConsumption();
+            var waterCapacity = GetTotalCapacity(ItemClass.Service.Water,
+              (ref Building data, WaterFacilityAI ai) =>
+              {
+                if (ai.m_waterIntake == 0)
+                  return 0;
+
+                if (ai.m_useGroundWater || data.m_waterSource != 0)
+                  return ai.m_waterIntake * data.m_productionRate / 100;
+                return 0;
+              }) * 16;
+            var sewageCapacity = GetTotalCapacity(ItemClass.Service.Water,
+              (ref Building data, WaterFacilityAI ai) =>
+              {
+                if (ai.m_sewageOutlet == 0)
+                  return 0;
+
+                if (ai.m_useGroundWater || data.m_waterSource != 0)
+                  return ai.m_sewageOutlet * data.m_productionRate / 100;
+                return 0;
+              }) * 16;
+
+            // Use the higher consumption here so we get accurate results
+            // The water/sewage is tied together on the same budget.
+            if (GetPercentage(waterCapacity, waterConsumption) > GetPercentage(sewageCapacity, sewageConsumption))
+            {
+              capacity = sewageCapacity;
+              consumption = sewageConsumption;
+            }
+            else
+            {
+              capacity = waterCapacity;
+              consumption = waterConsumption;
+            }
+
+            break;
+
+          case ItemClass.Service.Garbage:
+            capacity = (int)district.m_productionData.m_tempIncinerationCapacity * 16;
+            consumption = district.GetGarbageAccumulation();
+            break;
+        }
+
+        if (capacity == 0 || consumption == 0)
+          return;
+
+        int budget;
+        for (budget = 1; budget < 150; budget++)
+        {
+          if (GetProductionRate(capacity, budget) >= consumption)
+            break;
+        }
+
+        // How much of our capacity do we need to meet our demands?
+        // This is odd for water specifically.
+        var neededUsage = (int)Math.Ceiling(((float)consumption / capacity) * 100);
+        DebugMessage("Service: " + service + ", Capacity: " + capacity + ", Consumption: " + consumption + ", Budget: " + budget + ", Needed: " + neededUsage);

         // Add 2% to the required amount so we don't end up with crazy stuff happening
         // When there are big "booms" in player buildings.
         eco.SetBudget(service, subService, Clamp(budget + 2, 10, 150), false);
-        eco.SetBudget(service, subService, Clamp(budget + 2, 10, 150), true);
-      }
-			catch (Exception ex)
-			{
-				Debug.LogException(ex);
-			}
-		}
-
-		private int Clamp(int val, int min, int max)
-		{
-			if (val < min)
-			{
-				val = min;
-			}
-			if (val > max)
-			{
-				val = max;
-			}
-			return val;
-		}
-		private float GetPercentage(int capacity, int consumption, int consumptionMin = 45, int consumptionMax = 55)
-		{
-			if (capacity == 0)
-			{
-				return 0f;
-			}
-			float pct = capacity / (float)consumption;
-			float mod = (consumptionMin + (float)consumptionMax) / 2;
-			return pct * mod;
-		}
-
-		#region Overrides of ThreadingExtensionBase
-
-		private readonly Stopwatch _throttle = Stopwatch.StartNew();
-
-		public override void OnAfterSimulationTick()
-		{
-			base.OnAfterSimulationTick();
-
-			// Probably not in a normal game type if the district manager doesn't actually exist.
-			if (!Singleton<DistrictManager>.exists)
-			{
-				return;
-			}
-
-			if (_throttle.ElapsedMilliseconds < 1000)
-			{
-				return;
-			}
-
-			var eco = Singleton<EconomyManager>.instance;
-
-			UpdateBudget(eco, ref Singleton<DistrictManager>.instance.m_districts.m_buffer[0], ItemClass.Service.Electricity);
-			UpdateBudget(eco, ref Singleton<DistrictManager>.instance.m_districts.m_buffer[0], ItemClass.Service.Water);
-
-			_throttle.Reset();
-			_throttle.Start();
-		}
-
-		#endregion
-	}
+        //eco.SetBudget(service, subService, Clamp(budget + 2, 10, 150), true);
+      }
+      catch (Exception ex)
+      {
+        Debug.LogException(ex);
+      }
+    }
+
+    private int Clamp(int val, int min, int max)
+    {
+      if (val < min)
+      {
+        val = min;
+      }
+      if (val > max)
+      {
+        val = max;
+      }
+      return val;
+    }
+
+    private float GetPercentage(int capacity, int consumption, int consumptionMin = 45, int consumptionMax = 55)
+    {
+      if (capacity == 0)
+      {
+        return 0f;
+      }
+      float pct = capacity / (float)consumption;
+      float mod = (consumptionMin + (float)consumptionMax) / 2;
+      return pct * mod;
+    }
+
+    #region Overrides of ThreadingExtensionBase
+
+    private readonly Stopwatch _throttle = Stopwatch.StartNew();
+
+    public override void OnAfterSimulationTick()
+    {
+      base.OnAfterSimulationTick();
+
+      // Probably not in a normal game type if the district manager doesn't actually exist.
+      if (!Singleton<DistrictManager>.exists)
+      {
+        return;
+      }
+
+      if (_throttle.ElapsedMilliseconds < 1000)
+      {
+        return;
+      }
+
+      var eco = Singleton<EconomyManager>.instance;
+
+      UpdateBudget(eco, ref Singleton<DistrictManager>.instance.m_districts.m_buffer[0], ItemClass.Service.Electricity);
+      UpdateBudget(eco, ref Singleton<DistrictManager>.instance.m_districts.m_buffer[0], ItemClass.Service.Water);
+
+      _throttle.Reset();
+      _throttle.Start();
+    }
+
+    #endregion Overrides of ThreadingExtensionBase
+  }
 }


Adding convenience overload

Adding convenience overload

--- src/ControlzEx/Microsoft.Windows.Shell/Standard/DpiHelper.cs
+++ src/ControlzEx/Microsoft.Windows.Shell/Standard/DpiHelper.cs
@@ -68,10 +68,15 @@
             return new Size(pt.X, pt.Y);
         }

-        public static Thickness LogicalThicknessToDevice(Thickness logicalThickness, double dpiX, double dpiY)
-        {
-            var topLeft = LogicalPixelsToDevice(new Point(logicalThickness.Left, logicalThickness.Top), dpiX, dpiY);
-            var bottomRight = LogicalPixelsToDevice(new Point(logicalThickness.Right, logicalThickness.Bottom), dpiX, dpiY);
+        public static Thickness LogicalThicknessToDevice(Thickness logicalThickness, DpiScale dpiScale)
+        {
+            return LogicalThicknessToDevice(logicalThickness, dpiScale.DpiScaleX, dpiScale.DpiScaleY);
+        }
+
+        public static Thickness LogicalThicknessToDevice(Thickness logicalThickness, double dpiScaleX, double dpiScaleY)
+        {
+            var topLeft = LogicalPixelsToDevice(new Point(logicalThickness.Left, logicalThickness.Top), dpiScaleX, dpiScaleY);
+            var bottomRight = LogicalPixelsToDevice(new Point(logicalThickness.Right, logicalThickness.Bottom), dpiScaleX, dpiScaleY);

             return new Thickness(topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y);
         }