using UnityEngine;
using System.Collections;

public class FileChooser : MonoBehaviour {

	FileBrowser fb = new FileBrowser();

	void OnGUI(){
		fb.searchPattern = "*.xml";

		FileLoaderXML fl = new FileLoaderXML();

		if(fb.draw()){
			if(fb.outputFile == null){
				Debug.Log("Cancel hit");
			}else{
				Debug.Log("Ouput File = \""+fb.outputFile.ToString()+"\"");
				/*the outputFile variable is of type FileInfo from the .NET library "http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx"*/
				fl.loadXMLFile(fb.outputFile.ToString());
			}
		}
	}

	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {
	}
}

using UnityEngine;
using System.Collections;

public class FileChooser : MonoBehaviour {

	FileBrowser fb = new FileBrowser();
	FileLoaderXML fl = new FileLoaderXML();

	// Use this for initialization
	void Start () {
		fb.searchPattern = "*.xml";
	}

	void OnGUI(){
		if (fb.draw()) {
			if (fb.outputFile == null){
				Debug.Log("Cancel hit");
				Application.Quit();
			} else {
				Debug.Log("Ouput File = \""+fb.outputFile.ToString()+"\"");
				/*the outputFile variable is of type FileInfo from the .NET library "http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx"*/
				fl.loadXMLFile(fb.outputFile.FullName);
				Destroy (this);
			}
		}
	}

	// Update is called once per frame
	void Update () {
	}
}

Make open file also work at runtime

Make open file also work at runtime

the file chooser didn't return the absolute path in runtime (?)


/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System;
using Microsoft.Xna.Framework;

namespace ShiftDrive {

    /// <summary>
    /// Represents the maximum weapon size that a mount can hold.
    /// </summary>
    internal enum MountSize {
        Small = 1,
        Medium = 2,
        Large = 3
    }

    /// <summary>
    /// Represents an attachment point for a weapon.
    /// </summary>
    internal sealed class WeaponMount {

        public Vector2 Offset;
        public Vector2 Position;
        public float Bearing;
        public float Arc;
        public float OffsetMag;
        public MountSize Size;

        public static WeaponMount FromLua(IntPtr L, int tableidx) {
            LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE);

            WeaponMount ret = new WeaponMount();
            LuaAPI.lua_getfield(L, tableidx, "position");
            LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE);
            ret.Offset = LuaAPI.lua_tovec2(L, -1);
            ret.OffsetMag = -ret.Offset.Length();
            LuaAPI.lua_pop(L, 1);
            ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing");
            ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc");
            ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size");
            return ret;
        }

    }

}

/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System;
using Microsoft.Xna.Framework;

namespace ShiftDrive {

    /// <summary>
    /// Represents the maximum weapon size that a mount can hold.
    /// </summary>
    internal enum MountSize {
        Small = 1,
        Medium = 2,
        Large = 3
    }

    /// <summary>
    /// Represents an attachment point for a weapon.
    /// </summary>
    internal sealed class WeaponMount {

        public Vector2 Offset;
        public Vector2 Position;
        public float Bearing;
        public float Arc;
        public float OffsetMag;
        public MountSize Size;

        public static WeaponMount FromLua(IntPtr L, int tableidx) {
            LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE);

            WeaponMount ret = new WeaponMount();
            LuaAPI.lua_getfield(L, tableidx, "position");
            LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE);
            ret.Offset = LuaAPI.lua_tovec2(L, -1);
            ret.OffsetMag = -ret.Offset.Length();
            LuaAPI.lua_pop(L, 1);
            ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing");
            ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc") / 2f;
            ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size");
            return ret;
        }

    }

}

Divide weapon arc by half

Divide weapon arc by half

Because WeaponMount.arc is added to either side of the bearing, the
total arc would be 2x arc value. Halving the property in the Lua script
fixes this problem.


using System;
using System.Collections.Generic;
using System.Linq;
using GitVersion.VersionCalculation.BaseVersionCalculators;

namespace GitVersion.VersionFilters
{
    public class ShaVersionFilter : IVersionFilter
    {
        private readonly IEnumerable<string> shas;

        public ShaVersionFilter(IEnumerable<string> shas)
        {
            if (shas == null) throw new ArgumentNullException("shas");
            this.shas = shas;
        }

        public bool Exclude(BaseVersion version, out string reason)
        {
            if (version == null) throw new ArgumentNullException("version");

            reason = null;

            if (version.BaseVersionSource != null &&
                shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase)))
            {
                reason = "Source was ignored due to commit having been excluded by configuration";
                return true;
            }

            return false;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using GitVersion.VersionCalculation.BaseVersionCalculators;

namespace GitVersion.VersionFilters
{
    public class ShaVersionFilter : IVersionFilter
    {
        private readonly IEnumerable<string> shas;

        public ShaVersionFilter(IEnumerable<string> shas)
        {
            if (shas == null) throw new ArgumentNullException("shas");
            this.shas = shas;
        }

        public bool Exclude(BaseVersion version, out string reason)
        {
            if (version == null) throw new ArgumentNullException("version");

            reason = null;

            if (version.BaseVersionSource != null &&
                shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase)))
            {
                reason = $"Sha {version.BaseVersionSource.Sha} was ignored due to commit having been excluded by configuration";
                return true;
            }

            return false;
        }
    }
}

Print the sha which was excluded from version calculation


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

namespace GTPWrapper {
    public class GTPWrapper {
        public GTPWrapper() {

        }

        public string Command(string input) {
            return "";
        }
    }
}

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

namespace GTPWrapper {
    public class GTPWrapper {
        public GTPWrapper() {

        }

        public string Command(string input) {
            return "=";
        }
    }
}

Test commit from Visual Studio

Test commit from Visual Studio


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace IronFoundry.Container
{
    public class ContainerHostDependencyHelper
    {
        const string ContainerHostAssemblyName = "IronFoundry.Container.Host";

        readonly Assembly containerHostAssembly;

        public ContainerHostDependencyHelper()
        {
            this.containerHostAssembly = GetContainerHostAssembly();
        }

        public virtual string ContainerHostExe
        {
            get { return ContainerHostAssemblyName + ".exe"; }
        }

        public virtual string ContainerHostExePath
        {
            get { return containerHostAssembly.Location; }
        }

        static Assembly GetContainerHostAssembly()
        {
            return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName);
        }

        public virtual IReadOnlyList<string> GetContainerHostDependencies()
        {
            return EnumerateLocalReferences(containerHostAssembly).ToList();
        }

        IEnumerable<string> EnumerateLocalReferences(Assembly assembly)
        {
            foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies())
            {
                var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName);

                if (!referencedAssembly.GlobalAssemblyCache)
                {
                    yield return referencedAssembly.Location;

                    if (!referencedAssembly.Location.Contains("ICSharpCode.SharpZipLib.dll"))
                        foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly))
                            yield return nestedReferenceFilePath;
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace IronFoundry.Container
{
    public class ContainerHostDependencyHelper
    {
        const string ContainerHostAssemblyName = "IronFoundry.Container.Host";

        readonly Assembly containerHostAssembly;

        public ContainerHostDependencyHelper()
        {
            this.containerHostAssembly = GetContainerHostAssembly();
        }

        public virtual string ContainerHostExe
        {
            get { return ContainerHostAssemblyName + ".exe"; }
        }

        public virtual string ContainerHostExePath
        {
            get { return containerHostAssembly.Location; }
        }

        static Assembly GetContainerHostAssembly()
        {
            return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName);
        }

        public virtual IReadOnlyList<string> GetContainerHostDependencies()
        {
            return EnumerateLocalReferences(containerHostAssembly).ToList();
        }

        IEnumerable<string> EnumerateLocalReferences(Assembly assembly)
        {
            foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies())
            {
                var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName);

                if (!referencedAssembly.GlobalAssemblyCache)
                {
                    yield return referencedAssembly.Location;

                    foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly))
                        yield return nestedReferenceFilePath;
                }
            }
        }
    }
}

Remove unnecessary check for SharpZipLib dll.


using System;
using System.Buffers;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;

namespace SuperSocket.Channel
{
    public class UdpPipeChannel<TPackageInfo> : VirtualChannel<TPackageInfo>, IChannelWithSessionIdentifier
    {
        private Socket _socket;

        private IPEndPoint _remoteEndPoint;

        public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint)
            : this(socket, pipelineFilter, options, remoteEndPoint, $"{remoteEndPoint.Address}:{remoteEndPoint.Port}")
        {

        }

        public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier)
            : base(pipelineFilter, options)
        {
            _socket = socket;
            _remoteEndPoint = remoteEndPoint;
            SessionIdentifier = sessionIdentifier;
        }

        public string SessionIdentifier { get; }

        protected override void Close()
        {
            WriteEOFPackage();
        }

        protected override ValueTask<int> FillPipeWithDataAsync(Memory<byte> memory, CancellationToken cancellationToken)
        {
            throw new NotSupportedException();
        }

        protected override async ValueTask<int> SendOverIOAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken)
        {
            var total = 0;

            foreach (var piece in buffer)
            {
                total += await _socket.SendToAsync(GetArrayByMemory<byte>(piece), SocketFlags.None, _remoteEndPoint);
            }

            return total;
        }
    }
}

