using System;
using System.Threading;
using Topshelf;

namespace Tellurium.VisualAssertion.Dashboard
{
    public class Program
    {
        public static void Main(string[] args)
        {
#if DEBUG
            using (var server = new WebServer())
            {
                server.Run(consoleMode:true);
                Console.ReadKey();
            }
#else
            InstallDashboardService();
#endif
        }

        private static void InstallDashboardService()
        {
            HostFactory.Run(hostConfiguration =>
            {
                hostConfiguration.Service<WebServer>(wsc =>
                {
                    wsc.ConstructUsing(() => new WebServer());
                    wsc.WhenStarted(server =>
                    {
                       server.Run();
                    });
                    wsc.WhenStopped(ws => ws.Dispose());
                });
                hostConfiguration.RunAsLocalSystem();
                hostConfiguration.SetDescription("This is Tellurium Dashboard");
                hostConfiguration.SetDisplayName("Tellurium Dashboard");
                hostConfiguration.SetServiceName("TelluriumDashboard");
                hostConfiguration.StartAutomatically();
            });
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Topshelf;

namespace Tellurium.VisualAssertion.Dashboard
{
    public class Program
    {
        public static void Main(string[] args)
        {
#if DEBUG
            using (var server = new WebServer())
            {
                Console.SetOut(new DebugWriter());
                server.Run(consoleMode:true);
                Console.ReadKey();
            }
#else
            InstallDashboardService();
#endif
        }

        private static void InstallDashboardService()
        {
            HostFactory.Run(hostConfiguration =>
            {
                hostConfiguration.Service<WebServer>(wsc =>
                {
                    wsc.ConstructUsing(() => new WebServer());
                    wsc.WhenStarted(server =>
                    {
                       server.Run();
                    });
                    wsc.WhenStopped(ws => ws.Dispose());
                });
                hostConfiguration.RunAsLocalSystem();
                hostConfiguration.SetDescription("This is Tellurium Dashboard");
                hostConfiguration.SetDisplayName("Tellurium Dashboard");
                hostConfiguration.SetServiceName("TelluriumDashboard");
                hostConfiguration.StartAutomatically();
            });
        }
    }

    public class DebugWriter : StringWriter
    {
        public override void WriteLine(string value)
        {
            Debug.WriteLine(value);
            base.WriteLine(value);
        }
    }
}

Add Debug writer for diagnostic purpose

Add Debug writer for diagnostic purpose


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Baskerville.Models.DataModels
{
    public class ProductCategory
    {
        public ProductCategory()
        {
            this.Products = new HashSet<Product>();
            this.Subcategories = new HashSet<ProductCategory>();
        }

        public int Id { get; set; }

        public string NameBg { get; set; }

        public string NameEn { get; set; }

        public bool IsRemoved { get; set; }

        public bool IsPrimary { get; set; }

        public ICollection<Product> Products { get; set; }

        public ICollection<ProductCategory> Subcategories { get; set; }

        public int? PrimaryCategoryId { get; set; }

        public ProductCategory PrimaryCategory { get; set; }
    }
}

namespace Baskerville.Models.DataModels
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public class ProductCategory
    {
        public ProductCategory()
        {
            this.Products = new HashSet<Product>();
            this.Subcategories = new HashSet<ProductCategory>();
        }

        public int Id { get; set; }

        [Required]
        public string NameBg { get; set; }

        [Required]
        public string NameEn { get; set; }

        public bool IsRemoved { get; set; }

        public bool IsPrimary { get; set; }

        public ICollection<Product> Products { get; set; }

        public ICollection<ProductCategory> Subcategories { get; set; }

        public int? PrimaryCategoryId { get; set; }

        public ProductCategory PrimaryCategory { get; set; }
    }
}

Add Db validation for ProductCategories model


#if FAT

namespace Theraot.Threading
{
    public static partial class ThreadingHelper
    {
        private static readonly RuntimeUniqueIdProdiver _threadIdProvider = new RuntimeUniqueIdProdiver();
        // Leaked until AppDomain unload
        private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(_threadIdProvider.GetNextId);

        public static bool HasThreadUniqueId
        {
            get
            {
                return _threadRuntimeUniqueId.IsValueCreated;
            }
        }

        public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId
        {
            get
            {
                return _threadRuntimeUniqueId.Value;
            }
        }
    }
}

#endif

#if FAT

namespace Theraot.Threading
{
    public static partial class ThreadingHelper
    {
        // Leaked until AppDomain unload
        private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(RuntimeUniqueIdProdiver.GetNextId);

        public static bool HasThreadUniqueId
        {
            get
            {
                return _threadRuntimeUniqueId.IsValueCreated;
            }
        }

        public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId
        {
            get
            {
                return _threadRuntimeUniqueId.Value;
            }
        }
    }
}

#endif

Fix - RuntimeUniqueIdProdiver is static

Fix - RuntimeUniqueIdProdiver is static


using IdentityServer3.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer3.Core.Models;
using IdentityServer3.Contrib.RedisStores.Models;
using StackExchange.Redis;
using IdentityServer3.Contrib.RedisStores.Converters;

namespace IdentityServer3.Contrib.RedisStores.Stores
{
    /// <summary>
    ///
    /// </summary>
    public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel>
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="redis"></param>
        /// <param name="options"></param>
        public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter())
        {

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="redis"></param>
        public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter())
        {

        }
        internal override string CollectionName => "refreshTokens";

        internal override int GetTokenLifetime(RefreshToken token)
        {
            return token.LifeTime;
        }
    }
}

using IdentityServer3.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer3.Core.Models;
using IdentityServer3.Contrib.RedisStores.Models;
using StackExchange.Redis;
using IdentityServer3.Contrib.RedisStores.Converters;

namespace IdentityServer3.Contrib.RedisStores
{
    /// <summary>
    ///
    /// </summary>
    public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel>, IRefreshTokenStore
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="redis"></param>
        /// <param name="options"></param>
        public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter())
        {

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="redis"></param>
        public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter())
        {

        }
        internal override string CollectionName => "refreshTokens";

        internal override int GetTokenLifetime(RefreshToken token)
        {
            return token.LifeTime;
        }
    }
}

Fix namespace and add inheritance

Fix namespace and add inheritance


using AutomaticTypeMapper;
using EOLib.Logger;
using EOLib.Net;
using EOLib.Net.Communication;
using EOLib.Net.Handlers;
using EOLib.Net.PacketProcessing;

namespace EOLib.PacketHandlers
{
    /// <summary>
    /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol
    /// </summary>
    [AutoMappedType]
    public class ConnectionPlayerHandler : DefaultAsyncPacketHandler
    {
        private readonly IPacketProcessActions _packetProcessActions;
        private readonly IPacketSendService _packetSendService;
        private readonly ILoggerProvider _loggerProvider;

        public override PacketFamily Family => PacketFamily.Connection;

        public override PacketAction Action => PacketAction.Player;

        public override bool CanHandle => true;

        public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions,
                                       IPacketSendService packetSendService,
                                       ILoggerProvider loggerProvider)
        {
            _packetProcessActions = packetProcessActions;
            _packetSendService = packetSendService;
            _loggerProvider = loggerProvider;
        }

        public override bool HandlePacket(IPacket packet)
        {
            var seq1 = packet.ReadShort();
            var seq2 = packet.ReadChar();

            _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2);

            var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping).Build();
            try
            {
                _packetSendService.SendPacket(response);
            }
            catch (NoDataSentException)
            {
                return false;
            }

            return true;
        }
    }
}

using AutomaticTypeMapper;
using EOLib.Logger;
using EOLib.Net;
using EOLib.Net.Communication;
using EOLib.Net.Handlers;
using EOLib.Net.PacketProcessing;

namespace EOLib.PacketHandlers
{
    /// <summary>
    /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol
    /// </summary>
    [AutoMappedType]
    public class ConnectionPlayerHandler : DefaultAsyncPacketHandler
    {
        private readonly IPacketProcessActions _packetProcessActions;
        private readonly IPacketSendService _packetSendService;
        private readonly ILoggerProvider _loggerProvider;

        public override PacketFamily Family => PacketFamily.Connection;

        public override PacketAction Action => PacketAction.Player;

        public override bool CanHandle => true;

        public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions,
                                       IPacketSendService packetSendService,
                                       ILoggerProvider loggerProvider)
        {
            _packetProcessActions = packetProcessActions;
            _packetSendService = packetSendService;
            _loggerProvider = loggerProvider;
        }

