Require all country names to be unique

Require all country names to be unique

--- ShopifySharp.Tests/Country_Tests.cs
+++ ShopifySharp.Tests/Country_Tests.cs
@@ -76,7 +76,8 @@
         [Fact]
         public async Task Deletes_Countries()
         {
-            var created = await Fixture.Create(true);
+            var customName = "Germany_" + Guid.NewGuid();
+            var created = await Fixture.Create(customName, true);
             bool threw = false;

             try
@@ -101,15 +102,15 @@
             Assert.NotNull(obj);
             Assert.True(obj.Id.HasValue);
             Assert.Equal(Fixture.Code, obj.Code);
-            Assert.Equal(Fixture.Name, obj.Name);
+            Assert.NotEmpty(obj.Name);
             Assert.Equal(Fixture.Tax, obj.Tax);
         }

         [Fact]
         public async Task Creates_Countries()
         {
-            var customName = Fixture.Name + "_" + Guid.NewGuid();
-            var obj = await Fixture.Create(false, customName);
+            var customName = "Germany" + Guid.NewGuid();
+            var obj = await Fixture.Create(customName);

             Assert.NotNull(obj);
             Assert.True(obj.Id.HasValue);
@@ -121,11 +122,12 @@
         [Fact]
         public async Task Updates_Countries()
         {
-            string name = "ShopifySharp Updated Test Country";
-            var created = await Fixture.Create();
-            long id = created.Id.Value;
-
-            created.Name = name;
+            var originalName = "Germany_" + Guid.NewGuid();
+            var created = await Fixture.Create(originalName);
+            var updatedName = "ShopifySharp Updated Test Country";
+            var id = created.Id.Value;
+
+            created.Name = updatedName;
             created.Id = null;

             var updated = await Fixture.Service.UpdateAsync(id, created);
@@ -133,7 +135,7 @@
             // Reset the id so the Fixture can properly delete this object.
             created.Id = id;

-            Assert.Equal(name, updated.Name);
+            Assert.Equal(updatedName, updated.Name);
         }
     }

@@ -145,8 +147,6 @@

         public string Code => "DE";

-        public string Name = "Germany";
-
         public decimal Tax = (decimal)0.14;

         public string TaxName = "VAT";
@@ -156,7 +156,7 @@
             Service.SetExecutionPolicy(new SmartRetryExecutionPolicy());

             // Create one for count, list, get, etc. orders.
-            await Create();
+            await Create("Germany_" + Guid.NewGuid());
         }

         public async Task DisposeAsync()
@@ -180,12 +180,12 @@
         /// <summary>
         /// Convenience function for running tests. Creates an object and automatically adds it to the queue for deleting after tests finish.
         /// </summary>
-        public async Task<Country> Create(bool skipAddToCreateList = false, string customName = null)
+        public async Task<Country> Create(string customName, bool skipAddToCreateList = false)
         {
             var obj = await Service.CreateAsync(new Country()
             {
                 Code = Code,
-                Name = customName ?? Name,
+                Name = customName,
                 Tax = Tax
             });


Entity page facet sample

Entity page facet sample

--- SocialToolBox.Sample.Web/Modules.cs
+++ SocialToolBox.Sample.Web/Modules.cs
@@ -1,5 +1,6 @@
 using SocialToolBox.Core.Database;
 using SocialToolBox.Core.Entity;
+using SocialToolBox.Core.Entity.Web;
 using SocialToolBox.Core.Mocks.Database;
 using SocialToolBox.Core.Web;
 using SocialToolBox.Crm.Contact;
@@ -31,6 +32,11 @@
         /// </summary>
         public readonly EntityModule Entities;

+        /// <summary>
+        /// Registered web endpoints for entity pages.
+        /// </summary>
+        public readonly EntityPageFacet EntityPages;
+
         public Modules()
         {
             Database = new DatabaseDriver();
@@ -47,6 +53,9 @@
             Contacts.Compile();
             Entities.Compile();

+            // Install facets
+            EntityPages = new EntityPageFacet(Web, Entities);
+
             // Initialize modules
             InitialData.AddTo(this);
         }


If the Id of two entities are the same, then its the same object

--- Source/EventFlow/Entities/Entity.cs
+++ Source/EventFlow/Entities/Entity.cs
@@ -21,11 +21,13 @@
 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 using System;
+using System.Collections.Generic;
 using EventFlow.Core;
+using EventFlow.ValueObjects;

 namespace EventFlow.Entities
 {
-    public abstract class Entity<TIdentity> : IEntity<TIdentity>
+    public abstract class Entity<TIdentity> : ValueObject, IEntity<TIdentity>
         where TIdentity : IIdentity
     {
         protected Entity(TIdentity id)
@@ -41,5 +43,10 @@
         {
             return Id;
         }
+
+        protected override IEnumerable<object> GetEqualityComponents()
+        {
+            yield return Id;
+        }
     }
 }


Lint again.

Lint again.

--- Sessions/Startup.cs
+++ Sessions/Startup.cs
@@ -56,8 +56,8 @@
                 .AddFirestoreDistributedCacheGarbageCollector();
             services.AddSession();
         }
-readonly
-        Random _random = new Random();
+        readonly
+                Random _random = new Random();

         private static readonly string[] s_greetings =
             {"Hello World", "Hallo Welt", "Hola mundo",


[trunk] Makes sure we don't zoom beyond Min/Max Zoom set on Map-Obj.
fixes #issue 14791

git-tfs-id: [https://tfs.codeplex.com/tfs/TFS01]$/SharpMap/Trunk;C94794

--- SharpMap/Map/Map.cs
+++ SharpMap/Map/Map.cs
@@ -657,6 +657,10 @@
                 _Zoom = bbox.Width; //Set the private center value so we only fire one MapOnViewChange event
                 if (Envelope.Height < bbox.Height)
                     _Zoom *= bbox.Height / Envelope.Height;
+                if (_Zoom < _MinimumZoom)
+                    _Zoom = _MinimumZoom;
+                if (_Zoom > _MaximumZoom)
+                    _Zoom = _MaximumZoom;
                 Center = bbox.GetCentroid();
             }
         }


Added missed file for #1703

Added missed file for #1703

--- core/Piranha.AspNetCore/Services/ApplicationService.cs
+++ core/Piranha.AspNetCore/Services/ApplicationService.cs
@@ -123,6 +123,7 @@
                 if (site != null)
                 {
                     Site.Id = site.Id;
+                    Site.LanguageId = site.LanguageId;
                     Site.Culture = site.Culture;
                     Site.Sitemap = await Api.Sites.GetSitemapAsync(Site.Id);


Handle null event source.

Handle null event source.

--- src/Avalonia.Input/MouseDevice.cs
+++ src/Avalonia.Input/MouseDevice.cs
@@ -219,7 +219,7 @@
                 InputModifiers = inputModifiers
             };

-            source.RaiseEvent(e);
+            source?.RaiseEvent(e);
             return e.Handled;
         }


change [RestService] paths to Routes.Add

--- src/Backbone.Todos/Global.asax.cs
+++ src/Backbone.Todos/Global.asax.cs
@@ -2,14 +2,11 @@
 using ServiceStack.Redis;
 using ServiceStack.ServiceInterface;
 using ServiceStack.WebHost.Endpoints;
-using ServiceStack.ServiceHost;

 //The entire C# source code for the ServiceStack + Redis TODO REST backend. There is no other .cs :)
 namespace Backbone.Todos
 {
 	//Register REST Paths
-	[RestService("/todos")]
-	[RestService("/todos/{Id}")]
 	public class Todo //REST Resource DTO
 	{
 		public long Id { get; set; }
@@ -61,6 +58,10 @@
 		{
 			//Register Redis factory in Funq IOC
 			container.Register<IRedisClientsManager>(new BasicRedisClientManager("localhost:6379"));
+
+			Routes
+			  .Add<Todo>("/todos")
+			  .Add<Todo>("/todos/{Id}");
 		}
 	}


Fix BL-756: "multilingual settings" instead of "one language"

The problem was when both Lang1 and Lang2 were the same (e.g. English)
the code would say that lang2 was unselected by default, thus also
deselecting lang1.

--- src/BloomExe/Edit/EditingModel.cs
+++ src/BloomExe/Edit/EditingModel.cs
@@ -326,9 +326,13 @@
 					}
 				}
 				//update the selections
-				_contentLanguages.Where(l => l.Iso639Code == _collectionSettings.Language2Iso639Code).First().Selected =
+				_contentLanguages.First(l => l.Iso639Code == _collectionSettings.Language2Iso639Code).Selected =
 					_bookSelection.CurrentSelection.MultilingualContentLanguage2 ==_collectionSettings.Language2Iso639Code;

+				//the first language is always selected. This covers the common situation in shellbook collections where
+				//we have English as both the 1st and national language. https://jira.sil.org/browse/BL-756
+				_contentLanguages.First(l => l.Iso639Code == _collectionSettings.Language1Iso639Code).Selected = true;
+

 				var contentLanguageMatchingNatLan2 =
 					_contentLanguages.Where(l => l.Iso639Code == _collectionSettings.Language3Iso639Code).FirstOrDefault();


allow set page items directly

allow set page items directly