using System;
using System.Buffers;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;

namespace SuperSocket.Channel
{
    public class UdpPipeChannel<TPackageInfo> : VirtualChannel<TPackageInfo>, IChannelWithSessionIdentifier
    {
        private Socket _socket;

        public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint)
            : this(socket, pipelineFilter, options, remoteEndPoint, $"{remoteEndPoint.Address}:{remoteEndPoint.Port}")
        {

        }

        public UdpPipeChannel(Socket socket, IPipelineFilter<TPackageInfo> pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier)
            : base(pipelineFilter, options)
        {
            _socket = socket;
            RemoteEndPoint = remoteEndPoint;
            SessionIdentifier = sessionIdentifier;
        }

        public string SessionIdentifier { get; }

        protected override void Close()
        {
            WriteEOFPackage();
        }

        protected override ValueTask<int> FillPipeWithDataAsync(Memory<byte> memory, CancellationToken cancellationToken)
        {
            throw new NotSupportedException();
        }

        protected override async ValueTask<int> SendOverIOAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken)
        {
            var total = 0;

            foreach (var piece in buffer)
            {
                total += await _socket.SendToAsync(GetArrayByMemory<byte>(piece), SocketFlags.None, RemoteEndPoint);
            }

            return total;
        }
    }
}

Set RemoteEndPoint for UDP connections

Set RemoteEndPoint for UDP connections


using System;

namespace WeifenLuo.WinFormsUI.Docking
{
    using System.ComponentModel;

    public partial class DockPanel
    {
        private DockPanelSkin m_dockPanelSkin = VS2005Theme.CreateVisualStudio2005();
        [LocalizedCategory("Category_Docking")]
        [LocalizedDescription("DockPanel_DockPanelSkin")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Obsolete("Please use Theme instead.")]
        public DockPanelSkin Skin
        {
            get { return m_dockPanelSkin;  }
            set { m_dockPanelSkin = value; }
        }

        private ThemeBase m_dockPanelTheme = new VS2005Theme();
        [LocalizedCategory("Category_Docking")]
        [LocalizedDescription("DockPanel_DockPanelTheme")]
        public ThemeBase Theme
        {
            get { return m_dockPanelTheme; }
            set
            {
                if (value == null)
                {
                    return;
                }

                if (m_dockPanelTheme.GetType() == value.GetType())
                {
                    return;
                }

                m_dockPanelTheme = value;
                m_dockPanelTheme.Apply(this);
            }
        }
    }
}

using System;

namespace WeifenLuo.WinFormsUI.Docking
{
    using System.ComponentModel;

    public partial class DockPanel
    {
        private DockPanelSkin m_dockPanelSkin = VS2005Theme.CreateVisualStudio2005();
        [LocalizedCategory("Category_Docking")]
        [LocalizedDescription("DockPanel_DockPanelSkin")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Obsolete("Please use Theme instead.")]
        [Browsable(false)]
        public DockPanelSkin Skin
        {
            get { return m_dockPanelSkin;  }
            set { m_dockPanelSkin = value; }
        }

        private ThemeBase m_dockPanelTheme = new VS2005Theme();
        [LocalizedCategory("Category_Docking")]
        [LocalizedDescription("DockPanel_DockPanelTheme")]
        public ThemeBase Theme
        {
            get { return m_dockPanelTheme; }
            set
            {
                if (value == null)
                {
                    return;
                }

                if (m_dockPanelTheme.GetType() == value.GetType())
                {
                    return;
                }

                m_dockPanelTheme = value;
                m_dockPanelTheme.Apply(this);
            }
        }
    }
}

Set Browsable to false to hide DockPanel.Skin property.


using Mazzimo.Models;
using Mazzimo.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mazzimo.Controllers
{
    public class HomeController : Controller
    {
        IPostRepository _postRepo;
        IResumeRepository _cvRepo;
        public HomeController(IPostRepository postRepo,
                              IResumeRepository cvRepo)
        {
            _postRepo = postRepo;
            _cvRepo = cvRepo;
        }

        public ActionResult Index()
        {
            var post = _postRepo.GetFirst();

            if (post == null)
                post = _postRepo.GetIntroductionPost();

            return View(post);
        }

        public ActionResult Cv(string id)
        {
            var cv = _cvRepo.GetResumeFromLanguageCode(id);
            if (cv == null)
                return HttpNotFound();
            ViewBag.Id = id;
            return View(cv);
        }

        public ActionResult CvPrint(string id)
        {
            var cv = _cvRepo.GetResumeFromLanguageCode(id);
            if (cv == null)
                return HttpNotFound();
            Response.Cache.SetExpires(DateTime.Now.AddYears(1));
            Response.Cache.SetCacheability(HttpCacheability.Public);

            return View(cv);
        }

        public ActionResult Post(string id)
        {
            var post = _postRepo.GetById(id);
            if (post == null)
                return HttpNotFound();

            return View(post);
        }
    }
}

using Mazzimo.Models;
using Mazzimo.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mazzimo.Controllers
{
    public class HomeController : Controller
    {
        IPostRepository _postRepo;
        IResumeRepository _cvRepo;
        public HomeController(IPostRepository postRepo,
                              IResumeRepository cvRepo)
        {
            _postRepo = postRepo;
            _cvRepo = cvRepo;
        }

        public ActionResult Index()
        {
            var post = _postRepo.GetFirst();

            if (post == null)
                post = _postRepo.GetIntroductionPost();

            return View(post);
        }

        public ActionResult Cv(string id)
        {
            var cv = _cvRepo.GetResumeFromLanguageCode(id);
            if (cv == null)
                return HttpNotFound();
            ViewBag.Id = id;
            return View(cv);
        }

        public ActionResult CvPrint(string id)
        {
            var cv = _cvRepo.GetResumeFromLanguageCode(id);
            if (cv == null)
                return HttpNotFound();

            return View(cv);
        }

        public ActionResult Post(string id)
        {
            var post = _postRepo.GetById(id);
            if (post == null)
                return HttpNotFound();

            return View(post);
        }
    }
}

Remove Cache From Print Version

Remove Cache From Print Version


extern alias pcl;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace MetroLog
{
    public static class GlobalCrashHandler
    {
        public static void Configure()
        {
            Application.Current.UnhandledException += App_UnhandledException;
        }

        private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // unbind we're going to re-enter and don't want to loop...
            Application.Current.UnhandledException -= App_UnhandledException;

            // say we've handled this one. this allows our FATAL write to complete.
            e.Handled = true;

            // go...
            var log = (ILoggerAsync)pcl::MetroLog.LogManagerFactory.DefaultLogManager.GetLogger<Application>();
            await log.FatalAsync("The application crashed: " + e.Message, e.Exception);

            // if we're aborting, fake a suspend to flush the targets...
            await LazyFlushManager.FlushAllAsync(new LogWriteContext());

            // abort the app here...
            Application.Current.Exit();
        }
    }
}

extern alias pcl;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace MetroLog
{
    public static class GlobalCrashHandler
    {
        public static void Configure()
        {
            Application.Current.UnhandledException += App_UnhandledException;
        }

        private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // unbind we're going to re-enter and don't want to loop...
            Application.Current.UnhandledException -= App_UnhandledException;

            // say we've handled this one. this allows our FATAL write to complete.
            e.Handled = true;

            // go...
            var log = (ILoggerAsync)pcl::MetroLog.LogManagerFactory.DefaultLogManager.GetLogger<Application>();
            await log.FatalAsync("The application crashed: " + e.Message, e);

            // if we're aborting, fake a suspend to flush the targets...
            await LazyFlushManager.FlushAllAsync(new LogWriteContext());

            // abort the app here...
            Application.Current.Exit();
        }
    }
}

Call correct overload of log.FatalAsync

Call correct overload of log.FatalAsync

The method was previously hitting `FatalSync(string message, params object[] args)` and thereby throwing away the exception object as it wasn't referenced in the message. The change ensures that `FatalSync(string message, Exception ex)` is hit and the exception information is logged correctly.


using NUnit.Framework;

namespace ConvNetSharp.Tests
{
    [TestFixture]
    public class ConvLayerTests
    {
        [Test]
        public void GradientWrtInputCheck()
        {
            const int inputWidth = 10;
            const int inputHeight = 10;
            const int inputDepth = 2;

            // Create layer
            const int filterWidth = 3;
            const int filterHeight = 3;
            const int filterCount = 2;

            var layer = new ConvLayer(filterWidth, filterHeight, filterCount);

            GradientCheckTools.GradientCheck(layer, inputWidth, inputHeight, inputDepth);
        }

        [Test]
        public void GradientWrtParametersCheck()
        {
            const int inputWidth = 10;
            const int inputHeight = 10;
            const int inputDepth = 2;

            // Create layer
            const int filterWidth = 3;
            const int filterHeight = 3;
            const int filterCount = 2;

            var layer = new ConvLayer(filterWidth, filterHeight, filterCount);

            GradientCheckTools.GradienWrtParameterstCheck(inputWidth, inputHeight, inputDepth, layer);
        }
    }
}

using NUnit.Framework;