        public override bool HandlePacket(IPacket packet)
        {
            var seq1 = packet.ReadShort();
            var seq2 = packet.ReadChar();

            _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2);

            var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping)
                .AddString("k")
                .Build();

            try
            {
                _packetSendService.SendPacket(response);
            }
            catch (NoDataSentException)
            {
                return false;
            }

            return true;
        }
    }
}

Fix handling of CONNECTION_PLAYER when sending response to GameServer


using System;

namespace gdRead.Data.Models
{
    public class Post
    {
        public int Id { get; set; }
        public int FeedId { get; set; }
        public string Name { get; set; }
        public string  Url { get; set; }
        public string Summary { get; set; }
        public string Content { get; set; }
        public DateTime PublishDate { get; set; }
        public bool Read { get; set; }
        public DateTime DateFetched { get;set; }

        public Post()
        {
            DateFetched = DateTime.Now;
        }
    }
}

using System;
using DapperExtensions.Mapper;

namespace gdRead.Data.Models
{
    public class Post
    {
        public int Id { get; set; }
        public int FeedId { get; set; }
        public string Name { get; set; }
        public string  Url { get; set; }
        public string Summary { get; set; }
        public string Content { get; set; }
        public DateTime PublishDate { get; set; }
        public bool Read { get; set; }
        public DateTime DateFetched { get;set; }

        public Post()
        {
            DateFetched = DateTime.Now;
        }
    }

    public class PostMapper : ClassMapper<Post>
    {
        public PostMapper()
        {
            Table("Post");
            Map(m => m.Read).Ignore();
            AutoMap();
        }
    }
}

Fix issue where Dapper was trying to insert Read into the post table where that column doesnt exist


using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.ManagedDialogs
{
	internal class ManagedFileChooserFilterViewModel : ViewModelBase
	{
		private readonly string[] Extensions;
		public string Name { get; }

		public ManagedFileChooserFilterViewModel(FileDialogFilter filter)
		{
			Name = filter.Name;

			if (filter.Extensions.Contains("*"))
			{
				return;
			}

			Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()).ToArray();
		}

		public ManagedFileChooserFilterViewModel()
		{
			Name = "All files";
		}

		public bool Match(string filename)
		{
			if (Extensions is null)
			{
				return true;
			}

			foreach (var ext in Extensions)
			{
				if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase))
				{
					return true;
				}
			}

			return false;
		}

		public override string ToString() => Name;
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.ManagedDialogs
{
	internal class ManagedFileChooserFilterViewModel : ViewModelBase
	{
		private IEnumerable<string> Extensions { get; }
		public string Name { get; }

		public ManagedFileChooserFilterViewModel(FileDialogFilter filter)
		{
			Name = filter.Name;

			if (filter.Extensions.Contains("*"))
			{
				return;
			}

			Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant());
		}

		public ManagedFileChooserFilterViewModel()
		{
			Name = "All files";
		}

		public bool Match(string filename)
		{
			if (Extensions is null)
			{
				return true;
			}

			foreach (var ext in Extensions)
			{
				if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase))
				{
					return true;
				}
			}

			return false;
		}

		public override string ToString() => Name;
	}
}

Replace string[] field by IEnumerable<string> property


// Copyright (c) 2015 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("BuildDependencyTestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2014-2016 Eberhard Beilharz")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

// Copyright (c) 2015 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("BuildDependencyTestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2014-2017 Eberhard Beilharz")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

Use GitVersion for test app

Use GitVersion for test app


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DotVVM.Framework.Compilation.Binding
{
    public class DefaultExtensionsProvider : IExtensionsProvider
    {
        private readonly List<Type> typesLookup;

        public DefaultExtensionsProvider()
        {
            typesLookup = new List<Type>();
            AddTypeForExtensionsLookup(typeof(Enumerable));
        }

        protected void AddTypeForExtensionsLookup(Type type)
        {
            typesLookup.Add(typeof(Enumerable));
        }

        public virtual IEnumerable<MethodInfo> GetExtensionMethods()
        {
            foreach (var registeredType in typesLookup)
                foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static))
                    yield return method;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DotVVM.Framework.Compilation.Binding
{
    public class DefaultExtensionsProvider : IExtensionsProvider
    {
        private readonly List<Type> typesLookup;

        public DefaultExtensionsProvider()
        {
            typesLookup = new List<Type>();
            AddTypeForExtensionsLookup(typeof(Enumerable));
        }

        protected void AddTypeForExtensionsLookup(Type type)
        {
            typesLookup.Add(type);
        }

        public virtual IEnumerable<MethodInfo> GetExtensionMethods()
        {
            foreach (var registeredType in typesLookup)
                foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static))
                    yield return method;
        }
    }
}

Fix issue when adding type to ExtensionsProvider


// project created on 11.11.2001 at 15:19
using System;
using System.IO;

using ICSharpCode.SharpZipLib.GZip;

class MainClass
{
	public static void Main(string[] args)
	{
		if (args[0] == "-d") { // decompress
			Stream s = new GZipInputStream(File.OpenRead(args[1]));
			FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
			int size = 2048;
			byte[] writeData = new byte[2048];
			while (true) {
				size = s.Read(writeData, 0, size);
				if (size > 0) {
					fs.Write(writeData, 0, size);
				} else {
					break;
				}
			}
			s.Close();
		} else { // compress
			Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"));
			FileStream fs = File.OpenRead(args[0]);
			byte[] writeData = new byte[fs.Length];
			fs.Read(writeData, 0, (int)fs.Length);
			s.Write(writeData, 0, writeData.Length);
			s.Close();
		}
	}
}

// project created on 11.11.2001 at 15:19
using System;
using System.IO;

using ICSharpCode.SharpZipLib.GZip;

class MainClass
{
	public static void Main(string[] args)
	{
		if ( args.Length > 0 ) {
			if ( args[0] == "-d" ) { // decompress
				Stream s = new GZipInputStream(File.OpenRead(args[1]));
				FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
				int size = 2048;
				byte[] writeData = new byte[2048];
				while (true) {
					size = s.Read(writeData, 0, size);
					if (size > 0) {
						fs.Write(writeData, 0, size);
					} else {
						break;
					}
				}
				s.Close();
			} else { // compress
				Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"));
				FileStream fs = File.OpenRead(args[0]);
				byte[] writeData = new byte[fs.Length];
				fs.Read(writeData, 0, (int)fs.Length);
				s.Write(writeData, 0, writeData.Length);
				s.Close();
			}
		}
	}
}

Stop exception when no argument sare suppplied to minigzip


using System;
using System.IO;
using System.Reflection;

// ReSharper disable once CheckNamespace
internal static class Program
{
    private static int Main(string[] args)
    {
        // Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries.
        // We emulate it using our own assembly redirector.
        AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
        {
            var assemblyName = e.LoadedAssembly.GetName();
            Console.WriteLine("Assembly load: {0}", assemblyName);
        };

        var mainAsm = Assembly.Load("citizenmp_server_updater");

        mainAsm.GetType("Costura.AssemblyLoader")
            .GetMethod("Attach")
            .Invoke(null, null);

        return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
            .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
            .Invoke(null, new object[] {args});
    }
}

using System;
using System.IO;
using System.Reflection;

// ReSharper disable once CheckNamespace
internal static class Program
{
    private static int Main(string[] args)
    {
        var mainAsm = Assembly.Load("citizenmp_server_updater");

        mainAsm.GetType("Costura.AssemblyLoader")
            .GetMethod("Attach")
            .Invoke(null, null);

        return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
            .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
            .Invoke(null, new object[] {args});
    }
}

Remove assembly load debug lines.

Remove assembly load debug lines.


using Microsoft.VisualStudio.TestTools.UnitTesting;
using SaurusConsole.OthelloAI;
namespace SaurusConsoleTests
{
    [TestClass]
    public class MoveTests
    {
        [TestMethod]
        public void NotationConstuctorTest()
        {
            Move e4move = new Move("E4");
            Assert.AreEqual("E4", e4move.ToString());

            Move a1move = new Move("A1");
            Assert.AreEqual("A1", a1move.ToString());

            Move a8move = new Move("A8");
            Assert.AreEqual("A8", a8move.ToString());

            Move h1move = new Move("H1");
            Assert.AreEqual("H1", h1move.ToString());

            Move h8move = new Move("H8");
            Assert.AreEqual("H8", h8move.ToString());
        }