--- src/BuildingBlocks.Common/Page.cs
+++ src/BuildingBlocks.Common/Page.cs
@@ -1,100 +1,112 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace BuildingBlocks.Common
-{
-    public class Page<T>
-    {
-        public static Page<T> Empty(int pageNumber, int pageSize)
-        {
-            return new Page<T>(pageNumber, pageSize, 0)
-                {
-                    Items = new List<T>(0)
-                };
-        }
-
-        public Page(int pageNumber, int pageSize, long totalItemCount)
-        {
-            PageNumber = pageNumber;
-            PageSize = pageSize;
-            TotalItemCount = totalItemCount;
-        }
-
-        public IList<T> Items { get; private set; }
-        public int PageNumber { get; private set; }
-        public int PageSize { get; private set; }
-        public long TotalItemCount { get; private set; }
-
-        public int PageIndex
-        {
-            get { return PageNumber - 1; }
-        }
-
-        public int PageCount
-        {
-            get { return TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0; }
-        }
-
-        public bool HasPreviousPage
-        {
-            get { return PageNumber > 1; }
-        }
-
-        public bool HasNextPage
-        {
-            get { return PageNumber < PageCount; }
-        }
-
-        public bool IsFirstPage
-        {
-            get { return PageNumber == 1; }
-        }
-
-        public bool IsLastPage
-        {
-            get { return PageNumber >= PageCount; }
-        }
-
-        public long FirstItemOnPage
-        {
-            get { return (PageNumber - 1) * PageSize + 1; }
-        }
-
-        public long LastItemOnPage
-        {
-            get
-            {
-                long num = FirstItemOnPage + PageSize - 1;
-                return num > TotalItemCount ? TotalItemCount : num;
-            }
-        }
-
-        public int SkippedItems
-        {
-            get
-            {
-                return PageNumber == 1 ? 0 : (PageNumber - 1) * PageSize;
-            }
-        }
-
-        public void QueryFrom<TSource>(IQueryable<TSource> itemsSource, Func<TSource, T> mapFunction)
-        {
-            var sources = itemsSource.Skip(SkippedItems).Take(PageSize).ToList();
-            Items = sources.Select(mapFunction).ToList();
-        }
-
-        public void QueryFrom(IQueryable<T> itemsSource)
-        {
-            Items = itemsSource.Skip(SkippedItems).Take(PageSize).ToList();
-        }
-
-        public Page<TResult> MapWith<TResult>(Func<T, TResult> mapFunction)
-        {
-            return new Page<TResult>(PageNumber, PageSize, TotalItemCount)
-                {
-                    Items = Items.Select(mapFunction).ToList()
-                };
-        }
-    }
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace BuildingBlocks.Common
+{
+    public class Page<T>
+    {
+        public static Page<T> Empty(int pageNumber, int pageSize)
+        {
+            return new Page<T>(pageNumber, pageSize, 0)
+                {
+                    Items = new List<T>(0)
+                };
+        }
+
+        public Page(int pageNumber, int pageSize, long totalItemCount)
+        {
+            PageNumber = pageNumber;
+            PageSize = pageSize;
+            TotalItemCount = totalItemCount;
+        }
+
+        public IList<T> Items { get; private set; }
+        public int PageNumber { get; private set; }
+        public int PageSize { get; private set; }
+        public long TotalItemCount { get; private set; }
+
+        public int PageIndex
+        {
+            get { return PageNumber - 1; }
+        }
+
+        public int PageCount
+        {
+            get { return TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0; }
+        }
+
+        public bool HasPreviousPage
+        {
+            get { return PageNumber > 1; }
+        }
+
+        public bool HasNextPage
+        {
+            get { return PageNumber < PageCount; }
+        }
+
+        public bool IsFirstPage
+        {
+            get { return PageNumber == 1; }
+        }
+
+        public bool IsLastPage
+        {
+            get { return PageNumber >= PageCount; }
+        }
+
+        public long FirstItemOnPage
+        {
+            get { return (PageNumber - 1) * PageSize + 1; }
+        }
+
+        public long LastItemOnPage
+        {
+            get
+            {
+                long num = FirstItemOnPage + PageSize - 1;
+                return num > TotalItemCount ? TotalItemCount : num;
+            }
+        }
+
+        public int SkippedItems
+        {
+            get
+            {
+                return PageNumber == 1 ? 0 : (PageNumber - 1) * PageSize;
+            }
+        }
+
+        public void SetItems(IEnumerable<T> enumerable)
+        {
+            if (enumerable == null)
+                throw new ArgumentNullException("enumerable");
+
+            var items = enumerable.ToList();
+            if (items.Count > PageSize)
+                throw new ArgumentException("Page items is more then page size", "enumerable");
+
+            Items = items;
+        }
+
+        public void QueryFrom<TSource>(IQueryable<TSource> itemsSource, Func<TSource, T> mapFunction)
+        {
+            var sources = itemsSource.Skip(SkippedItems).Take(PageSize).ToList();
+            Items = sources.Select(mapFunction).ToList();
+        }
+
+        public void QueryFrom(IQueryable<T> itemsSource)
+        {
+            Items = itemsSource.Skip(SkippedItems).Take(PageSize).ToList();
+        }
+
+        public Page<TResult> MapWith<TResult>(Func<T, TResult> mapFunction)
+        {
+            return new Page<TResult>(PageNumber, PageSize, TotalItemCount)
+                {
+                    Items = Items.Select(mapFunction).ToList()
+                };
+        }
+    }
 }


Fix column length formatting when the longest string is in one of columns' headers.

--- src/ConsoleTables/ConsoleTable.cs
+++ src/ConsoleTables/ConsoleTable.cs
@@ -190,7 +190,7 @@
         {
             var columnLengths = Columns
                 .Select((t, i) => Rows.Select(x => x[i])
-                    .Union(Columns)
+                    .Union(new[] { Columns[i] })
                     .Where(x => x != null)
                     .Select(x => x.ToString().Length).Max())
                 .ToList();


Disponibilizes page or post title in a common way

--- src/Core/LiquidTemplateManager.cs
+++ src/Core/LiquidTemplateManager.cs
@@ -1,11 +1,13 @@
 using System.Collections.Generic;
 using System.IO;
+using System.Text.RegularExpressions;
 using DotLiquid;

 namespace RDumont.Frankie.Core
 {
     public class LiquidTemplateManager : TemplateManager
     {
+        private readonly Regex _titleRegex = new Regex(@"<h1(?:.+)?>(.+)</h1>", RegexOptions.Compiled);
         private readonly Dictionary<string, Template> templatesByName = new Dictionary<string, Template>();

         public override void Init(string basePath)
@@ -28,6 +30,7 @@

             var hash = Hash.FromAnonymousObject(new
                 {
+                    title = _titleRegex.Match(model.Body).Groups[1].Value,
                     dependantPath = pagePath,
                     path = pagePath,
                     posts = SiteContext.Current.Posts
@@ -63,6 +66,7 @@

             var hash = Hash.FromAnonymousObject(new
                 {
+                    title = model.Title,
                     dependantPath = postPath,
                     path = postPath,
                     post = model
@@ -87,6 +91,8 @@
             page.TransformMarkdown();
             WrapWithTemplate(page, templateName);

+            hash.Add("title", _titleRegex.Match(page.Body).Groups[1].Value);
+
             return Template.Parse(page.Body).Render(hash);
         }


Do not release a null CFString handle. Fix bug #2728

--- src/CoreFoundation/CFException.cs
+++ src/CoreFoundation/CFException.cs
@@ -4,6 +4,7 @@
 // Authors: Mono Team
 //
 // Copyright (C) 2009 Novell, Inc
+// Copyright 2012 Xamarin Inc.
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -135,7 +136,7 @@
 		static string ToString (IntPtr cfStringRef, bool release)
 		{
 			var r = CFString.FetchString (cfStringRef);
-			if (release)
+			if (release && (cfStringRef != IntPtr.Zero))
 				CFObject.CFRelease (cfStringRef);
 			return r;
 		}


User AsyncReaderWriterLock

User AsyncReaderWriterLock

--- src/DotNetTor/TorSocks5Handler.cs
+++ src/DotNetTor/TorSocks5Handler.cs
@@ -29,9 +29,7 @@
 		public IPEndPoint TorSocks5EndPoint => TorSocks5Manager?.TorSocks5EndPoint;

 		private AsyncLock ConnectLock { get; }
-
-		private volatile bool _connectionsDisposingForCircuitChange; // true while disposes connections for circuit change request, also detects redundant calls
-		private int _requestCounter;
+		private AsyncReaderWriterLock DisposeRequestLock { get; }

 		#endregion

@@ -47,8 +45,7 @@

 			ConnectLock = new AsyncLock();

-			_connectionsDisposingForCircuitChange = false;
-			_requestCounter = 0;
+			DisposeRequestLock = new AsyncReaderWriterLock();

 			TorControlClient.CircuitChangeRequested += Client_CircuitChangeRequestedAsync;
 		}
@@ -68,35 +65,27 @@
 			// A sender MUST NOT generate an "http" URI with an empty host identifier.
 			var host = Guard.NotNullOrEmptyOrWhitespace($"{nameof(request)}.{nameof(request.RequestUri)}.{nameof(request.RequestUri.DnsSafeHost)}", request.RequestUri.DnsSafeHost, trim: true);

-			while (_connectionsDisposingForCircuitChange)
-			{
-				await Task.Delay(50).ConfigureAwait(false);
-			}
-
-			Interlocked.Increment(ref _requestCounter);
-			// this makes sure clients with the same host don't try to connect concurrently
-			// it is released after the connection is established or in the finally block
-			var connectLockTask = await ConnectLock.LockAsync().ConfigureAwait(false);
-			try
+			using (await DisposeRequestLock.ReaderLockAsync())
+			using (var connectLockTask = await ConnectLock.LockAsync().ConfigureAwait(false)) // this makes sure clients with the same host don't try to connect concurrently, it gets released after connection established
 			{
 				KeyValuePair<TorSocks5Client, AsyncLock> clientLockPair = TryFindClientLockPair(host, request.RequestUri.Port);
 				AsyncLock clientLock = clientLockPair.Value ?? new AsyncLock(); // this makes sure clients with the same host don't work concurrently
 				using (await clientLock.LockAsync().ConfigureAwait(false))
 				{
 					TorSocks5Client client;
-						// https://tools.ietf.org/html/rfc7230#section-2.6
-						// Intermediaries that process HTTP messages (i.e., all intermediaries
-						// other than those acting as tunnels) MUST send their own HTTP - version
-						// in forwarded messages.
-						request.Version = HttpProtocol.HTTP11.Version;
-
-						client = clientLockPair.Key;
-
-						if (client != null && !client.IsConnected)
-						{
-							Connections.TryRemove(client, out AsyncLock al);
-							client?.Dispose();
-						}
+					// https://tools.ietf.org/html/rfc7230#section-2.6
+					// Intermediaries that process HTTP messages (i.e., all intermediaries
+					// other than those acting as tunnels) MUST send their own HTTP - version
+					// in forwarded messages.
+					request.Version = HttpProtocol.HTTP11.Version;
+
+					client = clientLockPair.Key;
+
+					if (client != null && !client.IsConnected)
+					{
+						Connections.TryRemove(client, out AsyncLock al);
+						client?.Dispose();
+					}

 					if (client == null || !client.IsConnected)
 					{
@@ -195,11 +184,6 @@
 					return await new HttpResponseMessage().CreateNewAsync(client.Stream, request.Method).ConfigureAwait(false);
 				}
 			}
-			finally
-			{
-				Interlocked.Decrement(ref _requestCounter);
-				connectLockTask?.Dispose(); // just to be sure, if no exception it gets disposed way before
-			}
 		}

 		private KeyValuePair<TorSocks5Client, AsyncLock> TryFindClientLockPair(string host, int port)
@@ -213,28 +197,21 @@

 		#region Events

-		private async void Client_CircuitChangeRequestedAsync(object sender, EventArgs e)
-		{
-			if (_connectionsDisposingForCircuitChange) return; // don't dispose redundantly
-
-			try
-			{
-				_connectionsDisposingForCircuitChange = true;
-				while (Interlocked.CompareExchange(ref _requestCounter, 0, 0) > 0) // probably the best way to read with interlocked: https://stackoverflow.com/a/24893231/2061103
-				{
-					await Task.Delay(50).ConfigureAwait(false);
-				}
-
+		private void Client_CircuitChangeRequestedAsync(object sender, EventArgs e)
+		{
+			DisposeConnections();
+		}
+
+		private void DisposeConnections()
+		{
+			using (DisposeRequestLock.WriterLock())
+			{
 				foreach (var connection in Connections)
 				{
 					connection.Key?.Dispose();
 				}
 				Connections.Clear();
 			}
-			finally
-			{
-				_connectionsDisposingForCircuitChange = false;
-			}
 		}

 		#endregion
@@ -252,10 +229,7 @@
 					try
 					{
 						TorControlClient.CircuitChangeRequested -= Client_CircuitChangeRequestedAsync;
-						foreach (var connection in Connections)
-						{
-							connection.Key?.Dispose();
-						}
+						DisposeConnections();
 					}
 					catch (Exception ex)
 					{


fixing how we "Save" bitmaps, now at full quality

--- src/FODT/Models/ImageUtilities.cs
+++ src/FODT/Models/ImageUtilities.cs
@@ -1,16 +1,24 @@
 using System;
-using System.Collections.Generic;
 using System.Drawing;
 using System.Drawing.Drawing2D;
 using System.Drawing.Imaging;
 using System.IO;
 using System.Linq;
-using System.Web;

 namespace FODT.Models
 {
-    public class ImageUtilities
+    public static class ImageUtilities
     {
+        static ImageUtilities()
+        {
+            jpegEncoder = ImageCodecInfo.GetImageDecoders().First(x => x.FormatID == ImageFormat.Jpeg.Guid);
+            jpegEncoderHighQualityParameters = new EncoderParameters(1);
+            jpegEncoderHighQualityParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
+        }
+
+        private static readonly ImageCodecInfo jpegEncoder;
+        private static readonly EncoderParameters jpegEncoderHighQualityParameters;
+
         public static Bitmap LoadBitmap(byte[] image)
         {
             using (var s = new MemoryStream(image))
@@ -26,7 +34,7 @@
         {
             using (var s = new MemoryStream())
             {
-                source.Save(s, format);
+                source.Save(s, jpegEncoder, jpegEncoderHighQualityParameters);
                 return s.ToArray();
             }
         }


Increase gbContext timeout, set HttpVersion to 2.0

--- src/GiantBomb/GiantBombContext.cs
+++ src/GiantBomb/GiantBombContext.cs
@@ -44,7 +44,7 @@

             client = new HttpClient(handler, false)
             {
-                Timeout = TimeSpan.FromSeconds(7d)
+                Timeout = TimeSpan.FromSeconds(30d)
             };

             if (!client.DefaultRequestHeaders.UserAgent.TryParseAdd(_settings.UserAgent))
@@ -93,12 +93,16 @@
             HttpStatusCode status = HttpStatusCode.Unused;
             byte[] bytes = Array.Empty<byte>();

-            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
+            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri)
+            {
+                Version = HttpVersion.Version20
+            };
+
             HttpResponseMessage? response = null;

             try
             {
-                response = await client.SendAsync(request).ConfigureAwait(false);
+                response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                 if (response.IsSuccessStatusCode)
                 {
@@ -171,8 +175,7 @@
         private static bool GetIsLive(JsonElement root)
         {
             return root.TryGetProperty("liveNow", out JsonElement liveNow)
-                ? liveNow.ValueKind == JsonValueKind.Object
-                : false;
+                && liveNow.ValueKind == JsonValueKind.Object;
         }

         private static string GetLiveShowTitle(JsonElement root)


DataContacts, because!

DataContacts, because!

--- src/Messaging/InternalMessages.cs
+++ src/Messaging/InternalMessages.cs
@@ -1,19 +1,23 @@
 using System;
+using System.Runtime.Serialization;

 namespace Messaging
 {
     [Serializable]
+    [DataContract(Namespace = "ServiceBusInternalMessages")]
     public class StartSubscriptionRequest
     {
-        public Subscription Subscription { get; private set; }
-
         public StartSubscriptionRequest(Subscription subscription)
         {
             Subscription = subscription;
         }
+
+        [DataMember(Order = 1)]
+        public Subscription Subscription { get; private set; }
     }

     [Serializable]
+    [DataContract(Namespace = "ServiceBusInternalMessages")]
     public class EndSubscriptionRequest
     {
         public EndSubscriptionRequest(Subscription subscription)
@@ -21,10 +25,12 @@
             Subscription = subscription;
         }

+        [DataMember(Order = 1)]
         public Subscription Subscription { get; private set; }
     }

     [Serializable]
+    [DataContract(Namespace = "ServiceBusInternalMessages")]
     public class SubscriptionStarted
     {
         public SubscriptionStarted(Subscription subscription)
@@ -32,10 +38,12 @@
             Subscription = subscription;
         }

+        [DataMember(Order = 1)]
         public Subscription Subscription { get; private set; }
     }

     [Serializable]
+    [DataContract(Namespace = "ServiceBusInternalMessages")]
     public class SubscriptionEnded
     {
         public SubscriptionEnded(Subscription subscription)
@@ -43,6 +51,7 @@
             Subscription = subscription;
         }

+        [DataMember(Order = 1)]
         public Subscription Subscription { get; private set; }
     }
 }


Refactor

Refactor

--- src/Miningcore/Util/FormatUtil.cs
+++ src/Miningcore/Util/FormatUtil.cs
@@ -3,13 +3,12 @@
 public static class FormatUtil
 {
     public static readonly string[] HashrateUnits = { " H/s", " KH/s", " MH/s", " GH/s", " TH/s", " PH/s" , " EH/s" };
-    public static readonly string[] DifficultyUnits = { " K", " M", " G", " T", " P", " E" };
+    public static readonly string[] QuantityUnits = { "K", "M", "G", "T", "P", "E" };
     public static readonly string[] CapacityUnits = { " KB", " MB", " GB", " TB", " PB" };
-    public static readonly string[] QuantityUnits = { "K", "M", "B", "T", "Q" };

     public static string FormatHashrate(double hashrate)
     {
-        var hashrateUnits = HashrateUnits;// GetHashrateUnitsForCoin(coin);
+        var hashrateUnits = HashrateUnits;

         var i = 0;

@@ -45,6 +44,6 @@
             i++;
         } while(value > 1000);

-        return Math.Round(value, 2) + DifficultyUnits[i];
+        return Math.Round(value, 2) + QuantityUnits[i];
     }
 }


Replace pattern marching with two steps cast

--- src/NFluent/Kernel/FluentCheck.cs
+++ src/NFluent/Kernel/FluentCheck.cs
@@ -95,8 +95,10 @@
         {
             this.IsInstanceOfType(typeof(TU));

-            if (Value is TU converted)
-                return ExtensibilityHelper.BuildCheckLinkWhich(this, converted, SutName);
+            // TODO: respore pattern matching version when appveyor is upgraded
+//            if (Value is TU converted)
+            if (Value is TU )
+                return ExtensibilityHelper.BuildCheckLinkWhich(this, (TU) (object) Value, SutName);
             return ExtensibilityHelper.BuildCheckLinkWhich(this, default(TU), SutName);
         }


changing GetIdentifier visibility - enables XmlIn

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@2833

--- src/NHibernate/Type/EntityType.cs
+++ src/NHibernate/Type/EntityType.cs
@@ -75,7 +75,7 @@
 			get { return associatedClass; }
 		}

-		protected object GetIdentifier(object value, ISessionImplementor session)
+		public object GetIdentifier(object value, ISessionImplementor session)
 		{
 			if (IsReferenceToPrimaryKey)
 			{


Reimplement OneOrMore in terms of Repeat, so that the first item and trailing items can benefit from potential `locality of reference` optimizations. Prior to this change, the first item and remaining items were needlessly separated, and their inevitable iteration had to work via an atypical yield-return pattern. Now they appear in contiguous memory with as-efficient-as-possible iteration.

--- src/Parsley/Grammar.Repetition.cs
+++ src/Parsley/Grammar.Repetition.cs
@@ -61,9 +61,24 @@
     /// </summary>
     public static Parser<TItem, IEnumerable<TValue>> OneOrMore<TItem, TValue>(Parser<TItem, TValue> item)
     {
-        return from first in item
-            from rest in ZeroOrMore(item)
-            select List(first, rest);
+        return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out IEnumerable<TValue>? values, [NotNullWhen(false)] out string? expectation) =>
+        {
+            var accumulator = new List<TValue>();
+
+            if (item(input, ref index, out var value, out var itemExpectation))
+            {
+                accumulator.Add(value);
+            }
+            else
+            {
+                //The required first item failed.
+                expectation = itemExpectation;
+                values = null;
+                return false;
+            }
+
+            return Repeat(accumulator, item, input, ref index, out values, out expectation);
+        };
     }

     /// <summary>


debug_zval_dump()

--- src/Peachpie.Library/Variables.cs
+++ src/Peachpie.Library/Variables.cs
@@ -867,7 +867,7 @@

         #endregion

-        #region print_r, var_export, var_dump
+        #region print_r, var_export, var_dump, debug_zval_dump

         abstract class FormatterVisitor : PhpVariableVisitor, IPhpVariableFormatter
         {
@@ -879,7 +879,7 @@

             protected const string RECURSION = "*RECURSION*";

-            protected FormatterVisitor(Context ctx, string newline)
+            protected FormatterVisitor(Context ctx, string newline = "\n")
             {
                 Debug.Assert(ctx != null);
                 _ctx = ctx;
@@ -941,7 +941,7 @@
                 }
             }

-            public PrintFormatter(Context ctx, string newline)
+            public PrintFormatter(Context ctx, string newline = "\n")
                 : base(ctx, newline)
             {
             }
@@ -1077,7 +1077,7 @@
                 }
             }

-            public ExportFormatter(Context ctx, string newline)
+            public ExportFormatter(Context ctx, string newline = "\n")
                 : base(ctx, newline)
             {
             }
@@ -1263,6 +1263,11 @@
         {
             const int IndentSize = 2;

+            /// <summary>
+            /// Enables verbose dump.
+            /// </summary>
+            bool Verbose { get; }
+
             void OutputIndent()
             {
                 if (_indent > 0)
@@ -1271,9 +1276,10 @@
                 }
             }

-            public DumpFormatter(Context ctx, string newline)
+            public DumpFormatter(Context ctx, string newline = "\n", bool verbose = false)
                 : base(ctx, newline)
             {
+                this.Verbose = verbose;
             }

             public override PhpString Serialize(PhpValue value)
@@ -1451,7 +1457,7 @@
         /// <returns>A string representation or <c>true</c> if <paramref name="returnString"/> is <c>false</c>.</returns>
         public static PhpValue print_r(Context ctx, PhpValue value, bool returnString = false)
         {
-            var output = (new PrintFormatter(ctx, "\n")).Serialize(value);
+            var output = (new PrintFormatter(ctx)).Serialize(value);

             if (returnString)
             {
@@ -1473,7 +1479,22 @@
         /// <param name="variables">Variables to be dumped.</param>
         public static void var_dump(Context ctx, params PhpValue[] variables)
         {
-            var formatter = new DumpFormatter(ctx, "\n"); // TODO: HtmlDumpFormatter
+            var formatter = new DumpFormatter(ctx); // TODO: HtmlDumpFormatter
+            for (int i = 0; i < variables.Length; i++)
+            {
+                ctx.Echo(formatter.Serialize(variables[i].GetValue()));
+            }
+        }
+
+        /// <summary>
+        /// Dumps a more detailed string representation of value.
+        /// </summary>
+        /// <param name="ctx">Current runtime context.</param>
+        /// <param name="variables">Variables to be dumped.</param>
+        public static void debug_zval_dump(Context ctx, params PhpValue[] variables)
+        {
+            var formatter = new DumpFormatter(ctx, verbose: true);
+
             for (int i = 0; i < variables.Length; i++)
             {
                 ctx.Echo(formatter.Serialize(variables[i].GetValue()));
@@ -1489,7 +1510,7 @@
         /// <returns>A string representation or a <c>null</c> reference if <paramref name="returnString"/> is <c>false</c>.</returns>
         public static string var_export(Context ctx, PhpValue variable, bool returnString = false)
         {
-            var output = (new ExportFormatter(ctx, "\n")).Serialize(variable);
+            var output = (new ExportFormatter(ctx)).Serialize(variable);

             if (returnString)
             {


cleanup

cleanup

--- src/Peachpie.Library/Variables.cs
+++ src/Peachpie.Library/Variables.cs
@@ -226,15 +226,13 @@
             else if (variable.IsObject)
             {
                 // PHP Countable
-                var countable = variable.Object as Spl.Countable;
-                if (countable != null)
+                if (variable.Object is Spl.Countable countable)
                 {
                     return countable.count();
                 }

                 // CLR ICollection
-                var collection = variable.Object as System.Collections.ICollection;
-                if (collection != null)
+                if (variable.Object is System.Collections.ICollection collection)
                 {
                     return collection.Count;
                 }


sdk: saving .rsp only in debug builds

sdk: saving .rsp only in debug builds

--- src/Peachpie.NET.Sdk/BuildTask.cs
+++ src/Peachpie.NET.Sdk/BuildTask.cs
@@ -199,6 +199,7 @@
                 }
             }

+#if DEBUG
             //
             // save the arguments as .rsp file for debugging purposes:
             try
@@ -209,6 +210,7 @@
             {
                 this.Log.LogWarningFromException(ex);
             }
+#endif

             //
             // run the compiler:


Clean up GetItemOrdValue

Clean up GetItemOrdValue

--- src/Peachpie.Runtime/Operators.cs
+++ src/Peachpie.Runtime/Operators.cs
@@ -620,25 +620,26 @@
         /// </summary>
         public static long GetItemOrdValue(PhpValue value, long index)
         {
-            switch (value.TypeCode)
-            {
-                case PhpTypeCode.String:
-                    return GetItemOrdValue(value.String, index);
-                case PhpTypeCode.MutableString:
-                    return GetItemOrdValue(value.MutableString, index);
-                default:
-                    var item = value.GetArrayItem(index);
-                    var itemType = item.TypeCode;
-                    if (itemType == PhpTypeCode.MutableString)
-                    {
-                        var phpStr = item.MutableString;
-                        return phpStr.IsEmpty ? 0 : phpStr[0];
-                    }
-                    else
-                    {
-                        var str = item.ToString();
-                        return string.IsNullOrEmpty(str) ? 0 : str[0];
-                    }
+            if (value.TypeCode == PhpTypeCode.String)
+            {
+                return GetItemOrdValue(value.String, index);
+            }
+            else if (value.IsMutableString(out var phpString))
+            {
+                return GetItemOrdValue(phpString, index);
+            }
+            else
+            {
+                var item = value.GetArrayItem(index);
+                if (item.IsMutableString(out var itemPhpString))
+                {
+                    return itemPhpString.IsEmpty ? 0 : itemPhpString[0];
+                }
+                else
+                {
+                    var str = item.ToString();
+                    return string.IsNullOrEmpty(str) ? 0 : str[0];
+                }
             }
         }


Fix for https://github.com/Jessecar96/SteamBot/issues/602 - exploit caused by Steam sometimes not correctly sending the ItemAdded/ItemRemoved events

--- SteamTrade/Trade.cs
+++ SteamTrade/Trade.cs
@@ -536,11 +536,8 @@
                     return false;
             }

-            if(status.newversion)
-            {
-                // handle item adding and removing
-                session.Version = status.version;
-
+            if (status.newversion)
+            {
                 HandleTradeVersionChange(status);
                 return true;
             }
@@ -581,10 +578,11 @@
                 switch((TradeEventType) tradeEvent.action)
                 {
                     case TradeEventType.ItemAdded:
-                        FireOnUserAddItem(new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid));
+                        //The ItemAdded and ItemRemoved events from Steam cannot be trusted.  See https://github.com/Jessecar96/SteamBot/issues/602
+                        //Instead, we now manually call FireOnUserAddItem/RemoveItem from HandleTradeVersionChange()
                         break;
                     case TradeEventType.ItemRemoved:
-                        FireOnUserRemoveItem(new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid));
+                        //Do nothing; see above comment
                         break;
                     case TradeEventType.UserSetReady:
                         OnUserSetReady(true);
@@ -615,8 +613,27 @@

         private void HandleTradeVersionChange(TradeStatus status)
         {
+            //Figure out which items have been added/removed
+            IEnumerable<TradeUserAssets> otherOfferedItemsUpdated = status.them.GetAssets();
+            IEnumerable<TradeUserAssets> addedItems = otherOfferedItemsUpdated.Except(otherOfferedItems).ToList();
+            IEnumerable<TradeUserAssets> removedItems = otherOfferedItems.Except(otherOfferedItemsUpdated).ToList();
+
+            //Copy of the new items and update the version number
             otherOfferedItems = status.them.GetAssets().ToList();
             myOfferedItems = status.me.GetAssets().ToList();
+            session.Version = status.version;
+
+            //Fire the OnUserRemoveItem events
+            foreach (TradeUserAssets asset in removedItems)
+            {
+                FireOnUserRemoveItem(asset);
+            }
+
+            //Fire the OnUserAddItem events
+            foreach (TradeUserAssets asset in addedItems)
+            {
+                FireOnUserAddItem(asset);
+            }
         }

         /// <summary>
@@ -770,14 +787,9 @@

         private void ValidateLocalTradeItems()
         {
-            if (myOfferedItemsLocalCopy.Count != MyOfferedItems.Count())
-            {
-                throw new TradeException("Error validating local copy of items in the trade: Count mismatch");
-            }
-
-            if (myOfferedItemsLocalCopy.Values.Any(id => !MyOfferedItems.Contains(id)))
-            {
-                throw new TradeException("Error validating local copy of items in the trade: Item was not in the Steam Copy.");
+            if (!myOfferedItemsLocalCopy.Values.OrderBy(o => o).SequenceEqual(MyOfferedItems.OrderBy(o => o)))
+            {
+                throw new TradeException("Error validating local copy of offered items in the trade");
             }
         }
     }


If an auto-created type doesn't compile, don't remove it from the list of types

--- Stylet/StyletIoC.cs
+++ Stylet/StyletIoC.cs
@@ -63,34 +63,23 @@
         public void Compile()
         {
             this.compilationStarted = true;
-
-            var toRemove = new List<IRegistration>();
             foreach (var kvp in this.registrations)
             {
-                toRemove.Clear();
                 foreach (var registration in kvp.Value)
                 {
                     try
                     {
                         registration.GetGenerator(this);
                     }
-                    catch (StyletIoCFindConstructorException e)
+                    catch (StyletIoCFindConstructorException)
                     {
-                        // If we can't resolve an auto-created type, that's fine - remove it from the list of types
-                        if (registration.WasAutoCreated)
-                        {
-                            System.Diagnostics.Debug.WriteLine(String.Format("ERROR: Unable to auto-bind type {0}: {1}", registration.Type.Name, e.Message), "StyletIoC");
-                            toRemove.Add(registration);
-                        }
-                        else
-                        {
+                        // If we can't resolve an auto-created type, that's fine
+                        // Don't remove it from the list of types - that way they'll get a
+                        // decent error message if they actually try and resolve it
+                        if (!registration.WasAutoCreated)
                             throw;
-                        }
                     }
                 }
-
-                foreach (var remove in toRemove)
-                    this.registrations[kvp.Key].Remove(remove);
             }
         }


Heartbit shouldn't be canceled

Heartbit shouldn't be canceled

--- wslib/Protocol/Heartbit.cs
+++ wslib/Protocol/Heartbit.cs
@@ -33,10 +33,7 @@

         private static async Task sendPing(IWebSocket socket)
         {
-            using (var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)))
-            {
-                await socket.SendMessageAsync(WsFrameHeader.Opcodes.PING, pingPayload, tokenSource.Token).ConfigureAwait(false);
-            }
+            await socket.SendMessageAsync(WsFrameHeader.Opcodes.PING, pingPayload, CancellationToken.None).ConfigureAwait(false);
         }
     }
 }


seems to show an improvement for most operations when level is 10 or more

--- TVGLTest/Program.cs
+++ TVGLTest/Program.cs
@@ -143,12 +143,9 @@

         public static void TestVoxelization(TessellatedSolid ts)
         {
-            var res = 8;
-
-            //stopwatch.Restart();
-            //var vs = new VoxelizedSolid(ts, res);
-            //stopwatch.Stop();
-            //Console.WriteLine("Original voxelization: {0}", stopwatch.Elapsed);
+            var res = 10;
+
+            Console.WriteLine("Original voxelization: {0}", stopwatch.Elapsed);

             stopwatch.Restart();
             var vs_dense = new VoxelizedSolidDense(ts, res);
@@ -156,97 +153,57 @@
             Console.WriteLine("Dense voxelization    : {0}", stopwatch.Elapsed);

-            //Console.WriteLine(ts.SurfaceArea);
-            //Console.WriteLine(vs_dense.SurfaceArea);
-            //Console.WriteLine();
-
-            //Console.WriteLine(ts.Volume);
-            ////Console.WriteLine(vs.Volume);
-            //Console.WriteLine(vs_dense.Volume);
-
-            //Presenter.ShowAndHang(vs_dense);
-
-
-            //stopwatch.Restart();
-            //var bb = vs.CreateBoundingSolid();
-            //stopwatch.Stop();
-            //Console.WriteLine("Original bounding solid: {0}", stopwatch.Elapsed);
+            //var vs_cut2 = vs_dense.SliceOnFlat(VoxelDirections.XNegative, 87);
+            //vs_cut2.Item1.SolidColor = new Color(KnownColors.Magenta);
+            //Presenter.ShowAndHang(vs_cut2.Item1, vs_cut2.Item2);
+

             stopwatch.Restart();
             var bb_dense = vs_dense.CreateBoundingSolid();
             stopwatch.Stop();
             Console.WriteLine("Dense bounding solid   : {0}", stopwatch.Elapsed);

-
-            //stopwatch.Restart();
-            //var erd = bb.ErodeToNewSolid(vs, new[] { -1, -2, -3.0 }, 0D, 20, false, true, "ball");
-            //stopwatch.Stop();
-            //Console.WriteLine("Original erosion: {0}", stopwatch.Elapsed);
-
-            stopwatch.Restart();
-            var erd_dense = bb_dense.ErodeToNewSolid(vs_dense, new[] {-1, -2, -3.0}, 0D, 20, "ball");
+            stopwatch.Restart();
+            var erd_dense = bb_dense.ErodeToNewSolid(vs_dense, new[] { 0, .471, -.882 }, 0, 0, "flat");
             stopwatch.Stop();
             Console.WriteLine("Dense erosion   : {0}", stopwatch.Elapsed);
+            erd_dense.SolidColor = new Color(KnownColors.Magenta);

             //Presenter.ShowAndHang(erd);
-            //Presenter.ShowAndHang(erd_dense);
-
-
-            //stopwatch.Restart();
-            //var neg = vs.InvertToNewSolid();
-            //stopwatch.Stop();
-            //Console.WriteLine("Original inversion: {0}", stopwatch.Elapsed);
-
-            //stopwatch.Restart();
-            //var neg_dense = vs_dense.InvertToNewSolid();
-            //stopwatch.Stop();
-            //Console.WriteLine("Dense inversion   : {0}", stopwatch.Elapsed);
-
-
-            //stopwatch.Restart();
-            //var draft = vs.ExtrudeToNewSolid(VoxelDirections.ZPositive);
-            //stopwatch.Stop();
-            //Console.WriteLine("Original draft: {0}", stopwatch.Elapsed);
-
-            //stopwatch.Restart();
-            //var draft_dense = vs_dense.DraftToNewSolid(VoxelDirections.ZPositive);
-            //stopwatch.Stop();
-            //Console.WriteLine("Dense draft   : {0}", stopwatch.Elapsed);
-
-
-            //stopwatch.Restart();
-            //var intersect = neg.IntersectToNewSolid(draft);
-            //stopwatch.Stop();
-            //Console.WriteLine("Original intersect: {0}", stopwatch.Elapsed);
-
-            //stopwatch.Restart();
-            //var intersect_dense = neg_dense.IntersectToNewSolid(draft_dense);
-            //stopwatch.Stop();
-            //Console.WriteLine("Dense intersect   : {0}", stopwatch.Elapsed);
-
-
-            //var draft1 = vs.ExtrudeToNewSolid(VoxelDirections.YNegative);
-            //stopwatch.Restart();
-            //var union = draft.UnionToNewSolid(draft1);
-            //stopwatch.Stop();
-            //Console.WriteLine("Original union: {0}", stopwatch.Elapsed);
-
-            //var draft1_dense = vs_dense.DraftToNewSolid(VoxelDirections.YNegative);
-            //stopwatch.Restart();
-            //var union_dense = draft_dense.UnionToNewSolid(draft1_dense);
-            //stopwatch.Stop();
-            //Console.WriteLine("Dense union   : {0}", stopwatch.Elapsed);
-
-
-            //stopwatch.Restart();
-            //var subtract = draft.SubtractToNewSolid(draft1);
-            //stopwatch.Stop();
-            //Console.WriteLine("Original subtract: {0}", stopwatch.Elapsed);
-
-            //stopwatch.Restart();
-            //var subtract_dense = draft_dense.SubtractToNewSolid(draft1_dense);
-            //stopwatch.Stop();
-            //Console.WriteLine("Dense subtract   : {0}", stopwatch.Elapsed);
+            //Presenter.ShowAndHang(erd_dense, vs_dense);
+
+
+            stopwatch.Restart();
+            var neg_dense = vs_dense.InvertToNewSolid();
+            stopwatch.Stop();
+            Console.WriteLine("Dense inversion   : {0}", stopwatch.Elapsed);
+
+            stopwatch.Restart();
+            var draft_dense = vs_dense.DraftToNewSolid(VoxelDirections.ZPositive);
+            stopwatch.Stop();
+            Console.WriteLine("Dense draft   : {0}", stopwatch.Elapsed);
+
+
+
+
+            stopwatch.Restart();
+            var intersect_dense = neg_dense.IntersectToNewSolid(draft_dense);
+            stopwatch.Stop();
+            Console.WriteLine("Dense intersect   : {0}", stopwatch.Elapsed);
+
+
+            var draft1_dense = vs_dense.DraftToNewSolid(VoxelDirections.YNegative);
+            stopwatch.Restart();
+            var union_dense = draft_dense.UnionToNewSolid(draft1_dense);
+            stopwatch.Stop();
+            Console.WriteLine("Dense union   : {0}", stopwatch.Elapsed);
+
+
+
+            stopwatch.Restart();
+            var subtract_dense = draft_dense.SubtractToNewSolid(draft1_dense);
+            stopwatch.Stop();
+            Console.WriteLine("Dense subtract   : {0}", stopwatch.Elapsed);
         }

         public static void TestSegmentation(TessellatedSolid ts)


Update HashCode.cs

Update HashCode.cs

--- Runtime/HashCode.cs
+++ Runtime/HashCode.cs
@@ -1,4 +1,4 @@
-#if (!NETCOREAPP2_0 && !NETCOREAPP2_1 && !NETCOREAPP2_2 && !NETCOREAPP3_0)
+#if (!NETCOREAPP2_0 && !NETCOREAPP2_1 && !NETCOREAPP2_2 && !NETCOREAPP3_0 && !NETCOREAPP3_1 && !NETSTANDARD2_1)
 namespace System
 {
     using System.Runtime.CompilerServices;


Added RemoveBreakableBody() to World Small namechange in variable

--- SourceFiles/FP3.0/Dynamics/World.cs
+++ SourceFiles/FP3.0/Dynamics/World.cs
@@ -59,7 +59,7 @@
         /// </summary>
         public JointRemovedDelegate JointRemoved;

-        private float _inv_dt0;
+        private float _invDt0;
         private Island _island = new Island();
         private Func<FixtureProxy, bool> _queryAABBCallback;
         private Func<int, bool> _queryAABBCallbackWrapper;
@@ -489,14 +489,14 @@
             step.dt = dt;
             if (dt > 0.0f)
             {
-                step.inv_dt = 1.0f/dt;
+                step.inv_dt = 1.0f / dt;
             }
             else
             {
                 step.inv_dt = 0.0f;
             }

-            step.dtRatio = _inv_dt0*dt;
+            step.dtRatio = _invDt0 * dt;

             //Update controllers
             foreach (Controller controller in Controllers)
@@ -534,7 +534,7 @@

             if (step.dt > 0.0f)
             {
-                _inv_dt0 = step.inv_dt;
+                _invDt0 = step.inv_dt;
             }

             if ((Flags & WorldFlags.ClearForces) != 0)
@@ -617,7 +617,7 @@
             if (hit)
             {
                 float fraction = output.Fraction;
-                Vector2 point = (1.0f - fraction)*input.Point1 + fraction*input.Point2;
+                Vector2 point = (1.0f - fraction) * input.Point1 + fraction * input.Point2;
                 return _rayCastCallback(fixture, point, output.Normal, fraction);
             }

@@ -649,7 +649,7 @@
             // Build and simulate all awake islands.
             int stackSize = BodyCount;
             if (stackSize > _stack.Length)
-                _stack = new Body[Math.Max(_stack.Length*2, stackSize)];
+                _stack = new Body[Math.Max(_stack.Length * 2, stackSize)];

             for (Body seed = BodyList; seed != null; seed = seed.Next)
             {
@@ -1091,5 +1091,13 @@
         {
             BreakableBodyList.Add(breakableBody);
         }
+
+        public void RemoveBreakableBody(BreakableBody breakableBody)
+        {
+            //The breakable body list does not contain the body you tried to remove.
+            Debug.Assert(BreakableBodyList.Contains(breakableBody));
+
+            BreakableBodyList.Remove(breakableBody);
+        }
     }
 }


Safer StreamToString

Safer StreamToString

--- Simple.OData.Client.Core/Utils.cs
+++ Simple.OData.Client.Core/Utils.cs
@@ -16,7 +16,8 @@
         public static string StreamToString(Stream stream, bool disposeStream = false)
         {
             if (!disposeStream)
-                stream.Seek(0, SeekOrigin.Begin);
+                if (stream.CanSeek)
+                    stream.Seek(0, SeekOrigin.Begin);
             var result = new StreamReader(stream).ReadToEnd();
             if (disposeStream)
                 stream.Dispose();


Removed redundant comma in collection initializer

--- src/Sharp48.ConsoleApp/Program.cs
+++ src/Sharp48.ConsoleApp/Program.cs
@@ -21,7 +21,7 @@
                             (score, game) => score*game.Grid.Squares.Max(x => x.Tile?.Value ?? 0)),
                         new TransformEvaluator(new MergeEvaluator(), (score, game) => score*4),
                         new TransformEvaluator(new MergesAwayEvaluator(), (score, game) => score*2048),
-                        new Reaching2048IsAWinEvaluator(),
+                        new Reaching2048IsAWinEvaluator()
                     }), 200000), 6));
             var ui = new GoogleChromeUI(Path.Combine(Environment.CurrentDirectory));
             using (var runner = new GameRunner(ui, solver))


shortening the lines

shortening the lines

svn path=/trunk/; revision=3965

--- src/UI.Dialog/PreferenceDialog.cs
+++ src/UI.Dialog/PreferenceDialog.cs
@@ -123,8 +123,8 @@
 			string active_theme = Preferences.Get (Preferences.GTK_RC) as string;
 			int it = 0;
 			foreach (string theme in theme_list.Keys) {
-				themelist_combo.AppendText (System.IO.Path.GetFileName (theme));
-				if (active_theme.Contains (System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileName (theme) + System.IO.Path.DirectorySeparatorChar))
+				themelist_combo.AppendText (Path.GetFileName (theme));
+				if (active_theme.Contains (Path.DirectorySeparatorChar + Path.GetFileName (theme) + Path.DirectorySeparatorChar))
 					themelist_combo.Active = it;
 				it ++;
 			}
@@ -133,7 +133,7 @@
 			themelist_combo.Changed += HandleThemeComboChanged;
 			themelist_combo.Show ();
 			themelist_combo.Sensitive = theme_filechooser.Sensitive = themecustom_radio.Active;
-			if (System.IO.File.Exists (active_theme))
+			if (File.Exists (active_theme))
 				theme_filechooser.SetFilename (Preferences.Get (Preferences.GTK_RC) as string);
 			theme_filechooser.SelectionChanged += HandleThemeFileActivated;
 			themecustom_radio.Active = (active_theme != String.Empty);


Some bugfixes

Some bugfixes

--- Src/WHampson.Cascara/SymbolTable.cs
+++ Src/WHampson.Cascara/SymbolTable.cs
@@ -263,7 +263,7 @@
         /// </returns>
         public bool IsPrimitive(string name)
         {
-            return !IsStruct(name);
+            return ContainsEntry(name) && !IsStruct(name);
         }

         /// <summary>
@@ -323,12 +323,12 @@
         /// </returns>
         public int GetElemCount(string name)
         {
+            if (!IsArray(name))
+            {
+                return 0;
+            }
+
             name = StripArrayNotation(name);
-            if (!ContainsEntry(name))
-            {
-                return 0;
-            }
-
             int count = 0;
             do
             {


What the hell was I thinking?

What the hell was I thinking?

--- Superscrot/Superscrot/Screenshot.cs
+++ Superscrot/Superscrot/Screenshot.cs
@@ -51,7 +51,6 @@

         private Bitmap _bitmap;

-        #region Properties
         /// <summary>
         /// Gets or sets the source of the screenshot.
         /// </summary>
@@ -65,9 +64,7 @@
             get { return _bitmap; }
             set { _bitmap = value; }
         }
-        #endregion
-
-        #region Metadata
+
         /// <summary>
         /// Gets or sets the path on the server, or null if the screenshot hasn't been uploaded yet.
         /// </summary>
@@ -87,9 +84,6 @@
         /// Gets or sets the original filename that the screenshot originates from, or null for non file-based captures.
         /// </summary>
         public string OriginalFileName { get; set; }
-        #endregion
-
-        #region Constructors and static load functions

         /// <summary>
         /// Initializes a new <c>Superscrot.Screenshot</c> instance.
@@ -308,7 +302,6 @@
                 return null;
             }
         }
-        #endregion

         /// <summary>
         /// Saves this screenshot to the specified stream in an image format based on the current


v1.1.14.1

--- TCC.Core/Properties/AssemblyInfo.cs
+++ TCC.Core/Properties/AssemblyInfo.cs
@@ -49,5 +49,5 @@
 // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
 // usando l'asterisco '*' come illustrato di seguito:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.1.14.0")]
-[assembly: AssemblyFileVersion("1.1.14.0")]
+[assembly: AssemblyVersion("1.1.14.1")]
+[assembly: AssemblyFileVersion("1.1.14.1")]


Fix for incorrectly removing the background colour on widgets that explicitly set one.

--- Rendering/WebCef.cs
+++ Rendering/WebCef.cs
@@ -29,11 +29,13 @@
     {
         private ChromiumWebBrowser webView;
         private string regionId;
+        private bool hasBackgroundColor = false;

         public WebCef(RegionOptions options)
             : base(options)
         {
             this.regionId = options.regionId;
+            this.hasBackgroundColor = !string.IsNullOrEmpty(options.Dictionary.Get("backgroundColor", ""));
         }

         ///
@@ -141,7 +143,12 @@
         /// <returns></returns>
         protected override string MakeHtmlSubstitutions(string cachedFile)
         {
-            string html = cachedFile.Replace("", "");
+            // Check to see if the document already has a background-color, and if it does, leave it alone.
+            string html = cachedFile;
+            if (!this.hasBackgroundColor)
+            {
+                html = cachedFile.Replace("", "");
+            }
             html = html.Replace("[[ViewPortWidth]]", WidthIntended.ToString());
             html += "";
             html += "";


flock (on Windows) - Thanks KendallB!

flock (on Windows) - Thanks KendallB!

Originally checked in by DEVSENSE\Jakub on 2012-01-23 16:55:41.72 as Changeset 2331

git-tfs-id: [https://devsense.visualstudio.com/DefaultCollection]$/Phalanger/Main;C6422

--- Source/ClassLibrary/FileSystem.cs
+++ Source/ClassLibrary/FileSystem.cs
@@ -23,6 +23,9 @@
 using System.ComponentModel;
 using System.Runtime.Serialization;
 using System.Runtime.CompilerServices;
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;

 using PHP.Core;
 #if SILVERLIGHT
@@ -1484,20 +1487,89 @@
 			return Lock(handle, operation, ref dummy);
 		}

-		/// <summary>
-		/// Portable advisory file locking.
-		/// </summary>
-		/// <param name="handle"></param>
-		/// <param name="operation"></param>
-		/// <param name="wouldblock"></param>
-		/// <returns></returns>
-        [ImplementsFunction("flock", FunctionImplOptions.NotSupported)]
-		public static bool Lock(PhpResource handle, int operation, ref int wouldblock)
-		{
-			PhpException.FunctionNotSupported();
-			return false;
-		}
-
-		#endregion
-	}
+        /// <summary>
+        /// Portable advisory file locking.
+        /// </summary>
+        /// <param name="handle">A file system pointer resource that is typically created using fopen().</param>
+        /// <param name="operation">Operation is one of the following:
+        /// <c>LOCK_SH</c> to acquire a shared lock (reader).
+        /// <c>LOCK_EX</c> to acquire an exclusive lock (writer).
+        /// <c>LOCK_UN</c> to release a lock (shared or exclusive).
+        ///
+        /// It is also possible to add <c>LOCK_NB</c> as a bitmask to one of the above operations if you don't want flock() to block while locking. (not supported on Windows)
+        /// </param>
+        /// <param name="wouldblock">The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition). (not supported on Windows)</param>
+        /// <returns>Returns <c>true</c> on success or <c>false</c> on failure.</returns>
+        [ImplementsFunction("flock")]
+        public static bool Lock(PhpResource handle, int operation, ref int wouldblock)
+        {
+            // Get the native file handle for the PHP resource
+            var phpStream = PhpStream.GetValid(handle);
+            if (phpStream == null) return false;
+
+            var fileStream = phpStream.RawStream as FileStream;
+            if (fileStream == null) return false;
+
+            //
+            if (EnvironmentUtils.IsDotNetFramework)
+            {
+                return Lock_dotNET(fileStream, (StreamLockOptions)operation);
+            }
+            else
+            {
+                PhpException.FunctionNotSupported();
+                return false;
+            }
+        }
+
+        #region flock (Windows)
+
+        // Constants passed to LockFileEx for the flags
+        private const uint LOCKFILE_FAIL_IMMEDIATELY = 0x00000001;
+        private const uint LOCKFILE_EXCLUSIVE_LOCK = 0x00000002;
+
+        [DllImport("kernel32.dll")]
+        static extern bool LockFileEx(SafeFileHandle hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, [In] ref NativeOverlapped lpOverlapped);
+
+        [DllImport("kernel32.dll")]
+        static extern bool UnlockFileEx(SafeFileHandle hFile, uint dwReserved, uint nNumberOfBytesToUnlockLow, uint nNumberOfBytesToUnlockHigh, [In] ref NativeOverlapped lpOverlapped);
+
+        private static bool Lock_dotNET(FileStream/*!*/fileStream, StreamLockOptions op)
+        {
+            Debug.Assert(fileStream != null);
+
+            var hFile = fileStream.SafeFileHandle;
+
+            // Set up some parameters
+            uint low = 1, high = 0;
+            var offset = new NativeOverlapped();
+            bool noBlocking = (op & StreamLockOptions.NoBlocking) != 0;
+
+            // bug for bug compatible with Unix
+            UnlockFileEx(hFile, 0, low, high, ref offset);
+
+            //
+            switch (op & ~StreamLockOptions.NoBlocking)
+            {
+                case StreamLockOptions.Exclusive:
+                    // Exclusive lock
+                    return LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK + (noBlocking ? LOCKFILE_FAIL_IMMEDIATELY : 0), 0, low, high, ref offset);
+
+                case StreamLockOptions.Shared:
+                    // Shared lock
+                    return LockFileEx(hFile, (noBlocking ? LOCKFILE_FAIL_IMMEDIATELY : 0), 0, low, high, ref offset);
+
+                case StreamLockOptions.Unlock:
+                    // Unlock always succeeds
+                    return true;
+            }
+
+            // Bad call
+            return false;
+        }
+
+        #endregion
+
+        #endregion
+    }
 }