namespace ConvNetSharp.Tests
{
    [TestFixture]
    public class ConvLayerTests
    {
        [Test]
        public void GradientWrtInputCheck()
        {
            const int inputWidth = 30;
            const int inputHeight = 30;
            const int inputDepth = 2;

            // Create layer
            const int filterWidth = 3;
            const int filterHeight = 3;
            const int filterCount = 5;

            var layer = new ConvLayer(filterWidth, filterHeight, filterCount) { Stride = 2};

            GradientCheckTools.GradientCheck(layer, inputWidth, inputHeight, inputDepth);
        }

        [Test]
        public void GradientWrtParametersCheck()
        {
            const int inputWidth = 10;
            const int inputHeight = 10;
            const int inputDepth = 2;

            // Create layer
            const int filterWidth = 3;
            const int filterHeight = 3;
            const int filterCount = 2;

            var layer = new ConvLayer(filterWidth, filterHeight, filterCount) { Stride = 2 };

            GradientCheckTools.GradienWrtParameterstCheck(inputWidth, inputHeight, inputDepth, layer);
        }
    }
}

Make convlayer tests more complete

Make convlayer tests more complete


// 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.Threading;

#nullable enable

namespace osu.Framework.Threading
{
    /// <summary>
    /// A synchronisation context which posts all continuatiuons to a scheduler instance.
    /// </summary>
    internal class SchedulerSynchronizationContext : SynchronizationContext
    {
        private readonly Scheduler scheduler;

        public SchedulerSynchronizationContext(Scheduler scheduler)
        {
            this.scheduler = scheduler;
        }

        public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), false);
    }
}

// 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.Threading;

#nullable enable

namespace osu.Framework.Threading
{
    /// <summary>
    /// A synchronisation context which posts all continuatiuons to a scheduler instance.
    /// </summary>
    internal class SchedulerSynchronizationContext : SynchronizationContext
    {
        private readonly Scheduler scheduler;

        public SchedulerSynchronizationContext(Scheduler scheduler)
        {
            this.scheduler = scheduler;
        }

        public override void Send(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), false);

        public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), true);
    }
}

Fix insane oversight in `SynchronizationContext` implementation


using System;
using System.Web.UI.WebControls;

namespace R7.HelpDesk
{
	public partial class AdminSettings
	{
		protected Panel pnlAdminSettings;
		protected Panel pnlAdministratorRole;
		protected Panel pnlUploFilesPath;
		protected Panel pnlTagsAdmin;
		protected Panel pnlRoles;

		protected Button btnAddNew;
		protected Button btnUpdate;
		protected HyperLink lnkAdminRole;
		protected HyperLink lnkUploFilesPath;
		protected HyperLink lnkTagsAdmin;
		protected HyperLink lnkRoles;

		protected DropDownList ddlAdminRole;
		protected TextBox txtUploadedFilesPath;
		protected DropDownList ddlUploadPermission;

		protected TreeView tvCategories;
		protected Label lblAdminRole;
		protected Label lblUploadedFilesPath;
		protected TextBox txtCategoryID;

		protected DropDownList ddlParentCategory;
		protected TextBox txtCategory;
		protected CheckBox chkRequesterVisible;
		protected CheckBox chkSelectable;
		protected TextBox txtParentCategoryID;

		protected Button btnDelete;
		protected Label lblTagError;
		protected Label lblRoleError;
		protected DropDownList ddlRole;
		protected ListView lvRoles;

	}
}

using System;
using System.Web.UI.WebControls;

namespace R7.HelpDesk
{
	public partial class AdminSettings
	{
		protected Panel pnlAdminSettings;
		protected Panel pnlAdministratorRole;
		protected Panel pnlUploFilesPath;
		protected Panel pnlTagsAdmin;
		protected Panel pnlRoles;

		protected Button btnAddNew;
		protected Button btnUpdate;
		protected LinkButton lnkAdminRole;
		protected LinkButton lnkUploFilesPath;
		protected LinkButton lnkTagsAdmin;
		protected LinkButton lnkRoles;

		protected DropDownList ddlAdminRole;
		protected TextBox txtUploadedFilesPath;
		protected DropDownList ddlUploadPermission;

		protected TreeView tvCategories;
		protected Label lblAdminRole;
		protected Label lblUploadedFilesPath;
		protected TextBox txtCategoryID;

		protected DropDownList ddlParentCategory;
		protected TextBox txtCategory;
		protected CheckBox chkRequesterVisible;
		protected CheckBox chkSelectable;
		protected TextBox txtParentCategoryID;

		protected Button btnDelete;
		protected Label lblTagError;
		protected Label lblRoleError;
		protected DropDownList ddlRole;
		protected ListView lvRoles;

	}
}

Fix wrong type for linkbuttons

Fix wrong type for linkbuttons


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;