        [TestMethod]
        public void ToStringTest()
        {
            ulong h1Mask = 1;
            Move h1Move = new Move(h1Mask);
            Assert.AreEqual("H1", h1Move.ToString());

            ulong e4Mask = 0x8000000;
            Move e4Move = new Move(e4Mask);
            Assert.AreEqual("E4", e4Move.ToString());
        }

        [TestMethod]
        public void GetBitMaskTest()
        {
            ulong mask = 0b1000000000000;
            Move move = new Move(mask);
            Assert.AreEqual(mask, move.GetBitMask());
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SaurusConsole.OthelloAI;
namespace SaurusConsoleTests
{
    [TestClass]
    public class MoveTests
    {
        [TestMethod]
        public void NotationConstuctorTest()
        {
            Move e4move = new Move("E4");
            Assert.AreEqual("E4", e4move.ToString());

            Move a1move = new Move("A1");
            Assert.AreEqual("A1", a1move.ToString());

            Move a8move = new Move("A8");
            Assert.AreEqual("A8", a8move.ToString());

            Move h1move = new Move("H1");
            Assert.AreEqual("H1", h1move.ToString());

            Move h8move = new Move("H8");
            Assert.AreEqual("H8", h8move.ToString());
            Assert.Fail();
        }

        [TestMethod]
        public void ToStringTest()
        {
            ulong h1Mask = 1;
            Move h1Move = new Move(h1Mask);
            Assert.AreEqual("H1", h1Move.ToString());

            ulong e4Mask = 0x8000000;
            Move e4Move = new Move(e4Mask);
            Assert.AreEqual("E4", e4Move.ToString());
        }

        [TestMethod]
        public void GetBitMaskTest()
        {
            ulong mask = 0b1000000000000;
            Move move = new Move(mask);
            Assert.AreEqual(mask, move.GetBitMask());
        }
    }
}

Test if a failed test will fail the build


using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;

namespace SupportManager.Web
{
    public class Program
    {
        private static string[] args;

        public static void Main()
        {
            HostFactory.Run(cfg =>
            {
                cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));

                cfg.SetServiceName("SupportManager.Web");
                cfg.SetDisplayName("SupportManager.Web");
                cfg.SetDescription("SupportManager Web Interface");

                cfg.Service<IWebHost>(svc =>
                {
                    svc.ConstructUsing(CreateWebHost);
                    svc.WhenStarted(webHost =>
                    {
                        webHost.Start();
                        RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely);
                    });
                    svc.WhenStopped(webHost => webHost.Dispose());
                });

                cfg.RunAsLocalSystem();
                cfg.StartAutomatically();
            });
        }

        private static IWebHost CreateWebHost()
        {
            var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            if (!Debugger.IsAttached)
            {
                builder.UseHttpSys(options =>
                {
                    options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                    options.Authentication.AllowAnonymous = true;
                });

                builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
            }

            return builder.Build();
        }
    }
}

using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;

namespace SupportManager.Web
{
    public class Program
    {
        private static string[] args;

        public static void Main()
        {
            HostFactory.Run(cfg =>
            {
                cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));

                cfg.SetServiceName("SupportManager.Web");
                cfg.SetDisplayName("SupportManager.Web");
                cfg.SetDescription("SupportManager Web Interface");

                cfg.Service<IWebHost>(svc =>
                {
                    svc.ConstructUsing(CreateWebHost);
                    svc.WhenStarted(webHost =>
                    {
                        webHost.Start();
                        RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.MinuteInterval(10));
                    });
                    svc.WhenStopped(webHost => webHost.Dispose());
                });

                cfg.RunAsLocalSystem();
                cfg.StartAutomatically();
            });
        }

        private static IWebHost CreateWebHost()
        {
            var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            if (!Debugger.IsAttached)
            {
                builder.UseHttpSys(options =>
                {
                    options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                    options.Authentication.AllowAnonymous = true;
                });

                builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
            }

            return builder.Build();
        }
    }
}

Set interval to 10 minutes

ReadAllTeamStatus: Set interval to 10 minutes


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Nether.Web.Features.Identity
{
    [Route("identity-test")]
    [Authorize]
    public class IdentityTestController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }
    }
}

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Nether.Web.Features.Identity
{
    [Route("identity-test")]
    [Authorize]
    public class IdentityTestController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            // Convert claim type, value pairs into a dictionary for easier consumption as JSON
            // Need to group as there can be multiple claims of the same type (e.g. 'scope')
            var result = User.Claims
                .GroupBy(c => c.Type)
                .ToDictionary(
                    keySelector: g => g.Key,
                    elementSelector: g => g.Count() == 1 ? (object)g.First().Value : g.Select(t => t.Value).ToArray()
                );
            return new JsonResult(result);
        }
    }
}

Make identity-test API easier to consume


/*
 * The official C# API client for alpaca brokerage
 * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2
*/

using System;
using Newtonsoft.Json;

namespace QuantConnect.Brokerages.Alpaca.Markets
{
    internal sealed class JsonError
    {
        [JsonProperty(PropertyName = "code", Required = Required.Always)]
        public Int32 Code { get; set; }

        [JsonProperty(PropertyName = "message", Required = Required.Always)]
        public String Message { get; set; }

    }
}

/*
 * The official C# API client for alpaca brokerage
 * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2
*/

using System;
using Newtonsoft.Json;

namespace QuantConnect.Brokerages.Alpaca.Markets
{
    internal sealed class JsonError
    {
        [JsonProperty(PropertyName = "code", Required = Required.Default)]
        public Int32 Code { get; set; }

        [JsonProperty(PropertyName = "message", Required = Required.Always)]
        public String Message { get; set; }

    }
}

Fix Alpaca error message deserialization

Some JSON error messages could not be deserialized because they do not contain the "code" property.


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable enable

using System;
using osu.Game.Users;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
    {
        public readonly long UserID;

        public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;

        public User? User { get; set; }

        public MultiplayerRoomUser(in int userId)
        {
            UserID = userId;
        }

        public bool Equals(MultiplayerRoomUser other)
        {
            if (ReferenceEquals(this, other)) return true;

            return UserID == other.UserID;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;

            return Equals((MultiplayerRoomUser)obj);
        }

        public override int GetHashCode() => UserID.GetHashCode();
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable enable

using System;
using osu.Game.Users;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
    {
        public readonly int UserID;

        public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;

        public User? User { get; set; }

        public MultiplayerRoomUser(in int userId)
        {
            UserID = userId;
        }

        public bool Equals(MultiplayerRoomUser other)
        {
            if (ReferenceEquals(this, other)) return true;

            return UserID == other.UserID;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;

            return Equals((MultiplayerRoomUser)obj);
        }

        public override int GetHashCode() => UserID.GetHashCode();
    }
}

Change user id type to int

Change user id type to int


using System;
using System.Collections.Generic;

namespace IvionSoft
{
    public class History<T>
    {
        public int Length { get; private set; }

        HashSet<T> hashes;
        Queue<T> queue;
        object _locker = new object();

        public History(int length) : this(length, null)
        {}

        public History(int length, IEqualityComparer<T> comparer)
        {
            if (length < 1)
                throw new ArgumentException("Must be 1 or larger", "length");

            Length = length;
            queue = new Queue<T>(length + 1);

            if (comparer != null)
                hashes = new HashSet<T>(comparer);
            else
                hashes = new HashSet<T>();
        }

        public bool Contains(T item)
        {
            return hashes.Contains(item);
        }

        public bool Add(T item)
        {
            bool added;
            lock (_locker)
            {
                added = hashes.Add(item);

                if (added)
                {
                    queue.Enqueue(item);
                    if (queue.Count > Length)
                    {
                        T toRemove = queue.Dequeue();
                        hashes.Remove(toRemove);
                    }
                }
            }

            return added;
        }
    }
}

using System;
using System.Collections.Generic;

namespace IvionSoft
{
    public class History<T>
    {
        public int Length { get; private set; }

        HashSet<T> hashes;
        Queue<T> queue;

        public History()
        {
            Length = 0;
        }

        public History(int length) : this(length, null)
        {}

        public History(int length, IEqualityComparer<T> comparer)
        {
            if (length < 1)
                throw new ArgumentException("Cannot be less than or equal to 0.", "length");

            Length = length;
            queue = new Queue<T>(length + 1);

            if (comparer != null)
                hashes = new HashSet<T>(comparer);
            else
                hashes = new HashSet<T>();
        }