refresh session when accesstoken changes

--- Scripts/StomtAPI.cs
+++ Scripts/StomtAPI.cs
@@ -603,7 +603,11 @@
 				if (responseData["meta"].Keys.Contains("accesstoken"))
 				{
 					string accesstoken = (string)responseData["meta"]["accesstoken"];
-					this.config.SetAccessToken(accesstoken);
+					string oldAccessToken = this.config.GetAccessToken();
+					if (!oldAccessToken.Equals(accesstoken)) {
+						this.config.SetAccessToken(accesstoken);
+						this.RequestSession(null, null); // set/update user
+					}
 				}
 			}


Update Form1.cs

Update Form1.cs

Translated page

--- SMG/SMG/Form1.cs
+++ SMG/SMG/Form1.cs
@@ -165,6 +165,18 @@

         private void button9_Click(object sender, EventArgs e)
         {
+                    btnNewGame.Text = "開始";
+            btn_load.Text = "ロードゲーム";
+            btn_options.Text = "オプション";
+            btn_audio.Text = "オーディオ";
+            btn_music.Text = "音楽";
+            btn_musicStyle.Text = "音楽スタイル";
+            button7.Text = "言語";
+            button8.Text = "英語";
+            button9.Text = "日本語";
+            button10.Text ="リーダーボード";
+            btn_Quit.Text ="終了する";
+
             Console.WriteLine("Japanese was selected");
         }