namespace CodeBreaker.WebApp.Storage
{
    public class ScoreStore : IScoreStore
    {
        private readonly CodeBreakerDbContext _dbContext;
        public ScoreStore(CodeBreakerDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<Score[]> GetScores(int page, int size)
        {
            return (await _dbContext.Scores.ToListAsync())
                .OrderBy(s => s.Attempts)
                .ThenBy(s => s.Duration)
                .Skip(page * size).Take(size)
                .ToArray();
        }

        public async Task SaveScore(Score score)
        {
            await _dbContext.Scores.AddAsync(score);
            await _dbContext.SaveChangesAsync();
        }

        public Task<bool> ScoreExists(Guid gameId)
        {
           return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;

namespace CodeBreaker.WebApp.Storage
{
    public class ScoreStore : IScoreStore
    {
        private readonly CodeBreakerDbContext _dbContext;
        public ScoreStore(CodeBreakerDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public Task<Score[]> GetScores(int page, int size)
        {
            return _dbContext.Scores
                .OrderBy(s => s.Attempts)
                .ThenBy(s => s.Duration)
                .Skip(page * size).Take(size)
                .ToArrayAsync();
        }

        public async Task SaveScore(Score score)
        {
            await _dbContext.Scores.AddAsync(score);
            await _dbContext.SaveChangesAsync();
        }

        public Task<bool> ScoreExists(Guid gameId)
        {
           return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
        }
    }
}

Fix bug with slow loading high scores

Fix bug with slow loading high scores


using System;
using System.Linq;
using System.Net.NetworkInformation;

namespace HttpMock.Integration.Tests
{
	internal static class PortHelper
	{
		internal static int FindLocalAvailablePortForTesting()
		{
			IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
			var activeTcpConnections = properties.GetActiveTcpConnections();
			const int minPort = 1024;

			var random = new Random();
			var maxPort = 64000;
			var randomPort = random.Next(minPort, maxPort);

			while (activeTcpConnections.Any(a => a.LocalEndPoint.Port == randomPort))
			{
				randomPort = random.Next(minPort, maxPort);
			}
			return randomPort;
		}
	}
}

using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

namespace HttpMock.Integration.Tests
{
	internal static class PortHelper
	{
		internal static int FindLocalAvailablePortForTesting()
		{

			const int minPort = 1024;

			var random = new Random();
			var maxPort = 64000;
			var randomPort = random.Next(minPort, maxPort);

			while (IsPortInUse(randomPort))
			{
				randomPort = random.Next(minPort, maxPort);
			}
			return randomPort;
		}

		private static bool IsPortInUse(int randomPort)
		{
			var properties = IPGlobalProperties.GetIPGlobalProperties();
			return properties.GetActiveTcpConnections().Any(a => a.LocalEndPoint.Port == randomPort) && properties.GetActiveTcpListeners().Any( a=> a.Port == randomPort);
		}
	}
}

Check for active connections in each iteration

Check for listeners too


using System.Data;
using System.Linq;

namespace ZocMonLib
{
    public class StorageCommandsSupport : IStorageCommandsSupport
    {
        public string SelectCurrentReduceStatus(IDbConnection conn)
        {
            var result = DatabaseSqlHelper.CreateListWithConnection<bool>(conn, StorageCommandsSqlServerQuery.CurrentlyReducingSql);
            if (result.Any())
                return result.First() ? "1" : "0";
            return "";
        }

        public void UpdateCurrentReduceStatus(string value, IDbConnection conn)
        {
            DatabaseSqlHelper.ExecuteNonQueryWithConnection(conn, StorageCommandsSqlServerQuery.UpdateReducingSql, new { IsReducing = value == "1" });
        }
    }
}

using System.Data;
using System.Linq;

namespace ZocMonLib
{
    public class StorageCommandsSupport : IStorageCommandsSupport
    {
        public string SelectCurrentReduceStatus(IDbConnection conn)
        {
            const string sql = @"SELECT TOP(1) IsReducing FROM Settings";

            var result = DatabaseSqlHelper.Query<bool>(conn, sql);
            if (result.Any())
                return result.First() ? "1" : "0";
            return "";
        }

        public void UpdateCurrentReduceStatus(string value, IDbConnection conn)
        {
            //TODO this doesn't take into account if it doesn't exist
            const string sql = @"UPDATE Settings SET IsReducing = @isReducing";

            DatabaseSqlHelper.Execute(conn, sql, param: new { isReducing = value == "1" });
        }
    }
}

Switch over support commands from using the query class


// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;

namespace NodaTime.Annotations
{
    /// <summary>
    /// Indicates that a type is immutable. Some members of this type
    /// allow state to be visibly changed.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    internal sealed class MutableAttribute : Attribute
    {
    }
}

 // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;

namespace NodaTime.Annotations
{
    /// <summary>
    /// Indicates that a type is mutable. Some members of this type
    /// allow state to be visibly changed.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    internal sealed class MutableAttribute : Attribute
    {
    }
}

Fix documentation confusion in a similar way to r3a00fecf9d42.


// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using Wangkanai.Detection.Extensions;
using Wangkanai.Detection.Models;

namespace Wangkanai.Detection.Services
{
    public class PlatformService : IPlatformService
    {
        public Processor Processor { get; }
        public OperatingSystem OperatingSystem { get; }

        public PlatformService(IUserAgentService userAgentService)
        {
            var userAgent = userAgentService.UserAgent;
            Processor = ParseProcessor(userAgent);
            OperatingSystem = ParseOperatingSystem(userAgent);
        }

        private static OperatingSystem ParseOperatingSystem(UserAgent agent)
        {
            if (agent.Contains(OperatingSystem.Android))
                return OperatingSystem.Android;
            if (agent.Contains(OperatingSystem.Windows))
                return OperatingSystem.Windows;
            if (agent.Contains(OperatingSystem.Mac))
                return OperatingSystem.Mac;

            return OperatingSystem.Others;
        }

        private static Processor ParseProcessor(UserAgent agent)
        {
            if (agent.Contains(Processor.ARM))
                return Processor.ARM;
            if (agent.Contains(Processor.x86))
                return Processor.x86;
            if (agent.Contains(Processor.x64))
                return Processor.x64;

            return Processor.Others;
        }
    }
}

// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using Wangkanai.Detection.Extensions;
using Wangkanai.Detection.Models;

namespace Wangkanai.Detection.Services
{
    public class PlatformService : IPlatformService
    {
        public Processor Processor { get; }
        public OperatingSystem OperatingSystem { get; }

        public PlatformService(IUserAgentService userAgentService)
        {
            var userAgent = userAgentService.UserAgent;
            Processor = ParseProcessor(userAgent);
            OperatingSystem = ParseOperatingSystem(userAgent);
        }

        private static OperatingSystem ParseOperatingSystem(UserAgent agent)
        {
            if (agent.Contains(OperatingSystem.Android))
                return OperatingSystem.Android;
            if (agent.Contains(OperatingSystem.Windows))
                return OperatingSystem.Windows;
            if (agent.Contains(OperatingSystem.Mac))
                return OperatingSystem.Mac;
            if (agent.Contains(OperatingSystem.iOS))
                return OperatingSystem.iOS;
            if (agent.Contains(OperatingSystem.Linux))
                return OperatingSystem.Linux;

            return OperatingSystem.Others;
        }

        private static Processor ParseProcessor(UserAgent agent)
        {
            if (agent.Contains(Processor.ARM))
                return Processor.ARM;
            if (agent.Contains(Processor.x86))
                return Processor.x86;
            if (agent.Contains(Processor.x64))
                return Processor.x64;

            return Processor.Others;
        }
    }
}

Add all operating system in the platform resolver


// Automatically generated by Opus v0.50
namespace CopyTest1
{
    class CopySingleFileTest : FileUtilities.CopyFile
    {
        public CopySingleFileTest()
        {
            this.SetRelativePath(this, "data", "testfile.txt");
            this.UpdateOptions += delegate(Opus.Core.IModule module, Opus.Core.Target target) {
                FileUtilities.ICopyFileOptions options = module.Options as FileUtilities.ICopyFileOptions;
                if (null != options)
                {
                    if (target.HasPlatform(Opus.Core.EPlatform.OSX))
                    {
                        options.DestinationDirectory = "/tmp";
                    }
                    else if (target.HasPlatform(Opus.Core.EPlatform.Unix))
                    {
                        options.DestinationDirectory = "/tmp";
                    }
                    else if (target.HasPlatform(Opus.Core.EPlatform.Windows))
                    {
                        options.DestinationDirectory = @"c:/temp";
                    }
                }
           };
        }
    }

    class CopyMultipleFileTest : FileUtilities.CopyFileCollection
    {
        public CopyMultipleFileTest()
        {
            this.Include(this, "data", "*");
        }
    }

    class CopyDirectoryTest : FileUtilities.CopyDirectory
    {
        public CopyDirectoryTest()
        {
            this.Include(this, "data");
        }
    }
}

// Automatically generated by Opus v0.50
namespace CopyTest1
{
    class CopySingleFileTest : FileUtilities.CopyFile
    {
        public CopySingleFileTest()
        {
            this.SetRelativePath(this, "data", "testfile.txt");
            this.UpdateOptions += delegate(Opus.Core.IModule module, Opus.Core.Target target) {
                FileUtilities.ICopyFileOptions options = module.Options as FileUtilities.ICopyFileOptions;
                if (null != options)
                {
                    options.DestinationDirectory = System.IO.Path.GetTempPath();
                }
           };
        }
    }

    class CopyMultipleFileTest : FileUtilities.CopyFileCollection
    {
        public CopyMultipleFileTest()
        {
            this.Include(this, "data", "*");
        }
    }

    class CopyDirectoryTest : FileUtilities.CopyDirectory
    {
        public CopyDirectoryTest()
        {
            this.Include(this, "data");
        }
    }
}

Simplify fetching the temporary path

[050copyfiles] Simplify fetching the temporary path


using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("EVE-O Preview")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EVE-O Preview")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")]
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]

[assembly: CLSCompliant(true)]

using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("EVE-O Preview")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EVE-O Preview")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]

[assembly: CLSCompliant(true)]

Set app version to 3.0.0

Set app version to 3.0.0


using System;
using Diskordia.Columbus.Bots.FareDeals;
using Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines;
using Diskordia.Columbus.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Diskordia.Columbus.Bots
{
	public static class BotsExtensions
	{
		public static IServiceCollection AddFareDealBots(this IServiceCollection services, IConfiguration configuration)
		{
			if(services == null)
			{
				throw new ArgumentNullException(nameof(services));
			}

			if (configuration == null)
			{
				throw new ArgumentNullException(nameof(configuration));
			}

			services.AddTransient<IFareDealScanService, SingaporeAirlinesFareDealService>();

			services.Configure<SingaporeAirlinesOptions>(configuration.GetSection("FareDealScan:SingaporeAirlines"));

			return services;
		}
	}
}

using System;
using Diskordia.Columbus.Bots.FareDeals;
using Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Diskordia.Columbus.Bots
{
	public static class BotsExtensions
	{
		public static IServiceCollection AddFareDealBots(this IServiceCollection services, IConfiguration configuration)
		{
			if(services == null)
			{
				throw new ArgumentNullException(nameof(services));
			}

			if (configuration == null)
			{
				throw new ArgumentNullException(nameof(configuration));
			}

			services.AddTransient<IFareDealScanService, SingaporeAirlinesFareDealService>();

			services.Configure<SingaporeAirlinesOptions>(configuration.GetSection("FareDealScan:SingaporeAirlines"));
			services.Configure<FareDealScanOptions>(configuration.GetSection("FareDealScan"));

			return services;
		}
	}
}

fix(SingaporeAirlinesBot): Fix the not registered fare deal options.


using System;
using System.Linq;

namespace FibCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var max = 50;
            Enumerable.Range(0, int.MaxValue)
                .Select(Fib)
                .TakeWhile(x => x <= max)
                .ToList()
                .ForEach(Console.WriteLine);
        }

        static int Fib(int arg) =>
            arg == 0 ? 0
            : arg == 1 ? 1
            : Fib(arg - 2) + Fib(arg - 1);
    }
}

using System;
using System.Linq;

namespace FibCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var max = 50;
            Enumerable.Range(0, int.MaxValue)
                .Select(Fib)
                .TakeWhile(x => x <= max)
                .ToList()
                .ForEach(Console.WriteLine);
        }

        static int Fib(int arg) =>
            arg < 0 ? throw new Exception("Argument must be >= 0")
            : arg == 0 ? 0
            : arg == 1 ? 1
            : Fib(arg - 2) + Fib(arg - 1);
    }
}

Throw Exception if arg < 0 using Throw Expression


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T4TS.Tests
{
    [TestClass]
    public class ModuleOutputAppenderTests
    {
        [TestMethod]
        public void ModuleOutputAppenderRespectsCompatibilityVersion()
        {
            var sb = new StringBuilder();
            var module = new TypeScriptModule
            {
                QualifiedName = "Foo"
            };

            var settings = new Settings();
            var appender = new ModuleOutputAppender(sb, 0, settings);

            settings.CompatibilityVersion = new Version(0, 8, 3);
            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("module"));
            sb.Clear();

            settings.CompatibilityVersion = new Version(0, 9, 0);
            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("declare module"));
            sb.Clear();

            settings.CompatibilityVersion = null;
            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("declare module"));
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T4TS.Tests
{
    [TestClass]
    public class ModuleOutputAppenderTests
    {
        [TestMethod]
        public void TypescriptVersion083YieldsModule()
        {
            var sb = new StringBuilder();
            var module = new TypeScriptModule
            {
                QualifiedName = "Foo"
            };

            var appender = new ModuleOutputAppender(sb, 0, new Settings
            {
                CompatibilityVersion = new Version(0, 8, 3)
            });

            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("module "));
        }

        [TestMethod]
        public void TypescriptVersion090YieldsDeclareModule()
        {
            var sb = new StringBuilder();
            var module = new TypeScriptModule
            {
                QualifiedName = "Foo"
            };

            var appender = new ModuleOutputAppender(sb, 0, new Settings
            {
                CompatibilityVersion = new Version(0, 9, 0)
            });

            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("declare module "));
        }

        [TestMethod]
        public void DefaultTypescriptVersionYieldsDeclareModule()
        {
            var sb = new StringBuilder();
            var module = new TypeScriptModule
            {
                QualifiedName = "Foo"
            };

            var appender = new ModuleOutputAppender(sb, 0, new Settings
            {
                CompatibilityVersion = null
            });

            appender.AppendOutput(module);
            Assert.IsTrue(sb.ToString().StartsWith("declare module "));
        }
    }
}