        public bool Contains(T item)
        {
            if (Length > 0)
                return hashes.Contains(item);
            else
                return false;
        }

        public bool Add(T item)
        {
            if (Length == 0)
                return false;

            bool added;
            added = hashes.Add(item);

            if (added)
            {
                queue.Enqueue(item);
                if (queue.Count > Length)
                {
                    T toRemove = queue.Dequeue();
                    hashes.Remove(toRemove);
                }
            }

            return added;
        }
    }
}

Remove locking code and make it possible to have a dummy history, by calling the parameterless constructor.


using System;
using dnlib.DotNet;

namespace Confuser.Core.Project.Patterns {
	/// <summary>
	///     A function that compare the module of definition.
	/// </summary>
	public class ModuleFunction : PatternFunction {
		internal const string FnName = "module";

		/// <inheritdoc />
		public override string Name {
			get { return FnName; }
		}

		/// <inheritdoc />
		public override int ArgumentCount {
			get { return 1; }
		}

		/// <inheritdoc />
		public override object Evaluate(IDnlibDef definition) {
			if (!(definition is IOwnerModule))
				return false;
			object name = Arguments[0].Evaluate(definition);
			return ((IOwnerModule)definition).Module.Name == name.ToString();
		}
	}
}

using System;
using dnlib.DotNet;

namespace Confuser.Core.Project.Patterns {
	/// <summary>
	///     A function that compare the module of definition.
	/// </summary>
	public class ModuleFunction : PatternFunction {
		internal const string FnName = "module";

		/// <inheritdoc />
		public override string Name {
			get { return FnName; }
		}

		/// <inheritdoc />
		public override int ArgumentCount {
			get { return 1; }
		}

		/// <inheritdoc />
		public override object Evaluate(IDnlibDef definition) {
			if (!(definition is IOwnerModule) && !(definition is IModule))
				return false;
			object name = Arguments[0].Evaluate(definition);
			if (definition is IModule)
				return ((IModule)definition).Name == name.ToString();
			return ((IOwnerModule)definition).Module.Name == name.ToString();
		}
	}
}

Support module def in module function

Support module def in module function


using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Stampsy.ImageSource
{
    public class FileDestination : IDestination<FileRequest>
    {
        public string Folder { get; private set; }

        public FileDestination (string folder)
        {
            Folder = folder;
        }

        public FileRequest CreateRequest (IDescription description)
        {
            var url = description.Url;
            var filename = ComputeHash (url) + description.Extension;

            return new FileRequest (description) {
                Filename = Path.Combine (Folder, filename)
            };
        }

        static string ComputeHash (Uri url)
        {
            string hash;
            using (var sha1 = new SHA1CryptoServiceProvider ()) {
                var bytes = Encoding.ASCII.GetBytes (url.ToString ());
                hash = BitConverter.ToString (sha1.ComputeHash (bytes));
            }

            return hash.Replace ("-", string.Empty).ToLower ();
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Stampsy.ImageSource
{
    public class FileDestination : IDestination<FileRequest>
    {
        public static FileDestination InLibrary (params string [] folders)
        {
            var folder = Path.Combine (new [] { "..", "Library" }.Concat (folders).ToArray ());
            Directory.CreateDirectory (folder);
            return new FileDestination (folder);
        }

        public static FileDestination InLibraryCaches (params string [] folders)
        {
            return InLibrary (new [] { "Caches" }.Concat (folders).ToArray ());
        }

        public string Folder { get; private set; }

        public FileDestination (string folder)
        {
            Folder = folder;
        }

        public FileRequest CreateRequest (IDescription description)
        {
            var url = description.Url;
            var filename = ComputeHash (url) + description.Extension;

            return new FileRequest (description) {
                Filename = Path.Combine (Folder, filename)
            };
        }

        static string ComputeHash (Uri url)
        {
            string hash;
            using (var sha1 = new SHA1CryptoServiceProvider ()) {
                var bytes = Encoding.ASCII.GetBytes (url.ToString ());
                hash = BitConverter.ToString (sha1.ComputeHash (bytes));
            }

            return hash.Replace ("-", string.Empty).ToLower ();
        }
    }
}

Add helpers for saving in Library and Library/Caches


using System;
using System.Collections.Generic;

namespace Simple.Domain.Model
{
	public class Organization
	{
		public Guid Id { get; set; }
		public string Name { get; set; }
		public string CatchPhrase { get; set; }
		public string BSPhrase { get; set; }

		// Ref
		public DomainUser Owner { get; set; }

		// List Ref
		public List<Address> Addresses { get; set; }
		public List<DomainUser> Employees { get; set; }
	}
}

using System;
using System.Collections.Generic;
using Simple.Domain.Entities;

namespace Simple.Domain.Model
{
	public class Organization
	{
		public Guid Id { get; set; }
		public string Name { get; set; }
		public string CatchPhrase { get; set; }
		public string BSPhrase { get; set; }

		// Ref
		public User Owner { get; set; }

		// List Ref
		public List<Address> Addresses { get; set; }
		public List<User> Employees { get; set; }
	}
}

Update to use new User

Update to use new User


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicCash
{
    /// <summary>
    /// The customer
    /// </summary>
    public class Alice : BaseActor
    {

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicCash
{
    /// <summary>
    /// The customer
    /// </summary>
    public class Alice : BaseActor
    {
        public List<MoneyOrder> MoneyOrders { get; private set; }
        public string PersonalData { get; private set; }
        public byte[] PersonalDataBytes { get; private set; }

        public Alice(string _name, Guid _actorGuid, string _personalData)
        {
            Name = _name;
            ActorGuid = _actorGuid;
            Money = 1000;
            PersonalData = _personalData;
            PersonalDataBytes = GetBytes(_personalData);
        }

        /// <summary>
        /// Called every time the customer wants to pay for something
        /// </summary>
        public void CreateMoneyOrders()
        {
            MoneyOrders = new List<MoneyOrder>();

        }

        #region private methods

        /// <summary>
        /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        /// <summary>
        /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        #endregion
    }
}

Add some helpers and stuff

Add some helpers and stuff


// Copyright 2015 Palm Stone Games, Inc. All Rights Reserved.

using System.IO;

namespace UnrealBuildTool.Rules
{
	public class ue4czmq : ModuleRules
	{
        public ue4czmq(TargetInfo Target)
		{
            // Include paths
            //PublicIncludePaths.AddRange(new string[] {});
            //PrivateIncludePaths.AddRange(new string[] {});

            // Dependencies
            PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", });

            //PrivateDependencyModuleNames.AddRange(new string[] {});

            // Dynamically loaded modules
            //DynamicallyLoadedModuleNames.AddRange(new string[] {});

            // Definitions
            Definitions.Add("WITH_UE4CZMQ=1");

            LoadLib(Target);
		}

        public void LoadLib(TargetInfo Target)
        {
            string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name));

            // CZMQ
            string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq"));
            PrivateAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib"));
            PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes"));

            // LIBZMQ
            string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq"));
            PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes"));
        }
	}
}

// Copyright 2015 Palm Stone Games, Inc. All Rights Reserved.

using System.IO;

namespace UnrealBuildTool.Rules
{
	public class ue4czmq : ModuleRules
	{
        public ue4czmq(TargetInfo Target)
		{
            // Include paths
            //PublicIncludePaths.AddRange(new string[] {});
            //PrivateIncludePaths.AddRange(new string[] {});

            // Dependencies
            PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", });

            //PrivateDependencyModuleNames.AddRange(new string[] {});

            // Dynamically loaded modules
            //DynamicallyLoadedModuleNames.AddRange(new string[] {});

            // Definitions
            Definitions.Add("WITH_UE4CZMQ=1");

            LoadLib(Target);
		}

        public void LoadLib(TargetInfo Target)
        {
            string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name));

            // CZMQ
            string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq"));
            PublicAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib"));
            PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes"));

            // LIBZMQ
            string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq"));
            PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes"));
        }
	}
}

Revert "Use a PrivateAdditionalLibrary for czmq.lib instead of a public one"

This reverts commit f1e6a83fdd73c5589772ab9d3fef316853a5cd19.


@model APFT

@using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Id)
    @Html.ValidationSummary()

        @Html.DisplayNameFor(model => model.Soldier)
        @Html.EditorFor(model => model.SoldierId)

        @Html.DisplayNameFor(model => model.Date)
        @Html.EditorFor(model => model.Date)

        @Html.DisplayNameFor(model => model.PushUps)
        @Html.EditorFor(model => model.PushUps)

        @Html.DisplayNameFor(model => model.SitUps)
        @Html.EditorFor(model => model.SitUps)

        @Html.DisplayNameFor(model => model.Run)
        @Html.EditorFor(model => model.Run)

    <button type="submit">Save</button>
}