WIP #110 - Remove an outdated test

WIP #110 - Remove an outdated test

--- Test.CSF/TestExceptionExtensions.cs
+++ Test.CSF/TestExceptionExtensions.cs
@@ -179,31 +179,6 @@
       }
     }

-    [Test]
-    public void TestTryFixStackTraceFailure()
-    {
-      if(!Util.ReflectionHelper.IsMono())
-      {
-        Assert.Ignore("This test is not valid when not running on the open source Mono framework.  When executing " +
-                      "against the official .NET framework, the 'private framework method' implementation for fixing " +
-                      "stack traces will work and thus 'TryFixStackTrace' will not fail as intended.");
-      }
-
-      bool success = false;
-      CustomException fixedException = null;
-
-      try
-      {
-        throw new CustomException();
-      }
-      catch(CustomException ex)
-      {
-        success = ex.TryFixStackTrace(out fixedException);
-      }
-
-      Assert.IsFalse(success);
-    }
-
     #endregion

     #region contained custom exception


Trying NewtonSoft.json. Bad idea.

Trying NewtonSoft.json. Bad idea.

--- Tests/Integration/WebApp/Startup.cs
+++ Tests/Integration/WebApp/Startup.cs
@@ -41,6 +41,23 @@
                     options.RequireHttpsMetadata = false;
                     options.ClientId = "WebApp";
                     options.ClientSecret = "WebApp.Secret";