Split ModuleOutput tests to separate asserts


using UnityEngine;
using System.Reflection;

[assembly: AssemblyVersion("0.5.0.*")]
public class Loader : MonoBehaviour
{
    /// <summary>
    /// DebugUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _debugUI;

    /// <summary>
    /// ModalDialog prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _modalDialog;

    /// <summary>
    /// MainMenu prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _mainMenu;

    /// <summary>
    /// InGameUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _inGameUI;

    /// <summary>
    /// SoundManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _soundManager;

    /// <summary>
    /// GameManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _gameManager;

    protected void Awake()
    {
        // Check if the instances have already been assigned to static variables or they are still null.

        if (DebugUI.Instance == null)
        {
            Instantiate(_debugUI);
        }
        if (ModalDialog.Instance == null)
        {
            Instantiate(_modalDialog);
        }
        if (MainMenu.Instance == null)
        {
            Instantiate(_mainMenu);
        }
        if (InGameUI.Instance == null)
        {
            Instantiate(_inGameUI);
        }
        if (SoundManager.Instance == null)
        {
            Instantiate(_soundManager);
        }
        if (GameManager.Instance == null)
        {
            Instantiate(_gameManager);
        }
    }
}

using UnityEngine;
using System.Reflection;

[assembly: AssemblyVersion("0.5.1.*")]
public class Loader : MonoBehaviour
{
    /// <summary>
    /// DebugUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _debugUI;

    /// <summary>
    /// ModalDialog prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _modalDialog;

    /// <summary>
    /// MainMenu prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _mainMenu;

    /// <summary>
    /// InGameUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _inGameUI;

    /// <summary>
    /// SoundManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _soundManager;

    /// <summary>
    /// GameManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _gameManager;

    protected void Awake()
    {
        // Check if the instances have already been assigned to static variables or they are still null.

        if (DebugUI.Instance == null)
        {
            Instantiate(_debugUI);
        }
        if (ModalDialog.Instance == null)
        {
            Instantiate(_modalDialog);
        }
        if (MainMenu.Instance == null)
        {
            Instantiate(_mainMenu);
        }
        if (InGameUI.Instance == null)
        {
            Instantiate(_inGameUI);
        }
        if (SoundManager.Instance == null)
        {
            Instantiate(_soundManager);
        }
        if (GameManager.Instance == null)
        {
            Instantiate(_gameManager);
        }
    }
}

Change version up to 0.5.1

Change version up to 0.5.1


// 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 CoreGraphics;
using UIKit;

namespace osu.Framework.iOS
{
    internal class GameViewController : UIViewController
    {
        public override bool PrefersStatusBarHidden() => true;

        public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;

        public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
        {
            coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
            UIView.AnimationsEnabled = false;
            base.ViewWillTransitionToSize(toSize, coordinator);

            (View as IOSGameView)?.RequestResizeFrameBuffer();
        }
    }
}

// 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 CoreGraphics;
using UIKit;

namespace osu.Framework.iOS
{
    internal class GameViewController : UIViewController
    {
        public override bool PrefersStatusBarHidden() => true;

        public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();

            SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.ReleaseRetainedResources();
            GC.Collect();
        }

        public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
        {
            coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
            UIView.AnimationsEnabled = false;
            base.ViewWillTransitionToSize(toSize, coordinator);

            (View as IOSGameView)?.RequestResizeFrameBuffer();
        }
    }
}

Handle iOS memory alerts and free any memory we can


// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

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

namespace Nuke.Common.Execution
{
    internal class HandleHelpRequestsAttribute : BuildExtensionAttributeBase, IOnBuildInitialized
    {
        public void OnBuildInitialized(
            NukeBuild build,
            IReadOnlyCollection<ExecutableTarget> executableTargets,
            IReadOnlyCollection<ExecutableTarget> executionPlan)
        {
            if (build.Help || executionPlan.Count == 0)
            {
                Host.Information(HelpTextService.GetTargetsText(build.ExecutableTargets));
                Host.Information(HelpTextService.GetParametersText(build));
            }

            if (build.Plan)
                ExecutionPlanHtmlService.ShowPlan(build.ExecutableTargets);

            if (build.Help || executionPlan.Count == 0 || build.Plan)
                Environment.Exit(exitCode: 0);
        }
    }
}

// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

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

namespace Nuke.Common.Execution
{
    internal class HandleHelpRequestsAttribute : BuildExtensionAttributeBase, IOnBuildInitialized
    {
        public void OnBuildInitialized(
            NukeBuild build,
            IReadOnlyCollection<ExecutableTarget> executableTargets,
            IReadOnlyCollection<ExecutableTarget> executionPlan)
        {
            if (build.Help || executionPlan.Count == 0)
            {
                Host.Debug(HelpTextService.GetTargetsText(build.ExecutableTargets));
                Host.Debug(HelpTextService.GetParametersText(build));
            }

            if (build.Plan)
                ExecutionPlanHtmlService.ShowPlan(build.ExecutableTargets);

            if (build.Help || executionPlan.Count == 0 || build.Plan)
                Environment.Exit(exitCode: 0);
        }
    }
}

Fix help text to use Debug output

Fix help text to use Debug output


// 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.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;

namespace osu.Game.Scoring
{
    public class LegacyDatabasedScore : Score
    {
        public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
        {
            ScoreInfo = score;

            var replayFilename = score.Files.First(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase)).FileInfo.StoragePath;

            using (var stream = store.GetStream(replayFilename))
                Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
        }
    }
}

// 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.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;

namespace osu.Game.Scoring
{
    public class LegacyDatabasedScore : Score
    {
        public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
        {
            ScoreInfo = score;

            var replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.FileInfo.StoragePath;

            if (replayFilename == null)
                return;

            using (var stream = store.GetStream(replayFilename))
                Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
        }
    }
}

Allow legacy score to be constructed even if replay file is missing


using Nancy;
using Okanshi.Dashboard.Models;

namespace Okanshi.Dashboard
{
	public class DashboardModule : NancyModule
	{
		private readonly IGetHealthChecks _getHealthChecks;

		public DashboardModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks)
		{
			_getHealthChecks = getHealthChecks;
			Get["/"] = p => View["index.html", configuration.GetAll()];
			Get["/instances/{instanceName}"] = p =>
			{
				string instanceName = p.instanceName.ToString();
				var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = _getHealthChecks.Execute(instanceName) };
				return Response.AsJson(service);
			};
		}
	}
}

using Nancy;
using Okanshi.Dashboard.Models;

namespace Okanshi.Dashboard
{
	public class DashboardModule : NancyModule
	{
		private readonly IGetHealthChecks _getHealthChecks;

		public DashboardModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks)
		{
			_getHealthChecks = getHealthChecks;
			Get["/"] = p => View["index.html", configuration.GetAll()];
			Get["/instances/{instanceName}"] = p =>
			{
				string instanceName = p.instanceName.ToString();
				var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = _getHealthChecks.Execute(instanceName) };
				return Response.AsJson(service);
			};
			Get["/instances"] = _ => Response.AsJson(configuration.GetAll());
		}
	}
}

Add endpoint to get all instances

Add endpoint to get all instances


using System;
using System.Threading;

#if PORTABLE
using System.Threading.Tasks;
#endif

namespace Polly.Utilities
{
    /// <summary>
    /// Time related delegates used to improve testability of the code
    /// </summary>
    public static class SystemClock
    {
        /// <summary>
        /// Allows the setting of a custom Thread.Sleep implementation for testing.
        /// By default this will be a call to <see cref="Thread.Sleep(TimeSpan)"/>
        /// </summary>
#if !PORTABLE
        public static Action<TimeSpan> Sleep = Thread.Sleep;
#endif
#if PORTABLE
        public static Action<TimeSpan> Sleep = timespan => new ManualResetEvent(false).WaitOne(timespan);
#endif
        /// <summary>
        /// Allows the setting of a custom DateTime.UtcNow implementation for testing.
        /// By default this will be a call to <see cref="DateTime.UtcNow"/>
        /// </summary>
        public static Func<DateTime> UtcNow = () => DateTime.UtcNow;