@model APFT

@using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Id)
    @Html.ValidationSummary()

        @Html.DisplayNameFor(model => model.Soldier)
        @Html.DropDownListFor(model => model.SoldierId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")

        @Html.DisplayNameFor(model => model.Date)
        @Html.EditorFor(model => model.Date)

        @Html.DisplayNameFor(model => model.PushUps)
        @Html.EditorFor(model => model.PushUps)

        @Html.DisplayNameFor(model => model.SitUps)
        @Html.EditorFor(model => model.SitUps)

        @Html.DisplayNameFor(model => model.Run)
        @Html.EditorFor(model => model.Run)

    <button type="submit">Save</button>
}

Make soldier a dropdown list

Make soldier a dropdown list


#region copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleTests.cs" company="Stephen Reindl">
// Copyright (c) Stephen Reindl. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
// <summary>
//     Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion

namespace Oberon0.Compiler.Tests
{
    using NUnit.Framework;

    using Oberon0.Compiler.Definitions;
    using Oberon0.TestSupport;

    [TestFixture]
    public class SimpleTests
    {
        [Test]
        public void EmptyApplication()
        {
            Module m = Oberon0Compiler.CompileString("MODULE Test; END Test.");
            Assert.AreEqual("Test", m.Name);
            Assert.AreEqual(2, m.Block.Declarations.Count);
        }

        [Test]
        public void EmptyApplication2()
        {
            Module m = TestHelper.CompileString(
                @"MODULE Test; BEGIN END Test.");
            Assert.AreEqual(0, m.Block.Statements.Count);
        }

        [Test]
        public void ModuleMissingDot()
        {
            TestHelper.CompileString(
                @"MODULE Test; END Test",
                "missing '.' at '<EOF>'");
        }

        [Test]
        public void ModuleMissingId()
        {
            TestHelper.CompileString(
                @"MODULE ; BEGIN END Test.",
                "missing ID at ';'",
                "The name of the module does not match the end node");
        }
    }
}

#region copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleTests.cs" company="Stephen Reindl">
// Copyright (c) Stephen Reindl. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
// <summary>
//     Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion

namespace Oberon0.Compiler.Tests
{
    using NUnit.Framework;

    using Oberon0.Compiler.Definitions;
    using Oberon0.TestSupport;

    [TestFixture]
    public class SimpleTests
    {
        [Test]
        public void EmptyApplication()
        {
            Module m = Oberon0Compiler.CompileString("MODULE Test; END Test.");
            Assert.AreEqual("Test", m.Name);
            Assert.AreEqual(3, m.Block.Declarations.Count);
        }

        [Test]
        public void EmptyApplication2()
        {
            Module m = TestHelper.CompileString(
                @"MODULE Test; BEGIN END Test.");
            Assert.AreEqual(0, m.Block.Statements.Count);
        }

        [Test]
        public void ModuleMissingDot()
        {
            TestHelper.CompileString(
                @"MODULE Test; END Test",
                "missing '.' at '<EOF>'");
        }

        [Test]
        public void ModuleMissingId()
        {
            TestHelper.CompileString(
                @"MODULE ; BEGIN END Test.",
                "missing ID at ';'",
                "The name of the module does not match the end node");
        }
    }
}

Update unit test error for new const

Update unit test error for new const


namespace MvvmFx.CaliburnMicro
{
    using System;

    /// <summary>
    /// Used to manage logging.
    /// </summary>
    public static class LogManager
    {
        private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger();

        /// <summary>
        /// Creates an <see cref="Logging.ILog"/> for the provided type.
        /// </summary>
        public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance;
    }
}

namespace MvvmFx.CaliburnMicro
{
    using System;

    /// <summary>
    /// Used to manage logging.
    /// </summary>
    public static class LogManager
    {
        private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger();

#pragma warning disable CS3003 // Type is not CLS-compliant
        /// <summary>
        /// Creates an <see cref="Logging.ILog"/> for the provided type.
        /// </summary>
        public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance;
#pragma warning restore CS3003 // Type is not CLS-compliant
    }
}

Disable warning "Type is not CLS-compliant"


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsQuery.Implementation
{
    public class TrueStringComparer : IComparer<string>, IEqualityComparer<string>
    {
        public int Compare(string x, string y)
        {
            int pos = 0;
            int len = Math.Min(x.Length, y.Length);
            while (pos < len)
            {
                var xi = (int)x[pos];
                var yi = (int)y[pos];
                if (xi < yi)
                {
                    return -1;
                }
                else if (yi < xi)
                {
                    return 1;
                }
                pos++;
            }
            if (x.Length < y.Length)
            {
                return -1;
            }
            else if (y.Length < x.Length)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public bool Equals(string x, string y)
        {
            return Compare(x, y) == 0;
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsQuery.Implementation
{
    public class TrueStringComparer : IComparer<string>, IEqualityComparer<string>
    {
        public int Compare(string x, string y)
        {
            int pos = 0;
            int len = Math.Min(x.Length, y.Length);
            while (pos < len)
            {
                var xi = (int)x[pos];
                var yi = (int)y[pos];
                if (xi < yi)
                {
                    return -1;
                }
                else if (yi < xi)
                {
                    return 1;
                }
                pos++;
            }
            if (x.Length < y.Length)
            {
                return -1;
            }
            else if (y.Length < x.Length)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public bool Equals(string x, string y)
        {
            return x.Length == y.Length && Compare(x, y) == 0;
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
}

Use custom string comparer for RangeSortedDictionary


using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Sakuno.Collections
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class EnumerableExtensions
    {
        public static bool AnyNull<T>(this IEnumerable<T> source) where T : class
        {
            foreach (var item in source)
                if (item == null)
                    return true;

            return false;
        }

        public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source)
        {
            foreach (var item in source)
            {
                if (item is TExclusion)
                    continue;

                yield return item;
            }
        }

        public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance);
        public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer);

        public static IEnumerable<(T, bool)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items)
        {
            using (var enumerator = items.GetEnumerator())
            {
                var last = default(T);

                if (!enumerator.MoveNext())
                    yield break;

                var shouldYield = false;

                do
                {
                    if (shouldYield)
                        yield return (last, false);

                    shouldYield = true;
                    last = enumerator.Current;
                } while (enumerator.MoveNext());

                yield return (last, true);
            }
        }
    }
}

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Sakuno.Collections
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class EnumerableExtensions
    {
        public static bool AnyNull<T>(this IEnumerable<T> source) where T : class
        {
            foreach (var item in source)
                if (item == null)
                    return true;

            return false;
        }

        public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source)
        {
            foreach (var item in source)
            {
                if (item is TExclusion)
                    continue;

                yield return item;
            }
        }

        public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance);
        public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer);

        public static IEnumerable<(T Item, bool IsLast)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items)
        {
            using (var enumerator = items.GetEnumerator())
            {
                var last = default(T);

                if (!enumerator.MoveNext())
                    yield break;

                var shouldYield = false;

                do
                {
                    if (shouldYield)
                        yield return (last, false);

                    shouldYield = true;
                    last = enumerator.Current;
                } while (enumerator.MoveNext());

                yield return (last, true);
            }
        }
    }
}

Add field names in returned tuple of EnumerateItemAndIfIsLast()


namespace OpenRealEstate.Services
{
    public interface ITransmorgrifier
    {
        ///
        /// Converts some given data into a listing instance.
        ///
        /// <param name="data">some data source, like Xml data or json data.</param>
        /// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param>
        /// <param name="areBadCharactersRemoved">Help clean up the data.</param>
        /// <returns>List of listings and any unhandled data.</returns>
        /// <remarks>Why does isClearAllIsModified default to false? Because when you generally load some data into a new listing instance, you want to see which properties </remarks>
        ConvertToResult ConvertTo(string data,
            bool isClearAllIsModified = false,
            bool areBadCharactersRemoved = false);
    }
}