+                    options.Events.OnMessageReceived = message =>
+                    {
+                        var m = message.HttpContext.GetRequestMonitor();
+                        using( m.OpenInfo( "Receiving Oidc message" ) )
+                        {
+                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(
+                                message,
+                                Newtonsoft.Json.Formatting.Indented,
+                                new Newtonsoft.Json.JsonSerializerSettings()
+                                {
+                                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
+                                    MaxDepth = 2
+                                } );
+                            m.Info( json );
+                        }
+                        return Task.CompletedTask;
+                    };
                     options.Events.OnTicketReceived = c => c.WebFrontAuthRemoteAuthenticateAsync<IUserOidcInfo>( payload =>
                     {
                         payload.SchemeSuffix = "";


Update Kernel.cs

Update Kernel.cs

--- Tests/Kernels/GraphicTest/Kernel.cs
+++ Tests/Kernels/GraphicTest/Kernel.cs
@@ -49,8 +49,8 @@
             Pen pen = new Pen(Color.Red);
             aCanvas.DrawPoint(pen, 69, 69);

-            //Color color = aCanvas.GetPointColor(69, 69);
-            //Assert.AreEqual(color.ToArgb(), Color.Red.ToArgb(), "GetPointColor returns correct value");
+            Color color = aCanvas.GetPointColor(69, 69);
+            Assert.AreEqual(color.ToArgb(), Color.Red.ToArgb(), "GetPointColor returns correct value");

             /* A GreenYellow horizontal line */
             pen.Color = Color.GreenYellow;


CI Build Number Updated

CI Build Number Updated

git-svn-id: 7f05ad86c4f4f5ca50611136d23b835364929451@253 b33fba48-7441-0410-8d5c-f397f7ceaa6c

--- Source/Properties/AssemblyInfo.cs
+++ Source/Properties/AssemblyInfo.cs
@@ -7,7 +7,7 @@
 [assembly: AssemblyProduct("Moq")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
-[assembly: AssemblyVersion("3.0.925.4")]
+[assembly: AssemblyVersion("3.0.925.5")]
 [assembly: AssemblyFileVersion("3.0.0.0")]

 [assembly: InternalsVisibleTo("Moq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009f7a95086500f8f66d892174803850fed9c22225c2ccfff21f39c8af8abfa5415b1664efd0d8e0a6f7f2513b1c11659bd84723dc7900c3d481b833a73a2bcf1ed94c16c4be64d54352c86956c89930444e9ac15124d3693e3f029818e8410f167399d6b995324b635e95353ba97bfab856abbaeb9b40c9b160070c6325e22ddc")]


Another test case

Another test case

--- Tests/Theraot/TransactionalTests.cs
+++ Tests/Theraot/TransactionalTests.cs
@@ -302,6 +302,24 @@
             // We did rollback and commit again
             Assert.AreEqual(11, needleA.Value);
             Assert.AreEqual(5, needleB.Value);
+        }
+
+        [Test]
+        public void SimpleTest()
+        {
+            var needle = new Transact.Needle<int>(1);
+            var autoResetEvent = new AutoResetEvent(false);
+            new Thread(() =>
+            {
+                using (var transaction = new Transact())
+                {
+                    needle.Value = 2;
+                    transaction.Commit();
+                    autoResetEvent.Set();
+                }
+            }).Start();
+            autoResetEvent.WaitOne();
+            Assert.AreEqual(2, needle.Value);
         }

         [Test]


add error test

add error test

--- UnitTests/Class1.cs
+++ UnitTests/Class1.cs
@@ -1,4 +1,5 @@
 using IntranetGJAK.Controllers;
+using Microsoft.AspNet.Mvc;
 using Xunit;

 namespace UnitTests
@@ -12,6 +13,19 @@
         {
             Assert.True(true);
         }
+
+        [Fact]
+        public void Error()
+        {
+            var controller = new HomeController();
+            Assert.NotNull(controller);
+            var result = controller.Error();
+            Assert.NotNull(result);
+            Assert.IsType<ViewResult>(result);
+            ViewResult view = (ViewResult)result;
+            Assert.NotNull(view);
+            Assert.Equal("~/Views/Shared/Error.cshtml", view.ViewName);
+        }
     }

     public class UploadController


입력받은 좌표를 로그 값에 맞는 숫자로 출력하는 로직 수정

입력받은 좌표를 로그 값에 맞는 숫자로 출력하는 로직 수정

--- Transformation/LogTransformation.cs
+++ Transformation/LogTransformation.cs
@@ -353,10 +353,10 @@
             double CurrentPoint = 0; // 현재까지 이동한 좌표
             double RulerCount = 0; // 눈금의 개수
             double Gap = 0; // 눈금의 숫자 간격
+            double delta = 0; // 숫자 1에 해당하는 간격
             int i = 0; // 반복제어변수
             int j = 0; // 반복제어변수
             int k = 0; // 반복제어변수
-            double delta = 0; // 숫자 1에 해당하는 간격

             if (isX)
             {


– updated the AssemblyInfo

– updated the AssemblyInfo

--- TruckApp/Properties/AssemblyInfo.cs
+++ TruckApp/Properties/AssemblyInfo.cs
@@ -25,5 +25,5 @@
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
 [assembly: AssemblyVersion("0.10.*")]
-[assembly: AssemblyFileVersion("0.10.*")]
+[assembly: AssemblyFileVersion("0.10.0.0")]
 [assembly: ComVisible(false)]


Version 1.6.1

Version 1.6.1

--- TypeLess/Properties/AssemblyInfo.cs
+++ TypeLess/Properties/AssemblyInfo.cs
@@ -25,7 +25,7 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.6")]
-[assembly: AssemblyFileVersion("1.6")]
+[assembly: AssemblyVersion("1.6.1")]
+[assembly: AssemblyFileVersion("1.6.1")]
 [assembly: InternalsVisibleTo("TypeLess.Mail")]
 [assembly: InternalsVisibleTo("TypeLess.ResourceAccess")]


- DEADLINE SOLUTIONS.

- DEADLINE SOLUTIONS.

--- Unity/Assets/Code/Game/Character.cs
+++ Unity/Assets/Code/Game/Character.cs
@@ -15,7 +15,7 @@
 	[SerializeField] private Transform miniDemonRoot;
 	[SerializeField] private ParticleSystem poofCloud;

-	public float YCutOffOffset = -45.0f;
+	public float YCutOffOffset = -70.0f;

 	GameObject demonGO;

@@ -117,7 +117,9 @@

 		foreach( var materialGO in materialList )
 		{
-			materialGO.GetComponent<Renderer>().material.SetFloat( "_YCutOff", screenPoint.y + YCutOffOffset );
+			const float bullshit = -0.1f;
+
+			materialGO.GetComponent<Renderer>().material.SetFloat( "_YCutOff", screenPoint.y + ( Screen.height * bullshit ) );
 			materialGO.GetComponent<Renderer>().material.SetFloat( "_Alpha", alpha );
 		}
 	}


Use 7-bit encoding for length-prefixes

Use 7-bit encoding for length-prefixes

--- Utilities/BinaryStreamExtensions.cs
+++ Utilities/BinaryStreamExtensions.cs
@@ -67,7 +67,7 @@
         public static void WriteCompressedString(this BinaryWriter writer, string str, Encoding encoding)
         {
             var zipped = ZipText(str, encoding);
-            writer.Write(zipped.Length);
+            Write7BitEncodedInt(writer, zipped.Length);
             writer.Write(zipped);
         }

@@ -76,7 +76,7 @@
         /// </summary>
         public static string ReadCompressedString(this BinaryReader reader, Encoding encoding)
         {
-            var length = reader.ReadInt32();
+            var length = Read7BitEncodedInt(reader);
             var zipped = reader.ReadBytes(length);
             return Unzip(zipped, encoding);
         }


Rename member to better reflect behavior

--- Utilities/MarkdigAgg/AggRenderer.cs
+++ Utilities/MarkdigAgg/AggRenderer.cs
@@ -50,17 +50,17 @@
 		private readonly Stack<GuiWidget> stack = new Stack<GuiWidget>();
 		private char[] buffer;

-		public GuiWidget Document { get; }
+		public GuiWidget RootWidget { get; }

 		public Uri BaseUri { get; set; }
 		public List<MarkdownDocumentLink> ChildLinks { get; internal set; }

-		public AggRenderer(GuiWidget document)
+		public AggRenderer(GuiWidget rootWidget)
 		{
 			buffer = new char[1024];
-			Document = document;
-
-			stack.Push(document);
+			RootWidget = rootWidget;
+
+			stack.Push(rootWidget);

 			// Default block renderers
 			ObjectRenderers.Add(new AggCodeBlockRenderer());
@@ -90,7 +90,7 @@
 		public override object Render(MarkdownObject markdownObject)
 		{
 			Write(markdownObject);
-			return Document;
+			return RootWidget;
 		}

 		/// <summary>


Update the static content module to fit the new API.

--- data/mango-tool/layouts/default/StaticContentModule.cs
+++ data/mango-tool/layouts/default/StaticContentModule.cs
@@ -16,7 +16,7 @@
 //  module.
 //

-namespace $APPNAME {
+namespace AppNameFoo {

 	public class StaticContentModule : MangoModule {

@@ -26,7 +26,7 @@

 		}

-		public static void Content (MangoContext ctx)
+		public static void Content (IMangoContext ctx)
 		{
 			string path = ctx.Request.LocalPath;


Fix default category for new addins

Fix default category for new addins

--- Templates/Properties/AddinInfo.cs
+++ Templates/Properties/AddinInfo.cs
@@ -9,6 +9,6 @@
 )]

 [assembly:AddinName ("${ProjectName}")]
-[assembly:AddinCategory ("${ProjectName}")]
+[assembly:AddinCategory ("IDE extensions")]
 [assembly:AddinDescription ("${ProjectName}")]
-[assembly:AddinAuthor ("${AuthorName}")]+[assembly:AddinAuthor ("${AuthorName}")]


Bumped version to reflect what's currently in development.

--- Terraria_Server/Server/Statics.cs
+++ Terraria_Server/Server/Statics.cs
@@ -5,7 +5,7 @@
 {
     public static class Statics
     {
-        public const int BUILD = 28;
+        public const int BUILD = 29;
         public const int CURRENT_TERRARIA_RELEASE = 12;
         public static string CURRENT_TERRARIA_RELEASE_STR = CURRENT_TERRARIA_RELEASE.ToString();


tests

tests

--- Test/TestsModel/CoreModelTests.cs
+++ Test/TestsModel/CoreModelTests.cs
@@ -106,6 +106,7 @@
             #region Arrange
             var expectedFields = new List<NameAndType>();
             expectedFields.Add(new NameAndType("AdjustmentAmount", "System.Decimal", new List<string>()));
+            expectedFields.Add(new NameAndType("AdjustmentComments", "System.String", new List<string>()));
             expectedFields.Add(new NameAndType("BypassEmail", "System.Boolean", new List<string>()));
             expectedFields.Add(new NameAndType("Confirm", "System.Boolean", new List<string>()));
             expectedFields.Add(new NameAndType("LabComments", "System.String", new List<string>()));
@@ -121,6 +122,7 @@
             #region Arrange
             var expectedFields = new List<NameAndType>();
             expectedFields.Add(new NameAndType("AdjustmentAmount", "System.Decimal", new List<string>()));
+            expectedFields.Add(new NameAndType("AdjustmentComments", "System.String", new List<string>()));
             expectedFields.Add(new NameAndType("BypassEmail", "System.Boolean", new List<string>()));
             expectedFields.Add(new NameAndType("Confirm", "System.Boolean", new List<string>()));
             expectedFields.Add(new NameAndType("LabComments", "System.String", new List<string>()));


ThreadDebug, ThreadTrace の文字列フォーマット変更。

ThreadDebug, ThreadTrace の文字列フォーマット変更。

--- Util/ThreadDebug.cs
+++ Util/ThreadDebug.cs
@@ -75,19 +75,10 @@
             var msg = new StringBuilder();

             msg.Append('[');
-            msg.Append(DateTime.Now.ToString("HH:mm:ss"));
+            msg.Append(DateTime.Now.ToString(@"yyyy-MM-dd HH:mm:ss"));
             msg.Append(@"][TID:");
             msg.Append(Thread.CurrentThread.ManagedThreadId);
-            msg.Append(']');
-
-            if (text != null)
-            {
-                msg.Append(' ');
-                msg.Append(text);
-                msg.Append(' ');
-            }
-
-            msg.Append('[');
+            msg.Append(@"][");
             msg.Append(member);
             msg.Append('@');
             msg.Append(Path.GetFileName(file));
@@ -95,6 +86,12 @@
             msg.Append(line);
             msg.Append(']');

+            if (text != null)
+            {
+                msg.Append('#');
+                msg.Append(text);
+            }
+
             return msg.ToString();
         }
     }


Added SetInt to SetMaterialValue

Added SetInt to SetMaterialValue

--- SetMaterialValue.cs
+++ SetMaterialValue.cs
@@ -116,6 +116,19 @@
 	}

+	public void SetInt(int Value)
+	{
+		if (GlobalUniform)
+		{
+			Shader.SetGlobalInt(Uniform, Value);
+		}
+		else if ( material )
+		{
+			material.SetInt (Uniform, Value);
+		}
+	}
+
+
 	public void SetColor(Color Value)
 	{
 		if (GlobalUniform)


folder list method in FileHandler

folder list method in FileHandler

DON'T ASK ME HOW THIS WORKS I DON'T KNOW I JUST RANDOMED AND THEN
SUDDENLY IT WORKED LIKE WUT EVEN

--- Voxalia/Shared/Files/FileHandler.cs
+++ Voxalia/Shared/Files/FileHandler.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Text;
+using System.Linq;
 using System.IO;
 using System.IO.Compression;

@@ -41,7 +42,7 @@
                 }
                 else
                 {
-                    Files.Add(new PakkedFile(file.Replace(BaseDirectory, "")));
+                    Files.Add(new PakkedFile(file.Replace(BaseDirectory, "").ToLower()));
                 }
             }
             int id = 0;
@@ -57,7 +58,6 @@
                     {
                         continue;
                     }
-                    SysConsole.Output(OutputType.INIT, "--> " + name);
                     Files.Add(new PakkedFile(name, id, zent));
                 }
                 id++;