        /// <summary>
        /// Resets the custom implementations to their defaults.
        /// Should be called during test teardowns.
        /// </summary>
        public static void Reset()
        {
#if !PORTABLE
        Sleep = Thread.Sleep;
#endif
#if PORTABLE
            Sleep = async span => await Task.Delay(span);
#endif
            UtcNow = () => DateTime.UtcNow;
        }
    }
}

using System;
using System.Threading;

namespace Polly.Utilities
{
    /// <summary>
    /// Time related delegates used to improve testability of the code
    /// </summary>
    public static class SystemClock
    {
#if !PORTABLE
        /// <summary>
        /// Allows the setting of a custom Thread.Sleep implementation for testing.
        /// By default this will be a call to <see cref="M:Thread.Sleep"/>
        /// </summary>
        public static Action<TimeSpan> Sleep = Thread.Sleep;
#endif
#if PORTABLE
        /// <summary>
        /// Allows the setting of a custom Thread.Sleep implementation for testing.
        /// By default this will be a call to <see cref="M:ManualResetEvent.WaitOne"/>
        /// </summary>
        public static Action<TimeSpan> Sleep = timespan => new ManualResetEvent(false).WaitOne(timespan);
#endif
        /// <summary>
        /// Allows the setting of a custom DateTime.UtcNow implementation for testing.
        /// By default this will be a call to <see cref="DateTime.UtcNow"/>
        /// </summary>
        public static Func<DateTime> UtcNow = () => DateTime.UtcNow;

        /// <summary>
        /// Resets the custom implementations to their defaults.
        /// Should be called during test teardowns.
        /// </summary>
        public static void Reset()
        {
#if !PORTABLE
        Sleep = Thread.Sleep;
#endif
#if PORTABLE
            Sleep = timeSpan => new ManualResetEvent(false).WaitOne(timeSpan);
#endif
            UtcNow = () => DateTime.UtcNow;
        }
    }
}

Fix PCL implementation of Reset

Fix PCL implementation of Reset


using System;
using System.Text;
using Microsoft.AspNetCore.Http;

namespace Hellang.Middleware.SpaFallback
{
    public class SpaFallbackException : Exception
    {
        private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback);

        private const string StaticFiles = "UseStaticFiles";

        private const string Mvc = "UseMvc";

        public SpaFallbackException(PathString path) : base(GetMessage(path))
        {
        }

        private static string GetMessage(PathString path) => new StringBuilder()
            .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.")
            .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.")
            .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.")
            .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.")
            .ToString();
    }
}

using System;
using System.Text;
using Microsoft.AspNetCore.Http;

namespace Hellang.Middleware.SpaFallback
{
    public class SpaFallbackException : Exception
    {
        private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback);

        private const string StaticFiles = "UseStaticFiles";

        private const string Mvc = "UseMvc";

        public SpaFallbackException(PathString path) : base(GetMessage(path))
        {
            Path = path;
        }

        public PathString Path { get; }

        private static string GetMessage(PathString path) => new StringBuilder()
            .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.")
            .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.")
            .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.")
            .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.")
            .ToString();
    }
}

Add Path property to exception

Add Path property to exception


@*
 * Copyright (c) gestaoaju.com.br - All rights reserved.
 * Licensed under MIT (https://github.com/gestaoaju/commerce/blob/master/LICENSE).
 *@

@{ Layout = "~/Views/Shared/_AppLayout.cshtml"; }

@section scripts
{

}

    Título da página

    Conteúdo da página Comercial

Remove forced height for testing

Remove forced height for testing


<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

        @RenderBody()

© @DateTime.Now.Year - Ivan Zlatev

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

Add google analytics tracking code.

Add google analytics tracking code.


using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Logos.Git")]
[assembly: AssemblyDescription("Utility code for working with local git repos and the GitHub web API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Logos Bible Software")]
[assembly: AssemblyProduct("Logos.Git")]
[assembly: AssemblyCopyright("Copyright 2013 Logos Bible Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.5.1")]
[assembly: AssemblyFileVersion("0.5.1")]
[assembly: AssemblyInformationalVersion("0.5.1")]

using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Logos.Git")]
[assembly: AssemblyDescription("Utility code for working with local git repos and the GitHub web API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Logos Bible Software")]
[assembly: AssemblyProduct("Logos.Git")]
[assembly: AssemblyCopyright("Copyright 2013-2014 Logos Bible Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.5.2")]
[assembly: AssemblyFileVersion("0.5.2")]
[assembly: AssemblyInformationalVersion("0.5.2")]

Update Logos.Git version (for new dependencies).


using System.Collections.Generic;
using System.Linq;
using Fake;
using Machine.Specifications;

namespace Test.FAKECore
{
    public class when_encapsuting_strings
    {
        It should_encapsulate_without_special_chars =
            () => TeamCityHelper.EncapsulateSpecialChars("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0")
                      .ShouldEqual("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0");
    }

    public class when_creating_buildstatus
    {
        It should_encapsulate_special_chars =
            () => TeamCityHelper.buildStatus("FAILURE", "Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0")
                      .ShouldEqual("##teamcity[buildStatus 'FAILURE' text='Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0']");
    }
}

using System.Collections.Generic;
using System.Linq;
using Fake;
using Machine.Specifications;

namespace Test.FAKECore
{
    public class when_encapsuting_strings
    {
        It should_encapsulate_without_special_chars =
            () => TeamCityHelper.EncapsulateSpecialChars("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0")
                      .ShouldEqual("Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0");
    }

    public class when_creating_buildstatus
    {
        It should_encapsulate_special_chars =
            () => TeamCityHelper.buildStatus("FAILURE", "Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0")
                      .ShouldEqual("##teamcity[buildStatus status='FAILURE' text='Total 47, Failures 1, NotRun 0, Inconclusive 0, Skipped 0']");
    }
}

Correct test for TeamCity status

Correct test for TeamCity status

The accepted content in the test would not be recognised by teamcity as a failure.


---
Title: Documentation
---

    We gladly accept your contributions. If there is something that you would like to add then you can edit the content directly on GitHub.

@foreach(IDocument child in Model.DocumentList(Keys.Children).OrderBy(x => x.Get<int>(DocsKeys.Order, 1000)))
{

@(child.String(Keys.Title))

    if(child.ContainsKey(DocsKeys.Description))
    {

@Html.Raw(child.String(DocsKeys.Description))

    }

    @Html.Partial("_ChildPages", child)
}

Format contribution info as annotation

Format contribution info as annotation


using System;
using System.Collections.Generic;
using UnityEngine;

namespace Bugsnag.Unity.Tests
{
  public class TestConfiguration : IConfiguration
  {
    public TimeSpan MaximumLogsTimePeriod { get; set; }

    public Dictionary<LogType, int> MaximumTypePerTimePeriod { get; set; }

    public TimeSpan UniqueLogsTimePeriod { get; set; }

    public string ApiKey { get; set; }

    public int MaximumBreadcrumbs { get; set; }

    public string ReleaseStage { get; set; }

    public string AppVersion { get; set; }

    public Uri Endpoint { get; set; }

    public string PayloadVersion { get; set; }

    public Uri SessionEndpoint { get; set; }

    public string SessionPayloadVersion { get; set; }

    public string Context { get; set; }

    public LogType NotifyLevel { get; set; }

    public bool AutoNotify { get; set; }
  }
}

using System;
using System.Collections.Generic;
using UnityEngine;

namespace Bugsnag.Unity.Tests
{
  public class TestConfiguration : IConfiguration
  {
    public TimeSpan MaximumLogsTimePeriod { get; set; } = TimeSpan.FromSeconds(1);

    public Dictionary<LogType, int> MaximumTypePerTimePeriod { get; set; }

    public TimeSpan UniqueLogsTimePeriod { get; set; } = TimeSpan.FromSeconds(5);

    public string ApiKey { get; set; }

    public int MaximumBreadcrumbs { get; set; }

    public string ReleaseStage { get; set; }

    public string AppVersion { get; set; }

    public Uri Endpoint { get; set; }

    public string PayloadVersion { get; set; }

    public Uri SessionEndpoint { get; set; }

    public string SessionPayloadVersion { get; set; }

    public string Context { get; set; }

    public LogType NotifyLevel { get; set; }

    public bool AutoNotify { get; set; }
  }
}

Add required defaults for tests

Add required defaults for tests


#region

using System;
using System.Drawing;
using Novacode;
using Tabster.Data;
using Tabster.Data.Processing;

#endregion

namespace WordDoc
{
    public class WordDocExporter : ITablatureFileExporter
    {
        public WordDocExporter()
        {
            FileType = new FileType("Microsoft Office Open XML Format File", ".docx");
        }

        #region Implementation of ITablatureFileExporter

        public FileType FileType { get; private set; }

        public Version Version
        {
            get { return new Version("1.0"); }
        }

        public void Export(ITablatureFile file, string fileName)
        {
            using (var document = DocX.Create(fileName))
            {
                var p = document.InsertParagraph();
                p.Append(file.Contents).Font(new FontFamily("Courier New")).FontSize(9);
                document.Save();
            }
        }

        #endregion
    }
}

#region

using System;
using System.Drawing;
using Novacode;
using Tabster.Data;
using Tabster.Data.Processing;

#endregion

namespace WordDoc
{
    public class WordDocExporter : ITablatureFileExporter
    {
        public WordDocExporter()
        {
            FileType = new FileType("Microsoft Office Open XML Format File", ".docx");
        }

        #region Implementation of ITablatureFileExporter

        public FileType FileType { get; private set; }

        public Version Version
        {
            get { return new Version("1.0"); }
        }

        public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args)
        {
            using (var document = DocX.Create(fileName))
            {
                var p = document.InsertParagraph();
                p.Append(file.Contents).Font(FontFamily.GenericMonospace).FontSize(9);
                document.Save();
            }
        }

        #endregion
    }
}