namespace OpenRealEstate.Services
{
    public interface ITransmorgrifier
    {
        ///
        /// Converts some given data into a listing instance.
        ///
        /// <param name="data">some data source, like Xml data or json data.</param>
        /// <param name="areBadCharactersRemoved">Help clean up the data.</param>
        /// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param>
        /// <returns>List of listings and any unhandled data.</returns>
        /// <remarks>Why does isClearAllIsModified default to false? Because when you generally load some data into a new listing instance, you want to see which properties </remarks>
        ConvertToResult ConvertTo(string data,
            bool areBadCharactersRemoved = false,
            bool isClearAllIsModified = false);
    }
}

Correct ordering of method arguments.

Correct ordering of method arguments.


// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace Core2D.Avalonia
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.AttachDevTools();
            Renderer.DrawDirtyRects = true;
            Renderer.DrawFps = true;
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace Core2D.Avalonia
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.AttachDevTools();
#if DEBUG
            Renderer.DrawDirtyRects = true;
            Renderer.DrawFps = true;
#endif
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

Enable only in debug mode

Enable only in debug mode


using LiteNetLib;
using System;

namespace LiteNetLibManager
{
    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
    public class SyncFieldAttribute : Attribute
    {
        /// <summary>
        /// Sending method type
        /// </summary>
        public DeliveryMethod deliveryMethod;
        /// <summary>
        /// Interval to send network data (0.01f to 2f)
        /// </summary>
        public float sendInterval = 0.1f;
        /// <summary>
        /// If this is `TRUE` it will syncing although no changes
        /// </summary>
        public bool alwaysSync;
        /// <summary>
        /// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later)
        /// </summary>
        public bool doNotSyncInitialDataImmediately;
        /// <summary>
        /// How data changes handle and sync
        /// </summary>
        public LiteNetLibSyncField.SyncMode syncMode;
        /// <summary>
        /// Function name which will be invoked when data changed
        /// </summary>
        public string hook;
    }
}

using LiteNetLib;
using System;

namespace LiteNetLibManager
{
    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
    public class SyncFieldAttribute : Attribute
    {
        /// <summary>
        /// Sending method type
        /// </summary>
        public DeliveryMethod deliveryMethod = DeliveryMethod.ReliableOrdered;
        /// <summary>
        /// Interval to send network data (0.01f to 2f)
        /// </summary>
        public float sendInterval = 0.1f;
        /// <summary>
        /// If this is `TRUE` it will syncing although no changes
        /// </summary>
        public bool alwaysSync = false;
        /// <summary>
        /// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later)
        /// </summary>
        public bool doNotSyncInitialDataImmediately = false;
        /// <summary>
        /// How data changes handle and sync
        /// </summary>
        public LiteNetLibSyncField.SyncMode syncMode = LiteNetLibSyncField.SyncMode.ServerToClients;
        /// <summary>
        /// Function name which will be invoked when data changed
        /// </summary>
        public string hook = string.Empty;
    }
}

Set default values to sync field attribute


using System;
using Microsoft.EntityFrameworkCore.Migrations;
using System.IO;

namespace osu.Game.Migrations
{
    public partial class StandardizePaths : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            string sanitized = Path.DirectorySeparatorChar.ToString();
            string standardized = "/";

            // Escaping \ does not seem to be needed.
            migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{sanitized}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{sanitized}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{sanitized}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
        }
    }
}

using System;
using Microsoft.EntityFrameworkCore.Migrations;
using System.IO;

namespace osu.Game.Migrations
{
    public partial class StandardizePaths : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            string windowsStyle = @"\";
            string standardized = "/";

            // Escaping \ does not seem to be needed.
            migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{windowsStyle}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{windowsStyle}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{windowsStyle}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')");
            migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
        }
    }
}

Fix Windows-style path separators not being migrated on Unix systems


// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Applicative
{
    using System;

    using Narvalo;

    // Query Expression Pattern for nullables.
    public static class Qullable
    {
        public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
            where TSource : struct
            where TResult : struct
        {
            Require.NotNull(selector, nameof(selector));

            return @this.HasValue ? (TResult?)selector(@this.Value) : null;
        }

        public static TSource? Where<TSource>(
            this TSource? @this,
            Func<TSource, bool> predicate)
            where TSource : struct
        {
            Require.NotNull(predicate, nameof(predicate));

            return @this.HasValue && predicate(@this.Value) ? @this : null;
        }

        public static TResult? SelectMany<TSource, TMiddle, TResult>(
            this TSource? @this,
            Func<TSource, TMiddle?> valueSelector,
            Func<TSource, TMiddle, TResult> resultSelector)
            where TSource : struct
            where TMiddle : struct
            where TResult : struct
        {
            Require.NotNull(valueSelector, nameof(valueSelector));
            Require.NotNull(resultSelector, nameof(resultSelector));

            if (!@this.HasValue) { return null; }

            var middle = valueSelector(@this.Value);

            if (!middle.HasValue) { return null; }

            return resultSelector(@this.Value, middle.Value);
        }
    }
}

// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Applicative
{
    using System;

    using Narvalo;

    // Query Expression Pattern for nullables.
    public static class Qullable
    {
        public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
            where TSource : struct
            where TResult : struct
        {
            Require.NotNull(selector, nameof(selector));

            return @this is TSource v ? (TResult?)selector(v) : null;
        }

        public static TSource? Where<TSource>(
            this TSource? @this,
            Func<TSource, bool> predicate)
            where TSource : struct
        {
            Require.NotNull(predicate, nameof(predicate));

            return @this is TSource v && predicate(v) ? @this : null;
        }

        public static TResult? SelectMany<TSource, TResult>(
            this TSource? @this,
            Func<TSource, TResult?> selector)
            where TSource : struct
            where TResult : struct
        {
            Require.NotNull(selector, nameof(selector));

            return @this is TSource v ? selector(v) : null;
        }

        public static TResult? SelectMany<TSource, TMiddle, TResult>(
            this TSource? @this,
            Func<TSource, TMiddle?> valueSelector,
            Func<TSource, TMiddle, TResult> resultSelector)
            where TSource : struct
            where TMiddle : struct
            where TResult : struct
        {
            Require.NotNull(valueSelector, nameof(valueSelector));
            Require.NotNull(resultSelector, nameof(resultSelector));

            return @this is TSource v && valueSelector(v) is TMiddle m
                ? resultSelector(v, m)
                : (TResult?)null;
        }
    }
}

Add one overload for Nullable<T>.SelectMany.


namespace MvcTurbine.ComponentModel {
    using System;

    /// <summary>
    /// Defines common assemblies to filter. These assemblies are:
    ///     System, mscorlib, Microsoft, WebDev, CppCodeProvider).
    /// </summary>
    [Serializable]
    public class CommonAssemblyFilter : AssemblyFilter {
        /// <summary>
        /// Creates an instance and applies the default filters.
        /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
        /// </summary>
        public CommonAssemblyFilter() {
            AddDefaults();
        }

        /// <summary>
        /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
        /// </summary>
        private void AddDefaults() {
            AddFilter("System");
            AddFilter("mscorlib");
            AddFilter("Microsoft");

            AddFilter("MvcTurbine");
            AddFilter("MvcTurbine.Web");

            // Ignore the Visual Studio extra assemblies!
            AddFilter("WebDev");
            AddFilter("CppCodeProvider");
        }
    }
}

namespace MvcTurbine.ComponentModel {
    using System;

    /// <summary>
    /// Defines common assemblies to filter. These assemblies are:
    ///     System, mscorlib, Microsoft, WebDev, CppCodeProvider).
    /// </summary>
    [Serializable]
    public class CommonAssemblyFilter : AssemblyFilter {
        /// <summary>
        /// Creates an instance and applies the default filters.
        /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
        /// </summary>
        public CommonAssemblyFilter() {
            AddDefaults();
        }

        /// <summary>
        /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
        /// </summary>
        private void AddDefaults() {
            AddFilter("System");
            AddFilter("mscorlib");
            AddFilter("Microsoft");

            AddFilter("MvcTurbine,");
            AddFilter("MvcTurbine.Web");

            // Ignore the Visual Studio extra assemblies!
            AddFilter("WebDev");
            AddFilter("CppCodeProvider");
        }
    }
}

Add a comma to the MvcTurbine filters, which will prevent MvcTurbine from being included but not block out MvcTurbine.*.


using System.Collections.Generic;
using TechSmith.Hyde.Table.Azure;