@@ -192,17 +192,36 @@
         {
             return encoding.GetString(ReadBytes(filename)).Replace("\r", "");
         }
-
-        /// <summary>
-        /// Makes all directories along the filepath.
-        /// </summary>
-        public void MakeDirs(string filepath)
-        {
-            string fname = BaseDirectory + CleanFileName(filepath) + "/";
-            if (!Directory.Exists(fname))
-            {
-                Directory.CreateDirectory(fname);
-            }
+
+        /// <summary>
+        /// Returns a list of all folders that contain the filepath.
+        /// </summary>
+        public List<string> ListFolders(string filepath)
+        {
+            List<string> folds = new List<string>();
+            string fname = "/" + CleanFileName("/" + filepath);
+            if (fname.EndsWith("/"))
+            {
+                fname = fname.Substring(0, fname.Length - 1);
+            }
+            string fn2 = fname + "/";
+            if (fn2 == "//")
+            {
+                fn2 = "/";
+            }
+            for (int i = 0; i < Files.Count; i++)
+            {
+                string fina = "/" + Files[i].Name;
+                if (fina.StartsWith(fn2))
+                {
+                    string fold = "/" + (Files[i].Name.LastIndexOf('/') <= 0 ? "": Files[i].Name.Substring(0, Files[i].Name.LastIndexOf('/')));
+                    if (fold.StartsWith(fn2) && !folds.Contains(fold))
+                    {
+                        folds.Add(fold);
+                    }
+                }
+            }
+            return folds;
         }

         /// <summary>


add times to the test output

add times to the test output

--- SPO_CS/src/mTest.cs
+++ SPO_CS/src/mTest.cs
@@ -15,6 +15,10 @@

 public static class mTest {

+	[System.Runtime.InteropServices.DllImport("kernel32.dll")]
+	private static extern bool QueryThreadCycleTime(System.IntPtr aThreadHandle, out tNat64 aCycles);
+	private static readonly System.IntPtr PseudoHandle = (System.IntPtr)(-2);
+
 	public enum tResult {
 		OK,
 		Fail,
@@ -67,8 +71,31 @@
 				aDebugStream(TestRun._Name);
 				if (aFilters is null || aFilters.Any(TestRun._Name.Contains)) {
 					try {
+						QueryThreadCycleTime(PseudoHandle, out var ClocksStart);
 						TestRun._TestFunc(aText => aDebugStream("| " + aText));
-						aDebugStream("-> OK");
+						QueryThreadCycleTime(PseudoHandle, out var ClocksEnd);
+
+						var Value_00 = (ClocksEnd - ClocksStart) * 100;
+						var E = "";
+						if (Value_00 >= 1_000_000_000_00) {
+							E = "G";
+							Value_00 /= 1_000_000_000;
+						} else if (Value_00 >= 1_000_000_00) {
+							E = "M";
+							Value_00 /= 1_000_000;
+						} else if (Value_00 >= 1_000_00) {
+							E = "k";
+							Value_00 /= 1_000;
+						}
+						var Value = Value_00 / 100;
+						var SubValue = "";
+						if (Value < 100) {
+							SubValue += "." + ((Value_00 / 10) % 10);
+						}
+						if (Value < 10) {
+							SubValue += Value_00 % 10;
+						}
+						aDebugStream($"-> OK ({Value}{SubValue}{E} Clocks)");
 						aDebugStream("");
 						return tResult.OK;
 					} catch (System.Exception e) {
@@ -89,6 +116,8 @@
 					aFilters = null;
 				}
 				var Result = tResult.Skip;
+				var StopWatch = new System.Diagnostics.Stopwatch();
+				StopWatch.Start();
 				foreach (var Test in Tests._Tests) {
 					switch (Test.Run(aText => aDebugStream(cTab + aText), aFilters)) {
 						case tResult.OK: {
@@ -96,16 +125,30 @@
 							break;
 						}
 						case tResult.Fail: {
-							aDebugStream("-> Fail");
-							aDebugStream("");
-							return tResult.Fail;
+							Result = tResult.Fail;
+							break;
 						}
 						case tResult.Skip: {
 							break;
 						}
 					}
 				}
-				aDebugStream($"-> {Result}");
+				StopWatch.Stop();
+				var MSec = StopWatch.ElapsedMilliseconds;
+				var E = "mSec";
+				var Value_00 = MSec * 100;
+				if (MSec >= 60 * 60 * 1000) {
+					E = "Hour";
+					Value_00 /= 60 * 60 * 1000;
+				} else if (MSec >= 60 * 1000) {
+					E = "Min";
+					Value_00 /= 60 * 1000;
+				} else if (MSec >= 1000) {
+					E = "Sec";
+					Value_00 /= 1000;
+				}
+
+				aDebugStream($"-> {Result} ({Value_00/100}.{(Value_00/10)%10}{Value_00%10} {E})");
 				aDebugStream("");
 				return Result;
 			}


Add ExpandAll method to TreeView

Add ExpandAll method to TreeView

--- Xwt/Xwt/TreeView.cs
+++ Xwt/Xwt/TreeView.cs
@@ -302,6 +302,20 @@
 		{
 			Backend.CollapseRow (pos);
 		}
+
+		/// <summary>
+		/// Recursively expands all nodes of the tree
+		/// </summary>
+		public void ExpandAll ()
+		{
+			if (DataSource != null) {
+				var nc = DataSource.GetChildrenCount (null);
+				for (int n=0; n<nc; n++) {
+					var p = DataSource.GetChild (null, n);
+					Backend.ExpandRow (p, true);
+				}
+			}
+		}

 		/// <summary>
 		/// Saves the status of the tree


/help <command> should show the help for that command, not execute it

--- TrueCraft/Commands/HelpCommand.cs
+++ TrueCraft/Commands/HelpCommand.cs
@@ -29,7 +29,7 @@
             ICommand found;
             if ((found = Program.CommandManager.FindByName(identifier)) != null)
             {
-                found.Handle(client, identifier, new string[0]);
+                found.Help(client, identifier, new string[0]);
                 return;
             }
             else if ((found = Program.CommandManager.FindByAlias(identifier)) != null)


Remove MyClass

Remove MyClass

--- TwitterMonkey.Portable/MyClass.cs
+++ TwitterMonkey.Portable/MyClass.cs
@@ -1,7 +0,0 @@
-using System;
-using System.IO;
-namespace TwitterMonkey.Portable {
-  public class MyClass {
-  }
-}
-


Fixed handling of empty lists in long-polling for tail requests

--- WebApi.Pagination/HttpPagination.cs
+++ WebApi.Pagination/HttpPagination.cs
@@ -152,7 +152,7 @@
                 return request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
             }

-            bool openEndedRange = range.From.HasValue && !range.To.HasValue;
+            bool openEndedRange = !(range.From.HasValue && range.To.HasValue);
             var elements = openEndedRange
                 ? await paginatedData.ToListLongPollAsync(maxAttempts, delayMs, cancellationToken)
                 : paginatedData.ToList();


updated assembly version

updated assembly version

--- WebSocket4Net/GlobalAssemblyInfo.cs
+++ WebSocket4Net/GlobalAssemblyInfo.cs
@@ -8,5 +8,5 @@
 [assembly: AssemblyCopyright("Copyright © websocket4net.codeplex.com 2012")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("0.1.0.0")]
+[assembly: AssemblyFileVersion("0.1.0.0")]


Email regex fix

Email regex fix


Handle material set changes via an explicit sync instead of an event

--- Viewer/src/figure/FigureFacade.cs
+++ Viewer/src/figure/FigureFacade.cs
@@ -11,7 +11,9 @@
 	private readonly ControlVertexProvider controlVertexProvider;
 	private readonly FigureRendererLoader figureRendererLoader;

+	private MaterialSetOption currentMaterialSet;
 	private FigureRenderer renderer;
+
 	private List<FigureFacade> children = new List<FigureFacade>();

 	public IFigureAnimator Animator { get; set; } = null;
@@ -21,13 +23,9 @@
 		this.model = model;
 		this.controlVertexProvider = controlVertexProvider;
 		this.figureRendererLoader = figureRendererLoader;
-
-		model.MaterialSetChanged += Model_MaterialSetChanged;
-		SyncMaterialSet();
 	}

 	public void Dispose() {
-		model.MaterialSetChanged -= Model_MaterialSetChanged;
 		controlVertexProvider.Dispose();
 		renderer.Dispose();
 	}
@@ -36,18 +34,19 @@
 	public FigureModel Model => model;
 	public int VertexCount => controlVertexProvider.VertexCount;

-	private void Model_MaterialSetChanged(MaterialSetOption oldMaterialSet, MaterialSetOption newMaterialSet) {
-		SyncMaterialSet();
-	}
+	private void SyncMaterialSet() {
+		if (model.MaterialSet != currentMaterialSet) {
+			var newRenderer = figureRendererLoader.Load(definition.Directory, model.MaterialSet.Label);
+			renderer?.Dispose();

-	private void SyncMaterialSet() {
-		string materialSetName = model.MaterialSet.Label;
-		var newRenderer = figureRendererLoader.Load(definition.Directory, materialSetName);
-		renderer?.Dispose();
-		renderer = newRenderer;
+			renderer = newRenderer;
+			currentMaterialSet = model.MaterialSet;
+		}
 	}

 	public void SyncWithModel() {
+		SyncMaterialSet();
+
 		var childControlVertexProviders = children
 			.Select(child => child.controlVertexProvider)
 			.ToList();


исправлена возвращаемая коллекция ID лайков при Get запросе

--- VkNet/Categories/LikesCategory.cs
+++ VkNet/Categories/LikesCategory.cs
@@ -1,4 +1,5 @@
-using VkNet.Model.RequestParams;
+using VkNet.Utils;
+using VkNet.Model.RequestParams;

 namespace VkNet.Categories
 {
@@ -39,12 +40,10 @@
 		/// Страница документации ВКонтакте <see href="http://vk.com/dev/likes.getList"/>.
 		/// </remarks>
 		[ApiVersion("5.44")]
-		public ReadOnlyCollection<long> GetList(LikesGetListParams @params, bool skipAuthorization = true)
+		public VkCollection<long> GetList(LikesGetListParams @params, bool skipAuthorization = true)
 		{
 		    @params.Extended = false;
-			VkResponseArray response = _vk.Call("likes.getList", @params, skipAuthorization);
-
-            return response.ToReadOnlyCollectionOf<long>(x => x);
+			return _vk.Call("likes.getList", @params, skipAuthorization).ToVkCollectionOf<long>(x => x);
 		}

 		/// <summary>


Fixed XAML namespaces

Fixed XAML namespaces

--- WPFLib/Properties/AssemblyInfo.cs
+++ WPFLib/Properties/AssemblyInfo.cs
@@ -54,7 +54,9 @@
 [assembly: AssemblyFileVersion("1.0.0.0")]

 //XAML NAMESPACE DEFS
-[assembly: XmlnsPrefix("http://webmaster442.hu/wpflib", "WPFLib.Controls")]
-[assembly: XmlnsPrefix("http://webmaster442.hu/wpflib", "WPFLib.Converters")]
-[assembly: XmlnsPrefix("http://webmaster442.hu/wpflib", "WPFLib.Dialogs")]
-[assembly: XmlnsPrefix("http://webmaster442.hu/wpflib", "WPFLib.Extensions")]+[assembly: XmlnsPrefix("http://github.com/webmaster442/WPFLib", "wpflib")]
+[assembly: XmlnsDefinition("http://github.com/webmaster442/WPFLib", "WPFLib.Controls")]
+[assembly: XmlnsDefinition("http://github.com/webmaster442/WPFLib", "WPFLib.Converters")]
+[assembly: XmlnsDefinition("http://github.com/webmaster442/WPFLib", "WPFLib.Dialogs")]
+[assembly: XmlnsDefinition("http://github.com/webmaster442/WPFLib", "WPFLib.Extensions")]
+[assembly: XmlnsDefinition("http://github.com/webmaster442/WPFLib", "WPFLib.Shaders")]


FixUp Language parse

FixUp Language parse

--- WTM.Crawler/Parsers/ShotParser.cs
+++ WTM.Crawler/Parsers/ShotParser.cs
@@ -275,14 +275,14 @@

         private static List<string> GetLanguages(XPathNavigator navigator)
         {
-            var languageRegex = new Regex(@"images/flags/([a-z]*).png");
-            var nodes = navigator.Select("//div[@id='solve_station']/div[@class='col_center clearfix']/ul[@class='language_flags']/li/img/@src");
+            var languageRegex = new Regex(@"flag-c flag-([a-z]*)");
+            var nodes = navigator.Select("//div[@id='solve_station']/div[@class='col_center clearfix']/ul[@class='language_flags']/li/img/@class");
             var languageList = new List<string>(nodes.Count);
             while (nodes.MoveNext())
             {
                 var match = languageRegex.Match(nodes.Current.InnerXml);
                 if (!match.Success) continue;
-
+
                 languageList.Add(match.Groups[1].Value);
             }
             return languageList;


CA-169167: Screen resolution is less than the default value after switch to remote desktop

Fixing unused field as warning as error build issue

--- XenAdmin/ConsoleView/XSVNCScreen.cs
+++ XenAdmin/ConsoleView/XSVNCScreen.cs
@@ -69,7 +69,6 @@
         private int ConnectionRetries = 0;

         private volatile bool useVNC = true;
-        private volatile bool autoSwitchRDPLater = false;

         private bool autoCaptureKeyboardAndMouse = true;
         internal bool showConnectionBar = true;


[Mac] Optimize Dialog button padding

[Mac] Optimize Dialog button padding

Dialog buttons have an additional padding on Mac,
which is automatically added by NSAlert or by
system panels (open, save, etc.). This commit
adds this additional padding to all dialog buttons
in custom dialogs.

--- Xwt.XamMac/Xwt.Mac/DialogBackend.cs
+++ Xwt.XamMac/Xwt.Mac/DialogBackend.cs
@@ -113,6 +113,8 @@
 				button.Clicked += delegate {
 					OnClicked (tb);
 				};
+				button.MinWidth = 77; // Dialog buttons have a minimal width of 77px on Mac
+
 				buttonBox.PackEnd (button);
 				buttons [b] = button;
 				UpdateButton (b, button);
@@ -143,6 +145,11 @@
 			realButton.Image = b.Image;
 			realButton.Sensitive = b.Sensitive;
 			realButton.Visible = b.Visible;
+
+			// Dialog buttons on Mac have a 8px horizontal padding
+			realButton.WidthRequest = -1;
+			var s = realButton.Surface.GetPreferredSize ();
+			realButton.WidthRequest = s.Width + 16;
 		}

 		public void RunLoop (IWindowFrameBackend parent)


Correcciones

Correcciones

--- YUTPLAT/Services/MedicionService.cs
+++ YUTPLAT/Services/MedicionService.cs
@@ -196,7 +196,7 @@

                             celdaHeatMapViewModel.IdIndicador = medicionPorMes.IndicadorID;
                             celdaHeatMapViewModel.Medicion = medicionPorMes.Valor;
-                            celdaHeatMapViewModel.ColorMeta = "black";//ObtenerColorCeldaHeatMap(medicionPorMes);
+                            celdaHeatMapViewModel.ColorMeta = ObtenerColorCeldaHeatMap(medicionPorMes);
                             celdaHeatMapViewModel.MedicionCargada = true;
                         }


Add a try/catch when loading assembly

Add a try/catch when loading assembly

--- Wax.Model/VisualStudio/Project.cs
+++ Wax.Model/VisualStudio/Project.cs
@@ -139,21 +139,28 @@
                 //Reference can be a project reference and not be built
                 if (File.Exists(reference.Path))
                 {
-                    //Load first-tier reference
-                    var assembly = Assembly.LoadFile(reference.Path);
-                    //Get its references
-                    var referenced = assembly.GetReferencedAssemblies();
-                    var directory = new FileInfo(reference.Path).Directory;
-                    foreach (var referred in referenced)
+                    try
                     {
-                        //If second-tier reference is not in project references
-                        if (!References.Any(r => r.Name == referred.Name))
+                        //Load first-tier reference
+                        var assembly = Assembly.LoadFile(reference.Path);
+                        //Get its references
+                        var referenced = assembly.GetReferencedAssemblies();
+                        var directory = new FileInfo(reference.Path).Directory;
+                        foreach (var referred in referenced)
                         {
-                            //Try to resolve it from first-tier reference folder like MSBuild does
-                            var existingDll = directory.GetFiles().FirstOrDefault(f => f.Name == string.Concat(referred.Name, ".dll"));
-                            if (existingDll != null)
-                                projectOutput.Add(new ProjectOutput(rootProject, existingDll.Name, BuildFileGroups.Built));
+                            //If second-tier reference is not in project references
+                            if (!References.Any(r => r.Name == referred.Name))
+                            {
+                                //Try to resolve it from first-tier reference folder like MSBuild does
+                                var existingDll = directory.GetFiles().FirstOrDefault(f => f.Name == string.Concat(referred.Name, ".dll"));
+                                if (existingDll != null)
+                                    projectOutput.Add(new ProjectOutput(rootProject, existingDll.Name, BuildFileGroups.Built));
+                            }
                         }
+                    }
+                    catch
+                    {
+                        //Reference cannot be loaded
                     }
                 }
             }