Use Generic monospace font family for DOCX


using System;
using CIV.Formats;
using static System.Console;

namespace CIV
{

	[Flags]
	enum ExitCodes : int
	{
		Success = 0,
		FileNotFound = 1,
        ParsingFailed = 2,
        VerificationFailed = 4
	}

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
				var project = new Caal().Load(args[0]);
                VerifyAll(project);
			}
            catch (System.IO.FileNotFoundException ex)
            {
                ForegroundColor = ConsoleColor.Red;
                WriteLine(ex.Message);
				ResetColor();
                Environment.Exit((int)ExitCodes.FileNotFound);
			}
		}

        static void VerifyAll(Caal project)
        {
			WriteLine("Loaded project {0}", project.Name);

			foreach (var kv in project.Formulae)
			{
				var isSatisfied = kv.Key.Check(kv.Value);
				var symbol = isSatisfied ? "|=" : "|/=";
				ForegroundColor = isSatisfied ? ConsoleColor.Green : ConsoleColor.Red;
				WriteLine($"{kv.Value} {symbol} {kv.Key}");
			}
			ResetColor();
        }
    }
}

using System;
using System.Diagnostics;
using CIV.Formats;
using static System.Console;

namespace CIV
{

	[Flags]
	enum ExitCodes : int
	{
		Success = 0,
		FileNotFound = 1,
        ParsingFailed = 2,
        VerificationFailed = 4
	}

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
				var project = new Caal().Load(args[0]);
                VerifyAll(project);
			}
            catch (System.IO.FileNotFoundException ex)
            {
                ForegroundColor = ConsoleColor.Red;
                WriteLine(ex.Message);
				ResetColor();
                Environment.Exit((int)ExitCodes.FileNotFound);
			}
		}

        static void VerifyAll(Caal project)
        {
			WriteLine("Loaded project {0}. Starting verification...", project.Name);

            var sw = new Stopwatch();
            sw.Start();
			foreach (var kv in project.Formulae)
			{
                Write($"{kv.Value} |= {kv.Key}...");
				Out.Flush();
				var isSatisfied = kv.Key.Check(kv.Value);
				ForegroundColor = isSatisfied ? ConsoleColor.Green : ConsoleColor.Red;
                var result = isSatisfied ? "Success!" : "Failure";
                Write($"\t{result}");
                WriteLine();
				ResetColor();
			}
            sw.Stop();
            WriteLine($"Completed in {sw.Elapsed.TotalMilliseconds} ms.");

        }
    }
}

Add time measurement in Main, fix output


using System;
using System.Collections.Generic;

namespace Graph
{
    /// <summary>
    /// Represents a graph.
    /// </summary>
    /// <typeparam name="V">The vertex type.</typeparam>
    /// <typeparam name="E">The edge type.</typeparam>
    public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V>
    {
        /// <summary>
        /// The graph's vertices.
        /// </summary>
        ISet<V> Vertices { get; }

        /// <summary>
        /// Attempts to add an edge to the graph.
        /// </summary>
        /// <param name="edge">
        /// The edge.
        /// </param>
        /// <param name="allowNewVertices">
        /// Iff true, add vertices in the edge which aren't yet in the graph
        /// to the graph's vertex set.
        /// </param>
        /// <returns>
        /// True if the edge was successfully added (the definition of
        /// "success" may vary from implementation to implementation).
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Thrown if the edge contains at least one edge not in the graph,
        /// and allowNewVertices is set to false.
        /// </exception>
        bool TryAddEdge(E edge, bool allowNewVertices = false);

        /// <summary>
        /// Attempts to remove an edge from the graph.
        /// </summary>
        /// <param name="edge">The edge.</param>
        /// <returns>
        /// True if the edge was successfully removed, false otherwise.
        /// </returns>
        bool TryRemoveEdge(E edge);
    }
}

using System;
using System.Collections.Generic;

namespace Graph
{
    /// <summary>
    /// Represents a graph.
    /// </summary>
    /// <typeparam name="V">The vertex type.</typeparam>
    /// <typeparam name="E">The edge type.</typeparam>
    public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V>
    {
        /// <summary>
        /// Attempts to add an edge to the graph.
        /// </summary>
        /// <param name="edge">
        /// The edge.
        /// </param>
        /// <param name="allowNewVertices">
        /// Iff true, add vertices in the edge which aren't yet in the graph
        /// to the graph's vertex set.
        /// </param>
        /// <returns>
        /// True if the edge was successfully added (the definition of
        /// "success" may vary from implementation to implementation).
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Thrown if the edge contains at least one edge not in the graph,
        /// and allowNewVertices is set to false.
        /// </exception>
        bool TryAddEdge(E edge, bool allowNewVertices = false);

        /// <summary>
        /// Attempts to remove an edge from the graph.
        /// </summary>
        /// <param name="edge">The edge.</param>
        /// <returns>
        /// True if the edge was successfully removed, false otherwise.
        /// </returns>
        bool TryRemoveEdge(E edge);
    }
}

Remove publicly exposed Vertices property


@using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@using System.Collections.Specialized
@model PackageSearchResultsModel

@{
var routeValues = RouteHelper.RouteFromParameters(Html.ViewContext);

// Remove the page number from the route values since we are doing client-side
// pagination in the table mode
RouteHelper.UpdateRoute(routeValues, "page", null);
}

    @if (Model.DisplayMode == ResultsDisplayMode.Table)
    {

        ListTable

    }
    else
    {
        ListTable
    }

@if (SettingsHelper.GetGoogleAnalyticsEnabled())
{

}

Add Google Analytics tracking for changing results mode


namespace Raccoon.Components {
    public class Alarm : Component {
        public Alarm(uint interval, System.Action action) {
            NextActivationTimer = Interval = interval;
            Action = action;
        }

        public System.Action Action { get; set; }
        public uint Timer { get; private set; }
        public uint NextActivationTimer { get; private set; }
        public uint Interval { get; set; }
        public uint RepeatTimes { get; set; } = uint.MaxValue;
        public uint RepeatCount { get; private set; }

        public override void Update(int delta) {
            Timer += (uint) delta;

            if (Timer < NextActivationTimer) {
                return;
            }

            Action();

            if (RepeatCount < RepeatTimes) {
                RepeatCount++;
                NextActivationTimer += Interval;
            }
        }

        public override void Render() {
        }

        public override void DebugRender() {
        }

        public void Reset() {
            RepeatCount = 0;
            Timer = 0;
            NextActivationTimer = Interval;
        }
    }
}

namespace Raccoon.Components {
    public class Alarm : Component {
        public Alarm(uint interval, System.Action action) {
            NextActivationTimer = Interval = interval;
            Action = action;
        }

        public System.Action Action { get; set; }
        public uint Timer { get; private set; }
        public uint NextActivationTimer { get; private set; }
        public uint Interval { get; set; }
        public uint RepeatTimes { get; set; } = uint.MaxValue;
        public uint TriggeredCount { get; private set; }

        public override void Update(int delta) {
            Timer += (uint) delta;

            if (TriggeredCount > RepeatTimes || Timer < NextActivationTimer) {
                return;
            }

            Action();
            TriggeredCount++;
            NextActivationTimer += Interval;
        }

        public override void Render() {
        }

        public override void DebugRender() {
        }

        public void Reset() {
            TriggeredCount = 0;
            Timer = 0;
            NextActivationTimer = Interval;
        }
    }
}

Fix to alarm not triggering correctly

Fix to alarm not triggering correctly


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

namespace SlackAPI
{
    [RequestPath("oauth.access")]
    public class AccessTokenResponse : Response
    {
        public string access_token;
        public string scope;
        public string team_name;
        public string team_id { get; set; }
        public BotTokenResponse bot;
        public IncomingWebhook incoming_webhook { get; set; }
    }

    public class BotTokenResponse
    {
       public string emoji;
       public string image_24;
       public string image_32;
       public string image_48;
       public string image_72;
       public string image_192;

       public bool deleted;
       public UserProfile icons;
       public string id;
       public string name;
       public string bot_user_id;
       public string bot_access_token;
    }

    public class IncomingWebhook
    {
        public string channel { get; set; }
        public string channel_id { get; set; }
        public string configuration_url { get; set; }
        public string url { get; set; }
    }
}

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

namespace SlackAPI
{
    [RequestPath("oauth.access")]
    public class AccessTokenResponse : Response
    {
        public string access_token;
        public string scope;
        public string team_name;
        public string team_id { get; set; }
        public BotTokenResponse bot;
    }

    public class BotTokenResponse
    {
       public string emoji;
       public string image_24;
       public string image_32;
       public string image_48;
       public string image_72;
       public string image_192;