namespace TechSmith.Hyde.Table.Memory
{
   internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
   {
      public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
         : base( entities )
      {
      }

      private DynamicMemoryQuery( DynamicMemoryQuery previous )
         : base( previous )
      {
      }

      protected override AbstractQuery<dynamic> CreateCopy()
      {
         return new DynamicMemoryQuery( this );
      }

      internal override dynamic Convert( GenericTableEntity e )
      {
         return e.ConvertToDynamic();
      }
   }
}

using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using TechSmith.Hyde.Table.Azure;

namespace TechSmith.Hyde.Table.Memory
{
   internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
   {
      public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
         : base( entities )
      {
      }

      private DynamicMemoryQuery( DynamicMemoryQuery previous )
         : base( previous )
      {
      }

      protected override AbstractQuery<dynamic> CreateCopy()
      {
         return new DynamicMemoryQuery( this );
      }

      internal override dynamic Convert( GenericTableEntity e )
      {
         return StripNullValues( e.ConvertToDynamic() );
      }

      private static dynamic StripNullValues( dynamic obj )
      {
         dynamic result = new ExpandoObject();
         foreach ( var p in ( obj as IDictionary<string, object> ).Where( p => p.Value != null ) )
         {
            ( (IDictionary<string, object>) result ).Add( p );
         }
         return result;
      }
   }
}

Fix issue with null values returned by Memory provider


using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace OptionsDisplay
{
    class HearthWindow : InfoWindow
    {

        private HearthstoneTextBlock info;

        public HearthWindow()
        {
            info = new HearthstoneTextBlock();
            info.Text = "";
            info.FontSize = 12;
            var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
            var fromTop = canvas.Height / 2;
            var fromLeft = canvas.Width / 2;
            Canvas.SetTop(info, fromTop);
            Canvas.SetLeft(info, fromLeft);
            canvas.Children.Add(info);
        }

        public void AppendWindowText(string text)
        {
            info.Text = info.Text + text;
        }

        public void ClearAll()
        {
            info.Text = "";
        }

        public void MoveToHistory()
        {
            return;
        }

        public void SetWindowText(string text)
        {
            info.Text = text;
        }
    }
}

using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace OptionsDisplay
{
    class HearthWindow : InfoWindow
    {

        private HearthstoneTextBlock info;

        public HearthWindow()
        {
            info = new HearthstoneTextBlock();
            info.Text = "";
            info.FontSize = 12;
            var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
            var fromTop = canvas.Height / 2;
            var fromLeft = canvas.Width / 2;
            Canvas.SetTop(info, fromTop);
            Canvas.SetLeft(info, fromLeft);
            canvas.Children.Add(info);
        }

        public void AppendWindowText(string text)
        {
            info.Text = info.Text + text;
        }

        public void ClearAll()
        {
            info.Text = "";
        }

        public void MoveToHistory()
        {
            info.Text = "";
        }

        public void SetWindowText(string text)
        {
            info.Text = text;
        }
    }
}

Add trivial history programming to overlay window to clear each turn


namespace NetIRC.Messages
{
    public class PingMessage : IRCMessage, IServerMessage
    {
        public string Target { get; }

        public PingMessage(ParsedIRCMessage parsedMessage)
        {
            Target = parsedMessage.Trailing ?? parsedMessage.Parameters[0];
        }
    }
}

namespace NetIRC.Messages
{
    public class PingMessage : IRCMessage, IServerMessage
    {
        public string Target { get; }

        public PingMessage(ParsedIRCMessage parsedMessage)
        {
            Target = parsedMessage.Trailing;
        }
    }
}

Remove unnecessary null coalescing operator


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;

namespace osu.Game.Screens.Play
{
    /// <summary>
    /// Ensures screen is not suspended / dimmed while gameplay is active.
    /// </summary>
    public class ScreenSuspensionHandler : Component
    {
        private readonly GameplayClockContainer gameplayClockContainer;
        private Bindable<bool> isPaused;

        [Resolved]
        private GameHost host { get; set; }

        public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
        {
            this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            // This is the only usage game-wide of suspension changes.
            // Assert to ensure we don't accidentally forget this in the future.
            Debug.Assert(host.AllowScreenSuspension.Value);

            isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
            isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            isPaused?.UnbindAll();

            if (host != null)
                host.AllowScreenSuspension.Value = true;
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;

namespace osu.Game.Screens.Play
{
    /// <summary>
    /// Ensures screen is not suspended / dimmed while gameplay is active.
    /// </summary>
    public class ScreenSuspensionHandler : Component
    {
        private readonly GameplayClockContainer gameplayClockContainer;
        private Bindable<bool> isPaused;

        private readonly Bindable<bool> disableSuspensionBindable = new Bindable<bool>();

        [Resolved]
        private GameHost host { get; set; }

        public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
        {
            this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
            isPaused.BindValueChanged(paused =>
            {
                if (paused.NewValue)
                    host.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
                else
                    host.AllowScreenSuspension.AddSource(disableSuspensionBindable);
            }, true);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            isPaused?.UnbindAll();
            host?.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
        }
    }
}

Apply changes to AllowScreenSuspension bindable


using System;

namespace FalconUDP
{
    internal static class FalconHelper
    {
        internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
            int dstIndex,
            PacketType type,
            SendOptions opts,
            ushort seq,
            ushort payloadSize)
        {
            fixed (byte* ptr = &dstBuffer[dstIndex])
            {
                *ptr = (byte)((byte)opts | (byte)type);
                *(ushort*)(ptr + 1) = seq;
                *(ushort*)(ptr + 3) = payloadSize;
            }
        }

        internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
            int dstIndex,
            PacketType type,
            SendOptions opts,
            ushort payloadSize)
        {
            fixed (byte* ptr = &dstBuffer[dstIndex])
            {
                *ptr = (byte)((byte)opts | (byte)type);
                *(ushort*)(ptr + 1) = payloadSize;
            }
        }

        internal static void WriteAck(AckDetail ack,
            byte[] dstBuffer,
            int dstIndex)
        {
            float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000;
            ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
                ? ushort.MaxValue
                : (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue

            WriteFalconHeader(dstBuffer,
                dstIndex,
                ack.Type,
                ack.Channel,
                ack.Seq,
                stopoverMilliseconds);
        }
    }
}

using System;

namespace FalconUDP
{
    internal static class FalconHelper
    {
        internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
            int dstIndex,
            PacketType type,
            SendOptions opts,
            ushort seq,
            ushort payloadSize)
        {
            fixed (byte* ptr = &dstBuffer[dstIndex])
            {
                *ptr = (byte)((byte)opts | (byte)type);
                *(ushort*)(ptr + 1) = seq;
                *(ushort*)(ptr + 3) = payloadSize;
            }
        }

        internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
            int dstIndex,
            PacketType type,
            SendOptions opts,
            ushort payloadSize)
        {
            fixed (byte* ptr = &dstBuffer[dstIndex])
            {
                *ptr = (byte)((byte)opts | (byte)type);
                *(ushort*)(ptr + 1) = payloadSize;
            }
        }

        internal static void WriteAck(AckDetail ack,
            byte[] dstBuffer,
            int dstIndex)
        {
            float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000.0f;
            ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
                ? ushort.MaxValue
                : (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue

            WriteFalconHeader(dstBuffer,
                dstIndex,
                ack.Type,
                ack.Channel,
                ack.Seq,
                stopoverMilliseconds);
        }
    }
}

Use float instead of int

Use float instead of int


using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;

namespace Csla.Security
{
  public abstract partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
  {
    public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
    {
      DataPortal<T> dp = new DataPortal<T>();
      dp.FetchCompleted += completed;
      dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
    }
  }
}

using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;

namespace Csla.Security
{
  public partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
  {
    public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
    {
      DataPortal<T> dp = new DataPortal<T>();
      dp.FetchCompleted += completed;
      dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
    }
  }
}

Change MembershipIdentity so it is not an abstract class. bugid: 153


namespace Stripe
{
    public static class FilePurpose
    {
        public const string AdditionalVerification = "additional_verification";

        public const string BusinessIcon = "business_icon";

        public const string BusinessLogo = "business_logo";

        public const string CustomerSignature = "customer_signature";

        public const string DisputeEvidence = "dispute_evidence";

        public const string DocumentProviderIdentityDocument = "document_provider_identity_document";

        public const string FinanceReportRun = "finance_report_run";

        public const string IdentityDocument = "identity_document";

        public const string IncorporationArticle = "incorporation_article";

        public const string IncorporationDocument = "incorporation_document";

        public const string PaymentProviderTransfer = "payment_provider_transfer";

        public const string PciDocument = "pci_document";

        public const string ProductFeed = "product_feed";

        public const string SigmaScheduledQuery = "sigma_scheduled_query";

        public const string TaxDocumentUserUpload = "tax_document_user_upload";
    }
}

namespace Stripe
{
    public static class FilePurpose
    {
        public const string AccountRequirement = "account_requirement";

        public const string AdditionalVerification = "additional_verification";

        public const string BusinessIcon = "business_icon";

        public const string BusinessLogo = "business_logo";

        public const string CustomerSignature = "customer_signature";

        public const string DisputeEvidence = "dispute_evidence";

        public const string DocumentProviderIdentityDocument = "document_provider_identity_document";

        public const string FinanceReportRun = "finance_report_run";

        public const string IdentityDocument = "identity_document";

        public const string IdentityDocumentDownloadable = "identity_document_downloadable";

        public const string IncorporationArticle = "incorporation_article";

        public const string IncorporationDocument = "incorporation_document";

        public const string PaymentProviderTransfer = "payment_provider_transfer";

        public const string PciDocument = "pci_document";

        public const string Selfie = "selfie";

        public const string ProductFeed = "product_feed";

        public const string SigmaScheduledQuery = "sigma_scheduled_query";

        public const string TaxDocumentUserUpload = "tax_document_user_upload";
    }
}

Add missing enums for File purpose

Add missing enums for File purpose


using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ChangeOrderInLayer : MonoBehaviour
{
#pragma warning disable 0649
    [SerializeField]
    private Renderer _renderer;
    [SerializeField]
    private int orderInLayer;
#pragma warning restore 0649

	void Start()
	{
        if (_renderer == null)
            _renderer = GetComponent<Renderer>();
		_renderer.sortingOrder = orderInLayer;
	}

	void Update ()
	{
		if (orderInLayer != _renderer.sortingOrder)
			_renderer.sortingOrder = orderInLayer;
	}
}

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ChangeOrderInLayer : MonoBehaviour
{
    [SerializeField]
    private Renderer _renderer;
    [SerializeField]
    private int orderInLayer;
    [SerializeField]
    private string sortingLayer = "Default";
    [SerializeField]
    private bool disableOnPlay = true;

    private void Awake()
    {
        if (disableOnPlay && Application.isPlaying)
            enabled = false;
    }

    void Start()
	{
        if (_renderer == null)
            _renderer = GetComponent<Renderer>();
		_renderer.sortingOrder = orderInLayer;
	}

	void Update ()
	{
        if (orderInLayer != _renderer.sortingOrder)
            _renderer.sortingOrder = orderInLayer;
        if (!string.IsNullOrEmpty(sortingLayer))
            _renderer.sortingLayerName = sortingLayer;
	}
}

Add disableOnPlay option to changeOrderInLayer


using FluentAssertions;
using FluentAssertions.Execution;

namespace Bearded.Utilities.Testing
{
    public sealed class MaybeAssertions<T>
    {
        private readonly Maybe<T> subject;

        public MaybeAssertions(Maybe<T> instance) => subject = instance;

        [CustomAssertion]
        public void BeJust(T value, string because = "", params object[] becauseArgs)
        {
            BeJust().Which.Should().BeEquivalentTo(value, because, becauseArgs);
        }

        [CustomAssertion]
        public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs)
        {
            var onValueCalled = false;
            var matched = default(T);

            subject.Match(
                onValue: actual =>
                {
                    onValueCalled = true;
                    matched = actual;
                }, onNothing: () => { });

            Execute.Assertion
                .BecauseOf(because, becauseArgs)
                .ForCondition(onValueCalled)
                .FailWith("Expected maybe to have value, but had none.");

            return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched);
        }

        [CustomAssertion]
        public void BeNothing(string because = "", params object[] becauseArgs)
        {
            var onNothingCalled = false;

            subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true);

            Execute.Assertion
                .BecauseOf(because, becauseArgs)
                .ForCondition(onNothingCalled)
                .FailWith("Expected maybe to be nothing, but had value.");
        }
    }
}

using FluentAssertions;
using FluentAssertions.Execution;

namespace Bearded.Utilities.Testing
{
    public sealed class MaybeAssertions<T>
    {
        private readonly Maybe<T> subject;

        public MaybeAssertions(Maybe<T> instance) => subject = instance;

        [CustomAssertion]
        public void BeJust(T value, string because = "", params object[] becauseArgs)
        {
            BeJust().Which.Should().Be(value, because, becauseArgs);
        }

        [CustomAssertion]
        public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs)
        {
            var onValueCalled = false;
            var matched = default(T);

            subject.Match(
                onValue: actual =>
                {
                    onValueCalled = true;
                    matched = actual;
                }, onNothing: () => { });

            Execute.Assertion
                .BecauseOf(because, becauseArgs)
                .ForCondition(onValueCalled)
                .FailWith("Expected maybe to have value, but had none.");

            return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched);
        }

        [CustomAssertion]
        public void BeNothing(string because = "", params object[] becauseArgs)
        {
            var onNothingCalled = false;

            subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true);

            Execute.Assertion
                .BecauseOf(because, becauseArgs)
                .ForCondition(onNothingCalled)
                .FailWith("Expected maybe to be nothing, but had value.");
        }
    }
}

Use Be instead of BeEquivalentTo

:bug: Use Be instead of BeEquivalentTo


using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using Procon.Service.Shared;
using Procon.Setup.Models;

namespace Procon.Setup.Test.Models {
    [TestFixture]
    public class CertificateModelTest {
        /// <summary>
        /// Tests a certificate will be generated and can be read by .NET
        /// </summary>
        [Test]
        public void TestGenerate() {
            CertificateModel model = new CertificateModel();

            // Delete the certificate if it exists.
            Defines.CertificatesDirectoryCommandServerPfx.Delete();

            // Create a new certificate
            model.Generate();

            // Certificate exists
            Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists);

            // Loads the certificates
            var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password);

            // Certificate can be loaded.
            Assert.IsNotNull(loadedCertificate);
            Assert.IsNotNull(loadedCertificate.PrivateKey);
        }
    }
}

using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using Procon.Service.Shared;
using Procon.Setup.Models;

namespace Procon.Setup.Test.Models {
    [TestFixture]
    public class CertificateModelTest {
        /// <summary>
        /// Tests a certificate will be generated and can be read by .NET
        /// </summary>
        [Test]
        public void TestGenerate() {
            CertificateModel model = new CertificateModel();

            // Delete the certificate if it exists.
            Defines.CertificatesDirectoryCommandServerPfx.Delete();

            // Create a new certificate
            model.Generate();

            // Certificate exists
            Defines.CertificatesDirectoryCommandServerPfx.Refresh();
            Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists);

            // Loads the certificates
            var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password);

            // Certificate can be loaded.
            Assert.IsNotNull(loadedCertificate);
            Assert.IsNotNull(loadedCertificate.PrivateKey);
        }
    }
}

Fix certificate generation not refreshing test


namespace BigEgg.Tools.JsonComparer.Parameters
{
    using BigEgg.Tools.ConsoleExtension.Parameters;

    [Command("split", "Split the big JSON file to multiple small files.")]
    public class SplitParameter
    {
        [StringProperty("input", "i", "The path of JSON file to split.", Required = true)]
        public string FileName { get; set; }

        [StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)]
        public string OutputPath { get; set; }

        [StringProperty("node_name", "n", "The name of node to split.", Required = true)]
        public string NodeName { get; set; }

        [StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, ${index} for the child index.")]
        public string OutputFileNamePattern { get; set; }
    }
}

namespace BigEgg.Tools.JsonComparer.Parameters
{
    using BigEgg.Tools.ConsoleExtension.Parameters;

    [Command("split", "Split the big JSON file to multiple small files.")]
    public class SplitParameter
    {
        [StringProperty("input", "i", "The path of JSON file to split.", Required = true)]
        public string FileName { get; set; }

        [StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)]
        public string OutputPath { get; set; }

        [StringProperty("node_name", "n", "The name of node to split.", Required = true)]
        public string NodeName { get; set; }

        [StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, '${index}' for the child index.")]
        public string OutputFileNamePattern { get; set; }
    }
}

Fix the help message of output_pattern

Fix the help message of output_pattern