       public bool deleted;
       public UserProfile icons;
       public string id;
       public string name;
       public string bot_user_id;
       public string bot_access_token;
    }
}

Revert "Added incoming_webhook to Access Token Response"

This reverts commit c7606ad7fc541bab1eff431628e5b58fbac7181c.


using System;
using Mastodot.Entities;
using Mastodot.Exceptions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mastodot.Utils.JsonConverters
{
    internal class ErrorThrowJsonConverter<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType.Name.StartsWith("IEnumerable"))
            {
                JArray jArray = JArray.Load(reader);
                return jArray.ToObject<T>();
            }

            JObject jObject = JObject.Load(reader);
            if (jObject["error"] != null)
            {
                Error error = jObject.ToObject<Error>();
                var exception = new DeserializeErrorException($"Cant deserialize response, Type {objectType}")
                {
                    Error = error
                };
                throw exception;
            }

            return jObject.ToObject<T>();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }
    }
}

using System;
using Mastodot.Entities;
using Mastodot.Exceptions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mastodot.Utils.JsonConverters
{
    internal class ErrorThrowJsonConverter<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType.Name.StartsWith("IEnumerable"))
            {
                JArray jArray = JArray.Load(reader);
                return jArray.ToObject<T>();
            }

            JObject jObject = JObject.Load(reader);
            if (jObject["error"] != null)
            {
                Error error = jObject.ToObject<Error>();
                error.RawJson = jObject.ToString();
                var exception = new DeserializeErrorException($"Cant deserialize response, Type {objectType}")
                {
                    Error = error
                };
                throw exception;
            }

            return jObject.ToObject<T>();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }
    }
}

Fix Error entity not contain RawJson

Fix Error entity not contain RawJson


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

using System.Collections.Generic;
using System.Linq;
using Microsoft.Xunit.Performance;
using Xunit;

namespace SimplePerfTests
{
    public class Document
    {
        private string _text;

        public Document(string text)
        {
            _text = text;
        }

        public void Format()
        {
            _text = _text.ToUpper();
        }

        public override string ToString()
        {
            return _text;
        }
    }

    public class FormattingTests
    {
        private static IEnumerable<object[]> MakeArgs(params object[] args)
        {
            return args.Select(arg => new object[] { arg });
        }

        public static IEnumerable<object[]> FormatCurlyBracesMemberData = MakeArgs(
            new Document("Hello, world!")
        );

        [Benchmark]
        [MemberData(nameof(FormatCurlyBracesMemberData))]
        public static void FormatCurlyBracesTest(Document document)
        {
            Benchmark.Iterate(document.Format);
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Xunit.Performance;
using Xunit;

namespace SimplePerfTests
{
    public class Document
    {
        private string _text;

        public Document(string text)
        {
            _text = text;
        }

        public void Format()
        {
            _text = _text.ToUpper();
        }

        public Task FormatAsync()
        {
            Format();
            return Task.CompletedTask;
        }

        public override string ToString()
        {
            return _text;
        }
    }

    public class FormattingTests
    {
        private static IEnumerable<object[]> MakeArgs(params object[] args)
        {
            return args.Select(arg => new object[] { arg });
        }

        public static IEnumerable<object[]> FormatCurlyBracesMemberData = MakeArgs(
            new Document("Hello, world!")
        );

        [Benchmark]
        [MemberData(nameof(FormatCurlyBracesMemberData))]
        public static void FormatCurlyBracesTest(Document document)
        {
            Benchmark.Iterate(document.Format);
        }

        [Benchmark]
        [MemberData(nameof(FormatCurlyBracesMemberData))]
        public static async Task FormatCurlyBracesTestAsync(Document document)
        {
            await Benchmark.IterateAsync(() => document.FormatAsync());
        }
    }
}

Add a test for IterateAsync

Add a test for IterateAsync


// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;

namespace osu.Game.Tests.Visual.Settings
{
    [TestFixture]
    public class TestSceneSettingsPanel : OsuTestScene
    {
        private readonly SettingsPanel settings;
        private readonly DialogOverlay dialogOverlay;

        public TestSceneSettingsPanel()
        {
            settings = new SettingsOverlay
            {
                State = { Value = Visibility.Visible }
            };
            Add(dialogOverlay = new DialogOverlay
            {
                Depth = -1
            });
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Dependencies.Cache(dialogOverlay);

            Add(settings);
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Overlays;

namespace osu.Game.Tests.Visual.Settings
{
    [TestFixture]
    public class TestSceneSettingsPanel : OsuTestScene
    {
        private SettingsPanel settings;
        private DialogOverlay dialogOverlay;

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("create settings", () =>
            {
                settings?.Expire();

                Add(settings = new SettingsOverlay
                {
                    State = { Value = Visibility.Visible }
                });
            });
        }

        [Test]
        public void ToggleVisibility()
        {
            AddWaitStep("wait some", 5);
            AddToggleStep("toggle editor visibility", visible => settings.ToggleVisibility());
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Add(dialogOverlay = new DialogOverlay
            {
                Depth = -1
            });

            Dependencies.Cache(dialogOverlay);
        }
    }
}

Add better test coverage of `SettingsPanel`


using System;

namespace Glimpse.Agent.Web
{
    public class IIgnoredRequestPolicy
    {

    }
}

using System;

namespace Glimpse.Agent.Web
{
    public interface IIgnoredRequestPolicy
    {
        bool ShouldIgnore(IContext context);
    }
}

Update interface for ignored request policy


using LibPixelPet;
using System;

namespace PixelPet.CLI.Commands {
	internal class ClearTilesetCmd : CliCommand {
		public ClearTilesetCmd()
			: base("Clear-Tileset") { }

		public override void Run(Workbench workbench, ILogger logger) {
			int w = 8;
			int h = 8;

			workbench.Tileset = new Tileset(w, h);

			logger?.Log("Created new " + w + 'x' + h + " tileset.");
		}
	}
}

using LibPixelPet;
using System;

namespace PixelPet.CLI.Commands {
	internal class ClearTilesetCmd : CliCommand {
		public ClearTilesetCmd()
			: base("Clear-Tileset",
				new Parameter("tile-size", "s", false, new ParameterValue("width", "8"), new ParameterValue("height", "8"))
			) { }

		public override void Run(Workbench workbench, ILogger logger) {
			int tw = FindNamedParameter("--tile-size").Values[0].ToInt32();
			int th = FindNamedParameter("--tile-size").Values[1].ToInt32();

			workbench.Tileset = new Tileset(tw, th);

			logger?.Log("Created new " + tw + 'x' + th + " tileset.");
		}
	}
}

Allow tile size to be changed from 8x8 using Clear-Tileset --tile-size.


using System;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Winterdom.BizTalk.PipelineTesting;

namespace BizTalkComponents.Utils.Tests.UnitTests
{
    [TestClass]
    public class ContextExtensionTests
    {
        private IBaseMessage _testMessage;

        [TestInitialize]
        public void InitializeTest()
        {
            _testMessage = MessageHelper.Create("<test></test>");
            _testMessage.Context.Promote(new ContextProperty("http://testuri.org#SourceProperty"), "Value");
        }

        [TestMethod]
        public void TryReadValidTest()
        {
            object val;

            Assert.IsTrue(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#SourceProperty"), out val));
            Assert.AreEqual("Value", val.ToString());
        }

        [TestMethod]
        public void TryReadInValidTest()
        {
            object val;

            Assert.IsFalse(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#NonExisting"), out val));
        }
    }
}

using System;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Winterdom.BizTalk.PipelineTesting;

namespace BizTalkComponents.Utils.Tests.UnitTests
{
    [TestClass]
    public class ContextExtensionTests
    {
        private IBaseMessage _testMessage;

        [TestInitialize]
        public void InitializeTest()
        {
            _testMessage = MessageHelper.Create("<test></test>");
            _testMessage.Context.Promote(new ContextProperty("http://testuri.org#SourceProperty"), "Value");
        }

        [TestMethod]
        public void TryReadValidTest()
        {
            object val;

            Assert.IsTrue(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#SourceProperty"), out val));
            Assert.AreEqual("Value", val.ToString());
        }

        [TestMethod]
        public void TryReadInValidTest()
        {
            object val;

            Assert.IsFalse(_testMessage.Context.TryRead(new ContextProperty("http://testuri.org#NonExisting"), out val));
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TryReadInValidArgumentTest()
        {
            object val;

            _testMessage.Context.TryRead(null, out val);
        }
    }
}

Test case for calling try read with null values


// <copyright file="TJException.cs" company="Autonomic Systems, Quamotion">
// Copyright (c) Autonomic Systems. All rights reserved.
// Copyright (c) Quamotion. All rights reserved.
// </copyright>

using System;

namespace TurboJpegWrapper
{
    // ReSharper disable once InconsistentNaming

    /// <summary>
    /// Exception thrown then internal error in the underlying turbo jpeg library is occured.
    /// </summary>
    public class TJException : Exception
    {
        /// <summary>
        /// Creates new instance of the <see cref="TJException"/> class.
        /// </summary>
        /// <param name="error">Error message from underlying turbo jpeg library.</param>
        public TJException(string error) : base(error)
        {
        }
    }
}

SA1128: Put constructor initializers on their own line