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

namespace elbgb_core
{
    public abstract class ClockedComponent
    {
        protected GameBoy _gb;
        protected ulong _lastUpdate;

        public ClockedComponent(GameBoy gameBoy)
        {
            _gb = gameBoy;
        }

        public void SynchroniseWithSystemClock()
        {
            // if we're up to date with the current timestamp there
            // is nothing for us to do
            if (_lastUpdate == _gb.Clock.Timestamp)
            {
                return;
            }

            ulong timestamp = _gb.Clock.Timestamp;
            uint cyclesToUpdate = (uint)(timestamp - _lastUpdate);
            _lastUpdate = timestamp;

            Update(cyclesToUpdate);
        }

        // Run this component for the required number of cycles
        public abstract void Update(uint cycleCount);
    }
}

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

namespace elbgb_core
{
    public abstract class ClockedComponent
    {
        protected GameBoy _gb;
        private SystemClock _clock;
        protected ulong _lastUpdate;

        public ClockedComponent(GameBoy gameBoy)
        {
            _gb = gameBoy;
            _clock = gameBoy.Clock;
        }

        public void SynchroniseWithSystemClock()
        {
            ulong timestamp = _clock.Timestamp;
            uint cyclesToUpdate = (uint)(timestamp - _lastUpdate);
            _lastUpdate = timestamp;

            Update(cyclesToUpdate);
        }

        // Run this component for the required number of cycles
        public abstract void Update(uint cycleCount);
    }
}

Remove unnecessary cycle check from SynchroniseWithSystemClock

The update check was causing more overhead than it saved given the usage pattern of the method


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Edument.CQRS.EntityFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dynamic Generation Inc.")]
[assembly: AssemblyProduct("Edument.CQRS.EntityFramework")]
[assembly: AssemblyCopyright("Copyright © Dynamic Generation Inc. 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("285a28c4-4564-4bb9-8cc2-afce371074a0")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Edument.CQRS.EntityFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dynamic Generation Inc.")]
[assembly: AssemblyProduct("Edument.CQRS.EntityFramework")]
[assembly: AssemblyCopyright("Copyright © Dynamic Generation Inc. 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("285a28c4-4564-4bb9-8cc2-afce371074a0")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]

Fix version number in assembly

Fix version number in assembly


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts
{
    public string FirstName => "Matt";
    public string LastName => "Bobke";
    public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation.";
    public string StateOrRegion => "California, United States";
    public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa";
    public string EmailAddress => "matt@mattbobke.com";
    public string TwitterHandle => "MattBobke";
    public string GitHubHandle => "mcbobke";
    public GeoPosition Position => new GeoPosition(33.5676842, -117.7256083);
    public Uri WebSite => new Uri("https://mattbobke.com");
    public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://mattbobke.com/feed"); } }
    public bool Filter(SyndicationItem item)
    {
        // This filters out only the posts that have the "PowerShell" category
        return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
    }
    public string FeedLanguageCode => "en";
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts
{
    public string FirstName => "Matt";
    public string LastName => "Bobke";
    public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation.";
    public string StateOrRegion => "California, United States";
    public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa";
    public string EmailAddress => "matt@mattbobke.com";
    public string TwitterHandle => "MattBobke";
    public string GitHubHandle => "mcbobke";
    public GeoPosition Position => new GeoPosition(33.5676842, -117.7256083);
    public Uri WebSite => new Uri("https://mattbobke.com");
    public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://mattbobke.com/feed"); } }
    public bool Filter(SyndicationItem item)
    {
        // This filters out only the posts that have the "PowerShell" category
        return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
    }
    public string FeedLanguageCode => "en";
}

}

Fix Matt in name space

Fix Matt in name space


@model SFA.DAS.EmployerUsers.Web.Models.ChangeEmailViewModel

@{
    ViewBag.PageID = "page-change-email-address";
    ViewBag.Title = "Change your email address";
}

@if (!Model.Valid)
{

 Errors to fix

Check the following details:

}

 Change your email address

<form method="post">
    @Html.AntiForgeryToken()

    <fieldset>
        <legend class="visuallyhidden">New email address</legend>

            New email address
            <input autofocus="autofocus" aria-required="true" class="form-control" id="NewEmailAddress" name="NewEmailAddress">

            Re-type email addresss
            <input aria-required="true" class="form-control" id="ConfirmEmailAddress" name="ConfirmEmailAddress">

    </fieldset>
    <button type="submit" class="button">Continue</button>
</form>

Add model to change email view

Add model to change email view

Model has been added to the change email view.


// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Linq;
using Microsoft.TestCommon;

namespace System.Web.Http.OData.Formatter
{
    internal static class JsonAssert
    {
        public static void Equal(string expected, string actual)
        {
            // Due to a problem with one build system, don't assume source files use Environment.NewLine (they may just
            // use \n instead). Normalize the expected result to use Environment.NewLine.
            expected = expected.Replace(Environment.NewLine, "\n").Replace("\n", Environment.NewLine);

            // For now, simply compare the exact strings. Note that this approach requires whitespace to match exactly
            // (except for line endings).
            Assert.Equal(expected, actual);
        }
    }
}

// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using Microsoft.TestCommon;
using Newtonsoft.Json.Linq;

namespace System.Web.Http.OData.Formatter
{
    internal static class JsonAssert
    {
        public static void Equal(string expected, string actual)
        {
            Assert.Equal(JToken.Parse(expected), JToken.Parse(actual), JToken.EqualityComparer);
        }
    }
}

Fix some flaky OData JSON tests using string comparison

Fixing by using JToken.EqualityComparer.


using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.JsonNew.Psi;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;

namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon
{
    public abstract class AsmDefProblemAnalyzer<T> : ElementProblemAnalyzer<T>
        where T : ITreeNode
    {
        protected override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            // Run for visible documents and SWEA. Also run for "other", which is used by scoped quick fixes
            if (data.GetDaemonProcessKind() == DaemonProcessKind.GLOBAL_WARNINGS)
                return;

            if (data.SourceFile == null || !element.Language.Is<JsonNewLanguage>() || !data.SourceFile.IsAsmDef())
                return;

            if (!element.GetProject().IsUnityProject())
                return;

            Analyze(element, data, consumer);
        }

        protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer);
    }
}

using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.JsonNew.Psi;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;

namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon
{
    public abstract class AsmDefProblemAnalyzer<T> : ElementProblemAnalyzer<T>
        where T : ITreeNode
    {
        protected override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            // Run for visible documents and SWEA. Also run for "other", which is used by scoped quick fixes
            if (data.GetDaemonProcessKind() == DaemonProcessKind.GLOBAL_WARNINGS)
                return;

            if (data.SourceFile == null || !element.Language.Is<JsonNewLanguage>() || !data.SourceFile.IsAsmDef())
                return;

            if (!element.GetSolution().HasUnityReference())
                return;

            Analyze(element, data, consumer);
        }

        protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer);
    }
}

Fix asmdef analysers working on external files


using JetBrains.DocumentModel;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.Tree;
using ReSharperExtensionsShared.Highlighting;
using Roflcopter.Plugin.MismatchedFileNames;

[assembly: RegisterConfigurableSeverity(
    MismatchedFileNameHighlighting.SeverityId,
    CompoundItemName: null,
    Group: HighlightingGroupIds.CodeSmell,
    Title: MismatchedFileNameHighlighting.Title,
    Description: MismatchedFileNameHighlighting.Description,
    DefaultSeverity: Severity.WARNING)]

namespace Roflcopter.Plugin.MismatchedFileNames
{
    /// <summary>
    /// Xml Doc highlighting for types / type members with specific accessibility.
    /// </summary>
    [ConfigurableSeverityHighlighting(
        SeverityId,
        CSharpLanguage.Name,
        OverlapResolve = OverlapResolveKind.NONE,
        ToolTipFormatString = Message)]
        public class MismatchedFileNameHighlighting : SimpleTreeNodeHighlightingBase<ITypeDeclaration>
    {
        public const string SeverityId = "MismatchedFileName";
        public const string Title = "Mismatch between type and file name";
        private const string Message = "Type doesn't match file name '{0}'";

        public const string Description = Title;

        public MismatchedFileNameHighlighting(ITypeDeclaration declaration, string fileName)
            : base(declaration, string.Format(Message, fileName))
        {
        }

        public override DocumentRange CalculateRange()
        {
            return TreeNode.GetNameDocumentRange();
        }
    }
}

using JetBrains.DocumentModel;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.Tree;
using ReSharperExtensionsShared.Highlighting;
using Roflcopter.Plugin.MismatchedFileNames;

[assembly: RegisterConfigurableSeverity(
    MismatchedFileNameHighlighting.SeverityId,
    CompoundItemName: null,
    Group: HighlightingGroupIds.CodeSmell,
    Title: MismatchedFileNameHighlighting.Title,
    Description: MismatchedFileNameHighlighting.Description,
    DefaultSeverity: Severity.WARNING)]

namespace Roflcopter.Plugin.MismatchedFileNames
{
    [ConfigurableSeverityHighlighting(
        SeverityId,
        CSharpLanguage.Name,
        OverlapResolve = OverlapResolveKind.NONE,
        ToolTipFormatString = Message)]
    public class MismatchedFileNameHighlighting : SimpleTreeNodeHighlightingBase<ITypeDeclaration>
    {
        public const string SeverityId = "MismatchedFileName";
        public const string Title = "Mismatch between type and file name";
        private const string Message = "Type doesn't match file name '{0}'";

        public const string Description = Title;

        public MismatchedFileNameHighlighting(ITypeDeclaration declaration, string fileName)
            : base(declaration, string.Format(Message, fileName))
        {
        }

        public override DocumentRange CalculateRange()
        {
            return TreeNode.GetNameDocumentRange();
        }
    }
}

Format code and remove wrong doc comment


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;

namespace CompetitionPlatform.Data.ProjectCategory
{
    public class ProjectCategoriesRepository : IProjectCategoriesRepository
    {
        public List<string> GetCategories()
        {
            return new List<string>
            {
                "Blockchain",
                "Development",
                "Design",
                "Testing",
                "Finance",
                "Technology",
                "Bitcoin",
                "Communications and media",
                "Research"
            };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;

namespace CompetitionPlatform.Data.ProjectCategory
{
    public class ProjectCategoriesRepository : IProjectCategoriesRepository
    {
        public List<string> GetCategories()
        {
            return new List<string>
            {
                "Blockchain",
                "Software Development",
                "Design",
                "Testing",
                "Finance",
                "Technology",
                "Bitcoin",
                "Communications and media",
                "Research"
            };
        }
    }
}

Rename Development category to Software Development.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace MetroRadiance.Interop.Win32
{
	public static class Dwmapi
	{
		[DllImport("Dwmapi.dll", ExactSpelling = true)]
		public static extern void DwmGetColorizationColor([Out] out uint pcrColorization, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfOpaqueBlend);

		[DllImport("Dwmapi.dll")]
		public static extern void DwmGetWindowAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE dwAttribute, [Out] out RECT pvAttribute, int cbAttribute);

	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace MetroRadiance.Interop.Win32
{
	public static class Dwmapi
	{
		[DllImport("Dwmapi.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void DwmGetColorizationColor([Out] out uint pcrColorization, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfOpaqueBlend);

		[DllImport("Dwmapi.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void DwmGetWindowAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE dwAttribute, [Out] out RECT pvAttribute, int cbAttribute);

	}
}

Fix issue that HRESULT returned by DWMAPI isn't converted.


using System;
using System.Collections;
using UnityEngine;

//using DG.Tweening;

public class EditorCoroutineTween
{
	/*
	public static EditorCoroutine Run(Tween t)
	{
		EditorCoroutineTween ct = new EditorCoroutineTween();

		return EditorCoroutine.Start(ct.UpdateTween(t));
	}

	IEnumerator UpdateTween(Tween t)
	{
		#if UNITY_EDITOR
		float time = Time.realtimeSinceStartup;
		while (!t.IsComplete())
		{
			t.fullPosition = Time.realtimeSinceStartup - time;
			yield return 0;
		}
		#else
		yield return null;
		#endif
	}
	*/
}

#if !NO_DOTWEEN

using System;
using System.Collections;
using UnityEngine;
using DG.Tweening;

public class EditorCoroutineTween
{
	public static EditorCoroutine Run(Tween t)
	{
		EditorCoroutineTween ct = new EditorCoroutineTween();

		return EditorCoroutine.Start(ct.UpdateTween(t));
	}

	IEnumerator UpdateTween(Tween t)
	{
		#if UNITY_EDITOR
		float time = Time.realtimeSinceStartup;
		while (!t.IsComplete())
		{
			t.fullPosition = Time.realtimeSinceStartup - time;
			yield return 0;
		}
		#else
		yield return null;
		#endif
	}
}

#endif

Disable with compiler constant instead.

Disable with compiler constant instead.


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

namespace NHibernate.Caches.Redis.Tests
{
    public class PerformanceTests : IntegrationTestBase
    {
        [Fact]
        async Task concurrent_reads_and_writes()
        {
            DisableLogging();

            const int iterations = 1000;
            var sessionFactory = CreateSessionFactory();

            var tasks = Enumerable.Range(0, iterations).Select(i =>
            {
                return Task.Run(() =>
                {
                    object entityId = null;
                    UsingSession(sessionFactory, session =>
                    {
                        var entity = new Person("Foo", 1);
                        entityId = session.Save(entity);
                        session.Flush();
                        session.Clear();

                        entity = session.Load<Person>(entityId);
                        entity.Name = Guid.NewGuid().ToString();
                        session.Flush();
                    });
                });
            });

            await Task.WhenAll(tasks);
        }
    }
}

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

namespace NHibernate.Caches.Redis.Tests
{
    public class PerformanceTests : IntegrationTestBase
    {
        [Fact]
        async Task concurrent_sessions_with_reads_and_writes()
        {
            DisableLogging();

            const int iterations = 1000;
            var sessionFactory = CreateSessionFactory();

            var tasks = Enumerable.Range(0, iterations).Select(i =>
            {
                return Task.Run(() =>
                {
                    object entityId = null;
                    UsingSession(sessionFactory, session =>
                    {
                        var entity = new Person("Foo", 1);
                        entityId = session.Save(entity);
                        session.Flush();
                        session.Clear();

                        entity = session.Load<Person>(entityId);
                        entity.Name = Guid.NewGuid().ToString();
                        session.Flush();
                    });
                });
            });

            await Task.WhenAll(tasks);
        }

        [Fact]
        async Task concurrent_session_factories_with_reads_and_writes()
        {
            DisableLogging();

            const int sessionFactoryCount = 5;
            const int iterations = 1000;

            // Create factories on the same thread so we don't run into
            // concurrency issues with NHibernate.
            var sessionFactories = Enumerable.Range(0, sessionFactoryCount).Select(i =>
            {
                return CreateSessionFactory();
            });

            var tasks = sessionFactories.Select(sessionFactory =>
            {
                return Task.Run(() =>
                {
                    for (int i = 0; i < iterations; i++)
                    {
                        object entityId = null;
                        UsingSession(sessionFactory, session =>
                        {
                            var entity = new Person("Foo", 1);
                            entityId = session.Save(entity);
                            session.Flush();
                            session.Clear();

                            entity = session.Load<Person>(entityId);
                            entity.Name = Guid.NewGuid().ToString();
                            session.Flush();
                        });
                    }
                });
            });

            await Task.WhenAll(tasks);
        }
    }
}

Add test for concurrent session factories.


using Newtonsoft.Json;

namespace TMDbLib.Objects.General
{
    public class TranslationData
    {
        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("overview")]
        public string Overview { get; set; }

        [JsonProperty("homepage")]
        public string HomePage { get; set; }

        [JsonProperty("tagline")]
        public string Tagline { get; set; }

        [JsonProperty("runtime")]
        public int Runtime { get; set; }
    }
}

using Newtonsoft.Json;

namespace TMDbLib.Objects.General
{
    public class TranslationData
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        // Private hack to ensure two properties (name, title) are deserialized into Name.
        // Tv Shows and Movies will use different names for their translation data.
        [JsonProperty("title")]
        private string Title
        {
            set => Name = value;
        }

        [JsonProperty("overview")]
        public string Overview { get; set; }

        [JsonProperty("homepage")]
        public string HomePage { get; set; }

        [JsonProperty("tagline")]
        public string Tagline { get; set; }

        [JsonProperty("runtime")]
        public int Runtime { get; set; }
    }
}

Use Name and title interchangeably.

Use Name and title interchangeably.


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

namespace Booma.Proxy
{
	/// <summary>
	/// The collection of network players that are known about.
	/// </summary>
	public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
	{
		/// <summary>
		/// The networked players.
		/// </summary>
		IEnumerable<INetworkPlayer> Players { get; }

		/// <summary>
		/// Returns the <see cref="INetworkPlayer"/> with the id.
		/// Or null if the player doesn't exist.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
		INetworkPlayer this[int id] { get; }

		/// <summary>
		/// Indicates if it contains the <see cref="id"/> key value.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>True if the collection contains the ID.</returns>
		bool ContainsId(int id);
	}
}

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

namespace Booma.Proxy
{
	/// <summary>
	/// The collection of network players that are known about.
	/// </summary>
	public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
	{
		/// <summary>
		/// The local player.
		/// </summary>
		INetworkPlayer Local { get; }

		/// <summary>
		/// The networked players.
		/// </summary>
		IEnumerable<INetworkPlayer> Players { get; }

		/// <summary>
		/// The networked player's excluding the <see cref="Local"/> player.
		/// </summary>
		IEnumerable<INetworkPlayer> ExcludingLocal { get; }

		/// <summary>
		/// Returns the <see cref="INetworkPlayer"/> with the id.
		/// Or null if the player doesn't exist.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
		INetworkPlayer this[int id] { get; }

		/// <summary>
		/// Indicates if it contains the <see cref="id"/> key value.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>True if the collection contains the ID.</returns>
		bool ContainsId(int id);
	}
}

Revert "Remove uneeded player collection methods"

This reverts commit a94975b6e6925a52f67731f3dd134ff14760d230.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataAccessExamples.Core.Services;
using DataAccessExamples.Core.ViewModels;
using Nancy.TinyIoc;

namespace DataAccessExamples.Web
{
    using Nancy;

    public class Bootstrapper : DefaultNancyBootstrapper
    {
        // The bootstrapper enables you to reconfigure the composition of the framework,
        // by overriding the various methods and properties.
        // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            container.Register(ResolveImplementation<IDepartmentService>(container, context));
        }

        private T ResolveImplementation<T>(TinyIoCContainer container, NancyContext context) where T : class
        {
            var implementations = container.ResolveAll<T>();
            var implementationName = (string) context.Request.Query["Impl"];
            if (!String.IsNullOrWhiteSpace(implementationName))
            {
                return implementations.Distinct().FirstOrDefault(i => i.GetType().Name.StartsWith(implementationName));
            }
            return implementations.FirstOrDefault();
        }
    }
}

using System;
using System.Linq;
using DataAccessExamples.Core.Services;
using Nancy.Bootstrapper;
using Nancy.Responses;
using Nancy.TinyIoc;

namespace DataAccessExamples.Web
{
    using Nancy;

    public class Bootstrapper : DefaultNancyBootstrapper
    {
        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);
            container.Register(ResolveImplementation<IDepartmentService>(container, context));
        }

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            pipelines.BeforeRequest += context =>
            {
                var implementationName = (string) context.Request.Query["Impl"];
                if (!String.IsNullOrWhiteSpace(implementationName))
                {
                    var response = new RedirectResponse(context.Request.Path);
                    response.AddCookie("Impl", implementationName);
                    return response;
                }
                return null;
            };
        }

        private T ResolveImplementation<T>(TinyIoCContainer container, NancyContext context) where T : class
        {
            var implementations = container.ResolveAll<T>();
            if (context.Request.Cookies.ContainsKey("Impl"))
            {
                return implementations.FirstOrDefault(i => i.GetType().Name.StartsWith(context.Request.Cookies["Impl"]));
            }
            return implementations.FirstOrDefault();
        }
    }
}

Store selected implementation in cookie

Store selected implementation in cookie


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

public class GameManager : MonoBehaviour
{

    void Start ()
    {

	}

	void Update ()
    {

	}
}

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

public class GameManager : MonoBehaviour
{

    void Start ()
    {
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }

	void Update ()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            Application.Quit();
        }
	}
}

Hide cursor and quit with escape.

Hide cursor and quit with escape.


namespace Our.Umbraco.Nexu.Core.Services
{
    /// <summary>
    /// Represents nexu entity relation service.
    /// </summary>
    public class NexuEntityRelationService
    {
    }
}

namespace Our.Umbraco.Nexu.Core.Services
{
    using Our.Umbraco.Nexu.Common.Interfaces.Services;

    /// <summary>
    /// Represents nexu entity relation service.
    /// </summary>
    public class NexuEntityRelationService : IEntityRelationService
    {
    }
}

Implement interface in concrete class

Implement interface in concrete class


using Lbookshelf.Models;
using Lbookshelf.Utils;
using Lbookshelf.ViewModels;
using Ldata;
using Ldata.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Lbookshelf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static JsonDataStore _dataStore;
        public static IDataStore DataStore
        {
            get
            {
                if (_dataStore == null)
                {
                    _dataStore = new JsonDataStore("db");
                    //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.Books);
                    //_dataStore.RegisterPartitionSelector<string>(obj => DataCollectionNames.RecentKeywords);
                    _dataStore.RegisterPartitionSelector<SortedObservableGroup<string, Book>>(DataCollectionNames.Booklists, obj => obj.Key);
                    //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.RecentlyAdded);
                    //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.RecentlyOpened);
                    //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.Pinned);
                }

                return _dataStore;
            }
        }

        private static BrowseBooksViewModel _browseBooksViewModel;
        public static BrowseBooksViewModel BrowseBooksViewModel
        {
            get
            {
                if (_browseBooksViewModel == null)
                {
                    _browseBooksViewModel = new BrowseBooksViewModel();
                }

                return _browseBooksViewModel;
            }
        }

        private static HomeViewModel _homeViewModel;
        public static HomeViewModel HomeViewModel
        {
            get
            {
                if (_homeViewModel == null)
                {
                    _homeViewModel = new HomeViewModel();
                }

                return _homeViewModel;
            }
        }
    }
}

using Lbookshelf.Models;
using Lbookshelf.Utils;
using Lbookshelf.ViewModels;
using Ldata;
using Ldata.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Lbookshelf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static JsonDataStore _dataStore;
        public static IDataStore DataStore
        {
            get
            {
                if (_dataStore == null)
                {
                    _dataStore = new JsonDataStore("db");
                    _dataStore.RegisterPartitionSelector<SortedObservableGroup<string, Book>>(DataCollectionNames.Booklists, obj => obj.Key);
                }

                return _dataStore;
            }
        }

        private static BrowseBooksViewModel _browseBooksViewModel;
        public static BrowseBooksViewModel BrowseBooksViewModel
        {
            get
            {
                if (_browseBooksViewModel == null)
                {
                    _browseBooksViewModel = new BrowseBooksViewModel();
                }

                return _browseBooksViewModel;
            }
        }

        private static HomeViewModel _homeViewModel;
        public static HomeViewModel HomeViewModel
        {
            get
            {
                if (_homeViewModel == null)
                {
                    _homeViewModel = new HomeViewModel();
                }

                return _homeViewModel;
            }
        }
    }
}

Remove disused data collection partition registers.


@model BatteryCommander.Web.Models.Evaluation

@Model.Ratee

            Soldier
            @Model.Ratee

            Rater
            @Model.Rater

            SR Rater
            @Model.SeniorRater

            Last Message
            @Model.LastEvent.Message

            Author
            @Model.LastEvent.Author

            Timestamp
            @Model.LastEvent.TimestampHumanized

            Link
            Evaluation

Evaluation Tracker

@model BatteryCommander.Web.Models.Evaluation

@Model.Ratee

            Soldier
            @Model.Ratee

            Rater
            @Model.Rater

            SR Rater
            @Model.SeniorRater

            Last Message
            @Model.LastEvent.Message by @Model.LastEvent.Author @Model.LastUpdatedHumanized

            Link
            Evaluation

        @if(!String.IsNullOrWhiteSpace(Model.EvaluationLink))
        {

                EES
                @Model.EvaluationId

        }

Evaluation Tracker

Tweak format of evaluation email per BC request


using BibleBot.Lib;
using DSharpPlus.Entities;

namespace BibleBot.Frontend
{
    public class Utils
    {
        public DiscordEmbed Embed2Embed(InternalEmbed embed)
        {
            var builder = new DiscordEmbedBuilder();

            var footerText =

            builder.WithTitle(embed.Title);
            builder.WithDescription(embed.Description);
            builder.WithColor(new DiscordColor((int) embed.Colour));
            builder.WithFooter(embed.Footer.Text, "https://i.imgur.com/hr4RXpy.png");

            if (embed.Author != null)
            {
                builder.WithAuthor(embed.Author.Name, null, null);
            }

            return builder.Build();
        }
    }
}

using BibleBot.Lib;
using DSharpPlus.Entities;

namespace BibleBot.Frontend
{
    public class Utils
    {
        public enum Colours
        {
            NORMAL_COLOR = 6709986,
            ERROR_COLOR = 16723502
        }

        public DiscordEmbed Embed2Embed(InternalEmbed embed)
        {
            var builder = new DiscordEmbedBuilder();

            builder.WithTitle(embed.Title);
            builder.WithDescription(embed.Description);
            builder.WithColor(new DiscordColor((int) embed.Colour));
            builder.WithFooter(embed.Footer.Text, "https://i.imgur.com/hr4RXpy.png");

            if (embed.Author != null)
            {
                builder.WithAuthor(embed.Author.Name, null, null);
            }

            return builder.Build();
        }

        public DiscordEmbed Embedify(string title, string description, bool isError)
        {
            return Embedify(null, title, description, isError, null);
        }

        public DiscordEmbed Embedify(string author, string title, string description, bool isError, string copyright)
        {
            // TODO: Do not use hard-coded version tags.
            string footerText = "BibleBot v9.1-beta by Kerygma Digital";

            var builder = new DiscordEmbedBuilder();
            builder.WithTitle(title);
            builder.WithDescription(description);
            builder.WithColor(isError ? (int) Colours.ERROR_COLOR : (int) Colours.NORMAL_COLOR);

            builder.WithFooter(footerText, "https://i.imgur.com/hr4RXpy.png");

            if (author != null)
            {
                builder.WithAuthor(author, null, null);
            }

            return builder.Build();
        }
    }
}

Implement embedify function on frontend.


using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class CoinInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty)
		{
			Coin = coin;
			Title = $"Details of {coin.OutputIndex}:{coin.TransactionId[0..7]}";
		}

		public CoinViewModel Coin { get; }
	}
}

using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class CoinInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty)
		{
			Coin = coin;
			Title = $"Coin ({coin.Amount.ToString(false, true)}) Details";
		}

		public CoinViewModel Coin { get; }
	}
}

Use Amount as coin identifier.

Use Amount as coin identifier.


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RegTesting.Tests.Framework")]
[assembly: AssemblyDescription("A test framework for tests with selenium.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HOTELDE AG")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a7e6a771-5f9d-425a-a401-3a5f4c71b270")]

// Version information for an assembly consists of the following four values:
//
//      Major Version <- upper this for breaking api changes
//      Minor Version  <- upper this for new functionality
//      Build Number <- this should match to the referenced selenium version
//      Revision
//
[assembly: AssemblyVersion("1.0.*.*")]
[assembly: AssemblyFileVersion("1.0.*.*")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RegTesting.Tests.Framework")]
[assembly: AssemblyDescription("A test framework for tests with selenium.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HOTELDE AG")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a7e6a771-5f9d-425a-a401-3a5f4c71b270")]

// Version information for an assembly consists of the following four values:
//
//      Major Version <- upper this for breaking api changes
//      Minor Version  <- upper this for new functionality
//      Build Number <- auto generated while build
//      Revision <- auto generated while build
//
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]

Fix autogeneration of Framework version Version has to be Major.Minor.* instead of Major.Minor.*.*


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.ComponentModel;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;

namespace osu.Game.Tests.Visual
{
    [Description("Testing chat api and overlay")]
    public class TestCaseChatDisplay : OsuTestCase
    {
        public TestCaseChatDisplay()
        {
            Add(new ChatOverlay
            {
                State = Visibility.Visible
            });
        }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Overlays.Chat;
using osu.Game.Overlays.Chat.Tabs;

namespace osu.Game.Tests.Visual
{
    [Description("Testing chat api and overlay")]
    public class TestCaseChatDisplay : OsuTestCase
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ChatOverlay),
            typeof(ChatLine),
            typeof(DrawableChannel),
            typeof(ChannelSelectorTabItem),
            typeof(ChannelTabControl),
            typeof(ChannelTabItem),
            typeof(PrivateChannelTabItem),
            typeof(TabCloseButton)
        };

        public TestCaseChatDisplay()
        {
            Add(new ChatOverlay
            {
                State = Visibility.Visible
            });
        }
    }
}

Allow testing of all chat-related classes dynamically


// 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 osu.Game.Overlays.Profile.Sections.Ranks;
using osu.Game.Online.API.Requests;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class RanksSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraTopRanksTitle;

        public override string Identifier => @"top_ranks";

        public RanksSection()
        {
            Children = new[]
            {
                // todo: update to use UsersStrings.ShowExtraTopRanksPinnedTitle once that exists.
                new PaginatedScoreContainer(ScoreType.Pinned, User, "Pinned Scores"),
                new PaginatedScoreContainer(ScoreType.Best, User, UsersStrings.ShowExtraTopRanksBestTitle),
                new PaginatedScoreContainer(ScoreType.Firsts, User, UsersStrings.ShowExtraTopRanksFirstTitle)
            };
        }
    }
}

// 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 osu.Game.Overlays.Profile.Sections.Ranks;
using osu.Game.Online.API.Requests;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class RanksSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraTopRanksTitle;

        public override string Identifier => @"top_ranks";

        public RanksSection()
        {
            Children = new[]
            {
                new PaginatedScoreContainer(ScoreType.Pinned, User, UsersStrings.ShowExtraTopRanksPinnedTitle),
                new PaginatedScoreContainer(ScoreType.Best, User, UsersStrings.ShowExtraTopRanksBestTitle),
                new PaginatedScoreContainer(ScoreType.Firsts, User, UsersStrings.ShowExtraTopRanksFirstTitle)
            };
        }
    }
}

Update pinned score container header to use localised title


using System.Threading.Tasks;

namespace DanTup.DartAnalysis
{
	class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
	{
		public string method = "analysis.getHover";

		public AnalysisGetHoverRequest(string file, int offset)
		{
			this.@params = new AnalysisGetHoverParams(file, offset);
		}
	}

	class AnalysisGetHoverParams
	{
		public string file;
		public int offset;

		public AnalysisGetHoverParams(string file, int offset)
		{
			this.file = file;
			this.offset = offset;
		}
	}

	class AnalysisGetHoverResponse
	{
		public AnalysisHoverItem[] hovers = null;
	}

	public class AnalysisHoverItem
	{
		public int offset;
		public int length;
		public string containingLibraryPath;
		public string containingLibraryName;
		public string dartdoc;
		public string elementKind;
		public string elementDescription;
		public string propagatedType;
		public string staticType;
		public string parameter;
	}

	public static class AnalysisGetHoverImplementation
	{
		public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
		{
			var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset)).ConfigureAwait(continueOnCapturedContext: false);

			return response.result.hovers;
		}
	}
}

using System.Threading.Tasks;
using DanTup.DartAnalysis.Json;

namespace DanTup.DartAnalysis
{
	public static class AnalysisGetHoverImplementation
	{
		public static async Task<HoverInformation[]> GetHover(this DartAnalysisService service, string file, int offset)
		{
			var request = new AnalysisGetHoverRequest
			{
				File = file,
				Offset = offset
			};

			var response = await service.Service
				.Send(new AnalysisGetHover(request))
				.ConfigureAwait(continueOnCapturedContext: false);

			return response.result.Hovers;
		}
	}
}

Replace GetHover implementation with generated classes.

Does not yet compile; due to errors in generated classes (Eg. FileInfo
== string).


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

namespace Lab2.Automaton
{
    public class AutomatonBuilder : IIOAutomatonBuilder
    {
        private FiniteStateAutomaton automaton = new FiniteStateAutomaton();

        public void AddState(int identifier)
        {
            StateDescription state = new StateDescription(identifier.ToString());
            automaton.AddNewState(state);
        }

        public void AddTransition(int from, int to, char? label)
        {
            StateDescription head = automaton.FindByName(from.ToString());
            StateDescription tale = automaton.FindByName(to.ToString());
            if (head == null || tale == null)
            {
                throw new ArgumentException();
            }
            SymbolBase symbol = null;

            if (label.HasValue)
            {
                symbol = new CharSybmol(label.Value);
            }
            else
            {
                symbol = new EpsilonSymbol();
            }
            head.AddNewTransition(symbol, tale);
        }

        public void SetStartState(int identifier)
        {
            throw new NotImplementedException();
        }

        public void SetFinhState(int identifier)
        {
            throw new NotImplementedException();
        }

        public IAutomaton GetAutomaton()
        {
            return automaton;
        }

    }
}

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

namespace Lab2.Automaton
{
    public class AutomatonBuilder : IIOAutomatonBuilder
    {
        private FiniteStateAutomaton automaton = new FiniteStateAutomaton();

        public void AddState(int identifier)
        {
            StateDescription state = new StateDescription(identifier.ToString());
            automaton.AddNewState(state);
        }

        public void AddTransition(int from, int to, char? label)
        {
            StateDescription head = automaton.FindByName(from.ToString());
            StateDescription tale = automaton.FindByName(to.ToString());
            if (head == null || tale == null)
            {
                throw new ArgumentException();
            }
            SymbolBase symbol = null;

            if (label.HasValue)
            {
                symbol = new CharSybmol(label.Value);
            }
            else
            {
                symbol = new EpsilonSymbol();
            }
            head.AddNewTransition(symbol, tale);
        }

        public void SetStartState(int identifier)
        {
            StateDescription start = automaton.FindByName(identifier.ToString());
            if (start == null)
            {
                throw new ArgumentException();
            }
            start.IsStart = true;
        }

        public void SetFinhState(int identifier)
        {
            StateDescription finish = automaton.FindByName(identifier.ToString());
            if (finish == null)
            {
                throw new ArgumentException();
            }
            finish.IsFinish = true;
        }

        public IAutomaton GetAutomaton()
        {
            return automaton;
        }

    }
}

Add System Programming Lab2 Automaton Builder - Added Start and Finish


using System;
using AlphaDev.Core;
using AlphaDev.Web.Controllers;
using AlphaDev.Web.Models;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using Optional;
using Xunit;

namespace AlphaDev.Web.Tests.Unit.Controllers
{
    public class AdminControllerTests
    {
        private AdminController GetAdminController()
        {
            var blogService = Substitute.For<IBlogService>();
            blogService.GetLatest().Returns(((BlogBase) new Blog(default, null, null, default)).Some());

            return GetAdminController(blogService);
        }

        private AdminController GetAdminController(IBlogService blogService)
        {
            return new AdminController();
        }

        [Fact]
        public void IndexShouldReturnIndexView()
        {
            var controller = GetAdminController();

            controller.Index().Should().BeOfType<ViewResult>();
        }
    }
}

using System;
using AlphaDev.Core;
using AlphaDev.Web.Controllers;
using AlphaDev.Web.Models;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using Optional;
using Xunit;

namespace AlphaDev.Web.Tests.Unit.Controllers
{
    public class AdminControllerTests
    {
        private AdminController GetAdminController()
        {
            return new AdminController();
        }

        [Fact]
        public void IndexShouldReturnIndexViewResult()
        {
            var controller = GetAdminController();

            controller.Index().Should().BeOfType<ViewResult>().Which.ViewName.Should().BeEquivalentTo("Index");
        }
    }
}

Remove redundant code from Admin controller


using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Watsonia.Data.Tests")]
[assembly: InternalsVisibleTo("Watsonia.Data.Reference")]

Make the assembly's internals visible to the reference assembly


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace api
{
    public class CommaDelimitedArrayModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelMetadata.IsEnumerableType)
            {
                var key = bindingContext.ModelName;
                var value = bindingContext.ValueProvider.GetValue(key).ToString();

                if (!string.IsNullOrWhiteSpace(value))
                {
                    var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
                    var converter = TypeDescriptor.GetConverter(elementType);

                    var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => converter.ConvertFromString(x.Trim()))
                        .ToArray();

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Result = ModelBindingResult.Success(typedValues);
                }
                else
                {
                    Console.WriteLine("string was empty");
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
                }

                return Task.CompletedTask;
            }
            Console.WriteLine("Not enumerable");
            return Task.CompletedTask;
        }
    }
}

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace api
{
    public class CommaDelimitedArrayModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelMetadata.IsEnumerableType)
            {
                var key = bindingContext.ModelName;
                var value = bindingContext.ValueProvider.GetValue(key).ToString();

                if (!string.IsNullOrWhiteSpace(value))
                {
                    var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
                    var converter = TypeDescriptor.GetConverter(elementType);

                    var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => converter.ConvertFromString(x.Trim()))
                        .ToArray();

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Result = ModelBindingResult.Success(typedValues);
                }
                else
                {
                    Console.WriteLine("string was empty");
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
                }

                return Task.CompletedTask;
            }
            Console.WriteLine("Not enumerable");
            return Task.CompletedTask;
        }
    }
}

Add input binder to allow for comma-separated list inputs for API routes

Signed-off-by: Max Cairney-Leeming <d90f0d0190ac210d40c0e06a2594c771efeb4f5b@gmail.com>


namespace ExifLibrary
{
    /// <summary>
    /// Represents error severity.
    /// </summary>
    public enum Severity
    {
        Info,
        Warning,
        Error,
    }

    /// <summary>
    /// Represents errors or warnings generated while reading/writing image files.
    /// </summary>
    public class ImageError
    {

        /// <summary>
        /// Gets the severity of the error.
        /// </summary>
        public Severity Severity { get;}

        /// <summary>
        /// Gets the error message.
        /// </summary>
        public string Message { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageError"/> class.
        /// </summary>
        /// <param name="severity"></param>
        /// <param name="message"></param>
        public ImageError(Severity severity, string message)
        {
            Severity = severity;
            Message = message;
        }
    }
}

namespace ExifLibrary
{
    /// <summary>
    /// Represents error severity.
    /// </summary>
    public enum Severity
    {
        Info,
        Warning,
        Error,
    }

    /// <summary>
    /// Represents errors or warnings generated while reading/writing image files.
    /// </summary>
    public class ImageError
    {

        /// <summary>
        /// Gets the severity of the error.
        /// </summary>
        public Severity Severity { get;}

        /// <summary>
        /// Gets the error message.
        /// </summary>
        public string Message { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageError"/> class.
        /// </summary>
        /// <param name="severity"></param>
        /// <param name="message"></param>
        public ImageError(Severity severity, string message)
        {
            Severity = severity;
            Message = message;
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return Message;
        }
    }
}

Add toString override to error class

Add toString override to error class


using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta02")]

using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta03")]

Increase nuget package version to 2.0.0-beta03


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class BoxInfo : MonoBehaviour
{
	public Text LeftText;
	public Text RightText;

	readonly StringBuilder names = new StringBuilder();
	readonly StringBuilder values = new StringBuilder();

	public void Clear()
	{
		names.Length = 0;
		names.Capacity = 0;
		values.Length = 0;
		values.Capacity = 0;

		LeftText.text = string.Empty;
		RightText.text = string.Empty;
		gameObject.SetActive(false);
	}

	public void Append(string name, object value)
    {
		names.AppendLine(name);
		values.AppendLine(value.ToString());
    }

	public void Append()
    {
		Append(string.Empty, string.Empty);
    }

	public void AppendFormat(string name, string format, params object[] args)
    {
		Append(name, string.Format(format, args));
    }

    public void UpdateText()
    {
    	//remove last line return character
		names.Length -= 2;
		values.Length -= 2;

		LeftText.text = names.ToString();
		RightText.text = values.ToString();

		gameObject.SetActive(LeftText.text.Length > 0);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class BoxInfo : MonoBehaviour
{
	public Text LeftText;
	public Text RightText;

	readonly StringBuilder names = new StringBuilder();
	readonly StringBuilder values = new StringBuilder();

	public void Clear()
	{
		names.Length = 0;
		names.Capacity = 0;
		values.Length = 0;
		values.Capacity = 0;

		LeftText.text = string.Empty;
		RightText.text = string.Empty;
		gameObject.SetActive(false);
	}

	public void Append(string name, object value)
    {
		names.AppendLine(name);
		values.AppendLine(value.ToString());
    }

	public void Append()
    {
		Append(string.Empty, string.Empty);
    }

	public void AppendFormat(string name, string format, params object[] args)
    {
		Append(name, string.Format(format, args));
    }

    public void UpdateText()
    {
    	//remove last line return character
		if (names.Length >= 2)
		{
			names.Length -= 2;
			values.Length -= 2;
		}

		LeftText.text = names.ToString();
		RightText.text = values.ToString();

		gameObject.SetActive(LeftText.text.Length > 0);
    }
}

Fix exception when box info is empty

Fix exception when box info is empty


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

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace osu.Framework.Platform.Windows
{
    public class WindowsStorage : DesktopStorage
    {
        public WindowsStorage(string baseName, DesktopGameHost host)
            : base(baseName, host)
        {
            // allows traversal of long directory/filenames beyond the standard limitations (see https://stackoverflow.com/a/5188559)
            BasePath = Regex.Replace(BasePath, @"^([a-zA-Z]):\\", @"\\?\$1:\");
        }

        public override void OpenInNativeExplorer() => Process.Start("explorer.exe", GetFullPath(string.Empty));

        protected override string LocateBasePath() => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    }
}

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

using System;
using System.Diagnostics;

namespace osu.Framework.Platform.Windows
{
    public class WindowsStorage : DesktopStorage
    {
        public WindowsStorage(string baseName, DesktopGameHost host)
            : base(baseName, host)
        {
        }

        public override void OpenInNativeExplorer() => Process.Start("explorer.exe", GetFullPath(string.Empty));

        protected override string LocateBasePath() => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    }
}

Remove Windows long path workaround.

Remove Windows long path workaround.


namespace Fixie
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Reflection;
    using static Internal.Maybe;

    public static class ReflectionExtensions
    {
        public static bool IsVoid(this MethodInfo method)
        {
            return method.ReturnType == typeof(void);
        }

        public static bool IsStatic(this Type type)
        {
            return type.IsAbstract && type.IsSealed;
        }

        public static bool Has<TAttribute>(this MemberInfo member) where TAttribute : Attribute
        {
            return member.GetCustomAttributes<TAttribute>(true).Any();
        }

        public static bool Has<TAttribute>(this MemberInfo member, [NotNullWhen(true)] out TAttribute? matchingAttribute) where TAttribute : Attribute
        {
            return Try(() => member.GetCustomAttribute<TAttribute>(true), out matchingAttribute);
        }

        public static void Dispose(this object? o)
        {
            (o as IDisposable)?.Dispose();
        }
    }
}

namespace Fixie
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Reflection;
    using static Internal.Maybe;

    public static class ReflectionExtensions
    {
        public static bool IsVoid(this MethodInfo method)
        {
            return method.ReturnType == typeof(void);
        }

        public static bool IsStatic(this Type type)
        {
            return type.IsAbstract && type.IsSealed;
        }

        public static bool Has<TAttribute>(this MemberInfo member) where TAttribute : Attribute
        {
            return member.GetCustomAttributes<TAttribute>(true).Any();
        }

        public static bool Has<TAttribute>(this MemberInfo member, [NotNullWhen(true)] out TAttribute? matchingAttribute) where TAttribute : Attribute
        {
            return Try(() => member.GetCustomAttribute<TAttribute>(true), out matchingAttribute);
        }

        public static void Dispose(this object? o)
        {
            if (o is IDisposable disposable)
                disposable.Dispose();
        }
    }
}

Rephrase null-safe Dispose helper to use pattern matching syntax.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcMiniProfiler;
using Raven.Client.Connection;
using Raven.Client.Connection.Profiling;
using Raven.Client.Document;

namespace MvcMiniProfiler.RavenDb
{
	public class Profiler
	{
		private static Dictionary<string, IDisposable> _Requests = new Dictionary<string, IDisposable>();

		public static void AttachTo(DocumentStore store) {
			store.SessionCreatedInternal += TrackSession;
			store.JsonRequestFactory.ConfigureRequest += BeginRequest;
			store.JsonRequestFactory.LogRequest += EndREquest;
		}

		private static void TrackSession(InMemoryDocumentSessionOperations obj) {
			MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Created Session").Dispose();
		}

		private static void BeginRequest(object sender, WebRequestEventArgs e) {
			_Requests.Add(e.Request.RequestUri.PathAndQuery, MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Query - " + e.Request.RequestUri.PathAndQuery));
		}

		private static void EndREquest(object sender, RequestResultArgs e) {
			IDisposable request;
			if (_Requests.TryGetValue(e.Url, out request))
				request.Dispose();
		}
	}
}

using System;
using System.Collections.Generic;
using Raven.Client.Connection;
using Raven.Client.Connection.Profiling;
using Raven.Client.Document;

namespace MvcMiniProfiler.RavenDb
{
	public class Profiler
	{
		private static Dictionary<string, IDisposable> _Requests = new Dictionary<string, IDisposable>();

		public static void AttachTo(DocumentStore store) {
			store.SessionCreatedInternal += TrackSession;
			store.JsonRequestFactory.ConfigureRequest += BeginRequest;
			store.JsonRequestFactory.LogRequest += EndRequest;
		}

		private static void TrackSession(InMemoryDocumentSessionOperations obj) {
			MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Created Session").Dispose();
		}

		private static void BeginRequest(object sender, WebRequestEventArgs e) {
			_Requests.Add(e.Request.RequestUri.PathAndQuery, MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Query - " + e.Request.RequestUri.PathAndQuery));
		}

		private static void EndRequest(object sender, RequestResultArgs e) {
			IDisposable request;
			if (_Requests.TryGetValue(e.Url, out request))
				request.Dispose();
		}
	}
}

Tidy up some formatting of code file

Tidy up some formatting of code file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;

namespace LearnosityDemo.Pages
{
    public class ItemsAPIDemoModel : PageModel
    {
        public void OnGet()
        {
            // prepare all the params
            string service = "items";

            JsonObject security = new JsonObject();
            security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
            security.set("domain", LearnositySDK.Credentials.Domain);
            security.set("user_id", Uuid.generate());
            string secret = LearnositySDK.Credentials.ConsumerSecret;

            JsonObject request = new JsonObject();
            request.set("user_id", Uuid.generate());
            request.set("activity_template_id", "quickstart_examples_activity_template_001");
            request.set("session_id", Uuid.generate());
            request.set("activity_id", "quickstart_examples_activity_001");
            request.set("rendering_type", "assess");
            request.set("type", "submit_practice");
            request.set("name", "Items API Quickstart");
            request.set("state", "initial");

            // Instantiate Init class
            Init init = new Init(service, security, secret, request);

            // Call the generate() method to retrieve a JavaScript object
            ViewData["InitJSON"] = init.generate();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;

namespace LearnosityDemo.Pages
{
    public class ItemsAPIDemoModel : PageModel
    {
        public void OnGet()
        {
            // prepare all the params
            string service = "items";

            JsonObject security = new JsonObject();
            security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
            security.set("domain", LearnositySDK.Credentials.Domain);
            security.set("user_id", Uuid.generate());
            string secret = LearnositySDK.Credentials.ConsumerSecret;

            JsonObject request = new JsonObject();
            request.set("user_id", Uuid.generate());
            request.set("activity_template_id", "quickstart_examples_activity_template_001");
            request.set("session_id", Uuid.generate());
            request.set("activity_id", "quickstart_examples_activity_001");
            request.set("rendering_type", "assess");
            request.set("type", "submit_practice");
            request.set("name", "Items API Quickstart");
            request.set("state", "initial");

            // Instantiate Init class
            Init init = new Init(service, security, secret, request);

            // Call the generate() method to retrieve a JavaScript object
            ViewData["InitJSON"] = init.generate();
        }
    }
}

[DOC] Remove commented code line from developer review.


using System;

namespace NHibernate.DomainModel
{
	/// <summary>
	/// Summary description for SubComponent.
	/// </summary>
	public class SubComponent
	{
		private string _subName;
		private string _subName1;

		public SubComponent()
		{
		}

		public string SubName
		{
			get { return _subName; }
			set { _subName = value; }
		}

		public string SubName1
		{
			get { return _subName1; }
			set { _subName1 = value; }
		}
	}
}

Test code for SQL queries

NH-204: Test code for SQL queries

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@1333


namespace ZocMonLib
{
    public enum MonitorReductionType
    {
        Custom = 0,
        DefaultAverage = 1,
        DefaultAccumulate = 2
    }
}

namespace ZocMonLib
{
    public enum MonitorReductionType : byte
    {
        Custom = 0,
        DefaultAverage = 1,
        DefaultAccumulate = 2
    }
}

Make this enum a byte for small serialization


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

namespace DasMulli.Win32.ServiceUtils
{
    /// <summary>
    /// Simplifies the work of hashing.
    /// Taken from <see cref="https://rehansaeed.com/gethashcode-made-easy/"/>, and modified with Reshaper
    /// </summary>
    public struct HashCode
    {
        private readonly int value;
        private HashCode(int value)
        {
            this.value = value;
        }
        public static implicit operator int(HashCode hashCode)
        {
            return hashCode.value;
        }
        public static HashCode Of<T>(T item)
        {
            return new HashCode(GetHashCode(item));
        }
        public HashCode And<T>(T item)
        {
            return new HashCode(CombineHashCodes(this.value, GetHashCode(item)));
        }
        public HashCode AndEach<T>(IEnumerable<T> items)
        {
            int hashCode = items.Select(GetHashCode).Aggregate(CombineHashCodes);
            return new HashCode(CombineHashCodes(this.value, hashCode));
        }
        private static int CombineHashCodes(int h1, int h2)
        {
            unchecked
            {
                // Code copied from System.Tuple so it must be the best way to combine hash codes or at least a good one.
                return ((h1 << 5) + h1) ^ h2;
            }
        }
        private static int GetHashCode<T>(T item)
        {
            return item == null ? 0 : item.GetHashCode();
        }
    }
}

Add a reusable hash-code class.

Add a reusable hash-code class.


// http://careercup.com/question?id=5702976138117120
// Split string per pattern
//

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

static class Program
{
    static IEnumerable<String> Split(this String s, IEnumerable<int> pattern)
    {
        int prev = 0;
        foreach (int index in pattern)
        {
            yield return s.Substring(prev, index - prev + 1);
            prev = index + 1;
        }

        yield return s.Substring(prev, s.Length - prev);
    }

    static void Main()
    {
        String s = "Programmingproblemforidiots";
        Console.WriteLine(String.Join(", ", s.Split(new List<int> {10, 17, 20})));
    }
}

Split string per given pattern

Split string per given pattern


// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.IO;
using System.Text;
using Xunit;

namespace Google.Cloud.Storage.V1.IntegrationTests
{
    /// <summary>
    /// Tests that ensure the client does *not* perform any normalization.
    /// The bucket <see cref="s_bucket"/> contains two files, which are both named "Café"
    /// but using different normalization. The client should be able to retrieve both.
    /// </summary>
    public class NormalizationTest
    {
        private const string s_bucket = "storage-library-test-bucket";

        [Theory]
        // Normalization Form C: a single character for e-acute.
        // URL should end with Cafe%CC%81
        [InlineData("Caf\u00e9", "Normalization Form C")]
        // Normalization Form D: an ASCII e followed by U+0301 combining character
        // URL should end with Caf%C3%A9
        [InlineData("Cafe\u0301", "Normalization Form D")]
        public void FetchObjectAndCheckContent(string name, string expectedContent)
        {
            var client = StorageClient.Create();
            var obj = client.GetObject(s_bucket, name);
            Assert.Equal(name, obj.Name);

            var stream = new MemoryStream();
            client.DownloadObject(s_bucket, name, stream);
            string text = Encoding.UTF8.GetString(stream.ToArray());
            Assert.Equal(expectedContent, text);
        }
    }
}

Add "no normalization performed" test for Storage client.


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }

        [HttpPost]
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }

        /// <summary>
        /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Update server side API for single multiple answer question


using System;
using Microsoft.AspNetCore.Builder;
using Moq;
using Xunit;

namespace Marvin.Cache.Headers.Test.Extensions
{
    public class AppBuilderExtensionsFacts
    {
        [Fact(Skip = "The Verify throws an exception because UseMiddleware is an extension function as well and can't be mocked, need to find ")]
        public void Correctly_register_HttpCacheHeadersMiddleware()
        {
            var appBuilderMock = new Mock<IApplicationBuilder>();
            appBuilderMock.Object.UseHttpCacheHeaders();

            appBuilderMock.Verify(x => x.UseMiddleware<HttpCacheHeadersMiddleware>(), "Application builder isn't registering the middleware.");
        }

        [Fact]
        public void When_no_ApplicationBuilder_expect_ArgumentNullException()
        {
            IApplicationBuilder appBuilder = null;

            Assert.Throws<ArgumentNullException>(() => appBuilder.UseHttpCacheHeaders());

        }
    }
}

Add first draft of AppBuilderExtension tests.


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

namespace Pather.CSharp.PathElements
{
    public class SelectionAccess : IPathElement
    {
        public SelectionAccess()
        {
        }

        public object Apply(object target)
        {
            var enumerable = target as IEnumerable;
            var result = new Selection(enumerable);
            return result;
        }
    }
}

Add path element class for selection access


// 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;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Extensions;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Framework.Tests.Platform
{
    [TestFixture]
    public class GameExitTest
    {
        private TestTestGame game;
        private ManualExitHeadlessGameHost host;

        private const int timeout = 5000;

        [Test]
        public void TestExitBlocking()
        {
            var gameCreated = new ManualResetEventSlim();

            var task = Task.Factory.StartNew(() =>
            {
                using (host = new ManualExitHeadlessGameHost())
                {
                    game = new TestTestGame();
                    gameCreated.Set();
                    host.Run(game);
                }
            }, TaskCreationOptions.LongRunning);

            gameCreated.Wait(timeout);
            Assert.IsTrue(game.BecameAlive.Wait(timeout));

            // block game from exiting.
            game.BlockExit.Value = true;
            // `RequestExit()` should return true.
            Assert.That(host.RequestExit(), Is.True);
            // exit should be blocked.
            Assert.That(() => host.ExecutionState, Is.EqualTo(ExecutionState.Running).After(timeout));
            Assert.That(task.IsCompleted, Is.False);

            // unblock game from exiting.
            game.BlockExit.Value = false;
            // `RequestExit()` should not be blocked and return false.
            Assert.That(host.RequestExit(), Is.False);
            // finally, the game should exit.
            Assert.That(() => host.ExecutionState, Is.EqualTo(ExecutionState.Stopped).After(timeout));
            task.WaitSafely();
        }

        private class ManualExitHeadlessGameHost : TestRunHeadlessGameHost
        {
            public bool RequestExit() => OnExitRequested();
        }

        private class TestTestGame : TestGame
        {
            public readonly ManualResetEventSlim BecameAlive = new ManualResetEventSlim();

            protected override void LoadComplete()
            {
                BecameAlive.Set();
            }
        }
    }
}

Add baseline test coverage for blocking exit flow


using System.Linq;
using Xunit;
using Marten.Testing.Linq;

namespace Marten.Testing.Bugs
{
    public class Bug_854_multiple_or_expressions_softdelete_tenancy_filters_appended_incorrectly: IntegratedFixture
    {
        [Fact]
        public void query_where_with_multiple_or_expressions_against_single_tenant()
        {
            StoreOptions(_ =>
            {
                _.Schema.For<Target>().MultiTenanted();
            });

            Target[] reds = Target.GenerateRandomData(50).ToArray();

            theStore.BulkInsert("Bug_854", reds);

            var expected = reds.Where(x => x.String == "Red" || x.String == "Orange").Select(x => x.Id).OrderBy(x => x).ToArray();

            using (var query = theStore.QuerySession("Bug_854"))
            {
                var actual = query.Query<Target>().Where(x => x.String == "Red" || x.String == "Orange")
                                  .OrderBy(x => x.Id).Select(x => x.Id).ToArray();

                actual.ShouldHaveTheSameElementsAs(expected);
            }
        }

        [Fact]
        public void query_where_with_multiple_or_expresions_against_soft_Deletes()
        {
            StoreOptions(_ => _.Schema.For<SoftDeletedItem>().SoftDeleted());

            var item1 = new SoftDeletedItem { Number = 1, Name = "Jim Bob" };
            var item2 = new SoftDeletedItem { Number = 2, Name = "Joe Bill" };
            var item3 = new SoftDeletedItem { Number = 1, Name = "Jim Beam" };

            int expected = 3;

            using (var session = theStore.OpenSession())
            {
                session.Store(item1, item2, item3);
                session.SaveChanges();
            }

            using (var session = theStore.QuerySession())
            {
                var query = session.Query<SoftDeletedItem>()
                    .Where(x => x.Number == 1 || x.Number == 2);

                var actual = query.ToList().Count;
                Assert.Equal(expected, actual);
            }
        }
    }
}

Add failing tests for GH-854

Add failing tests for GH-854


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ComponentModel;
using System.Runtime.Serialization;

namespace System.Net.Sockets
{
    [Serializable]
    public partial class SocketException : Win32Exception
    {
        protected SocketException(SerializationInfo serializationInfo, StreamingContext streamingContext)
            : base(serializationInfo, streamingContext)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("SocketException::.ctor(serialized) " + NativeErrorCode.ToString() + ":" + Message);
            }
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ComponentModel;
using System.Runtime.Serialization;

namespace System.Net.Sockets
{
    [Serializable]
    public partial class SocketException : Win32Exception
    {
        protected SocketException(SerializationInfo serializationInfo, StreamingContext streamingContext)
            : base(serializationInfo, streamingContext)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print($"SocketException::.ctor(serialized, SocketErrorCode={SocketErrorCode}):{Message}");
            }
        }

        public override int ErrorCode => base.NativeErrorCode;
    }
}

Add missing members in System.Net.Sockets.SocketException

Fixes #12459


using System;
using System.ComponentModel.Composition;

using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.ProjectSystem.Utilities;
using Microsoft.VisualStudio.ProjectSystem.Utilities.Designers;

namespace NuProj.ProjectSystem
{
    [Export(typeof(IProjectTreeModifier))]
    [PartMetadata(ProjectCapabilities.Requires, NuProjCapabilities.NuProj)]
    internal sealed class NuProjProjectTreeModifier : IProjectTreeModifier
    {
        [Import]
        public Lazy<IProjectTreeFactory> TreeFactory { get; set; }

        public IProjectTree ApplyModifications(IProjectTree tree, IProjectTreeProvider projectTreeProvider)
        {
            if (tree.Capabilities.Contains(ProjectTreeCapabilities.ProjectRoot))
                tree = tree.SetIcon(Resources.NuProj);

            return tree;
        }
    }
}

using System;
using System.ComponentModel.Composition;

using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.ProjectSystem.Utilities;
using Microsoft.VisualStudio.ProjectSystem.Utilities.Designers;

namespace NuProj.ProjectSystem
{
    [Export(typeof(IProjectTreeModifier))]
    [PartMetadata(ProjectCapabilities.Requires, NuProjCapabilities.NuProj)]
    internal sealed class NuProjProjectTreeModifier : IProjectTreeModifier
    {
        public IProjectTree ApplyModifications(IProjectTree tree, IProjectTreeProvider projectTreeProvider)
        {
            if (tree.Capabilities.Contains(ProjectTreeCapabilities.ProjectRoot))
                tree = tree.SetIcon(Resources.NuProj);

            return tree;
        }
    }
}

Remove unused project tree factory.

Remove unused project tree factory.

Not only is it unused, tree modifiers are not generally privileged to create new nodes. So it's a bad import to have.


//  https://leetcode.com/problems/copy-list-with-random-pointer/
//
//   A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
//
//   Return a deep copy of the list.

//  Finally nailed it.
//  https://leetcode.com/submissions/detail/53588998/
//
//  Submission Details
//  11 / 11 test cases passed.
//      Status: Accepted
//      Runtime: 112 ms
//
//          Submitted: 0 minutes ago

public class Solution {
    public RandomListNode CopyRandomList(RandomListNode head, Dictionary<RandomListNode, RandomListNode> hash = null) {
        if (head == null)
        {
            return null;
        }

        if (hash == null)
        {
            hash = new Dictionary<RandomListNode, RandomListNode>();
        }

        if (hash.ContainsKey(head))
        {
            return hash[head];
        }

        hash[head] = new RandomListNode(head.label);
        hash[head].next = CopyRandomList(head.next, hash);
        hash[head].random = CopyRandomList(head.random, hash);
        return hash[head];
    }
}

Copy list with random pointer

Copy list with random pointer


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

using Xunit;

// Disable test parallelization to avoid port reuse issues
[assembly: CollectionBehavior(DisableTestParallelization = true)]

Disable test parallelization in PowerShellEditorServices.Test project

More test instability, I think xUnit's parallelization must have become
more aggressive in 2.2.


namespace System
{
    internal static class SystemExtensions
    {
        internal static bool IsSuccessStatusCode(this int @this)
        {
            return @this >= 200 && @this <= 299;
        }
    }
}

Add extension method check for success HTTP Status code


using System;
using System.Runtime.InteropServices;
using static Avalonia.Win32.Interop.UnmanagedMethods;

namespace Avalonia.Win32
{
    delegate void MarkFullscreenWindow(IntPtr This, IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fullscreen);
    delegate HRESULT HrInit(IntPtr This);

    struct ITaskBarList2VTable
    {
        public IntPtr IUnknown1;
        public IntPtr IUnknown2;
        public IntPtr IUnknown3;
        public IntPtr HrInit;
        public IntPtr AddTab;
        public IntPtr DeleteTab;
        public IntPtr ActivateTab;
        public IntPtr SetActiveAlt;
        public IntPtr MarkFullscreenWindow;
    }
}

Add delegates and VTables for ITaskBarList2.


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Pinta.ImageManipulation
{
	public static class BitmapExtensions
	{
		public static void Render (this BaseEffect effect, Bitmap source)
		{
			var wrapper = new BitmapWrapper (source);

			effect.Render (wrapper);
		}
	}
}

Add extension overload of Render that takes care of the BitmapWrapper.


using System.Collections.Generic;
using System.Xml.Serialization;

namespace parallel_extension_demo
{
    [XmlRoot("groop")]
    public class Groups
    {
        [XmlArray("employees"), XmlArrayItem("employee")]
        public List<Employee> Colection { get; set; }
        [XmlAttribute("employeeCount")]
        public long Count { get; set; }

        public Groups() { }

        public Groups(List<Employee> list)
        {
            Colection = list; //.AddRange(list);
            Count = Colection.Count;
        }

    }
}

Add Groping class for Employee

Add Groping class for Employee


using System;
using System.IO;
using System.Net;

namespace stellar_dotnet_sdk
{
    public static class AccountUtil
    {
	public static void FundTestAccount(string Public_Key)
	{
		UriBuilder baseUri = new UriBuilder("https://horizon-testnet.stellar.org/friendbot");
		string queryToAppend = "addr=" + Public_Key;

		baseUri.Query = queryToAppend;
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUri.ToString());
		request.Method = "GET";
		HttpWebResponse response = (HttpWebResponse)request.GetResponse();
		StreamReader sr = new StreamReader(response.GetResponseStream());
		sr.ReadToEnd();
	}
    }
}

Add fund test account method

Add fund test account method

Signed-off-by: Jagadish Krishnamoorthy <476cecf2ec888ddf2e8e64a95d4cb60429928e9e@gmail.com>


using Sprache;
using Xunit;

namespace Sprache.Tests
{
    public class OptionTests
    {
        private Parser<IOption<char>> ParserOptionalSelect = Parse.Char('a').Optional().Select(o => o.Select(c => char.ToUpperInvariant(c)));

        private Parser<IOption<string>> ParserOptionalSelectMany =
                from o1 in Parse.Char('a').Optional()
                from o2 in Parse.Char('b').Optional()
                select o1.SelectMany(c1 => o2.Select(c2 => $"{c2}{c1}"));

        private Parser<IOption<string>> ParserOptionalLinq =
                from o1 in Parse.Char('a').Optional()
                from o2 in Parse.Char('b').Optional()
                select (from c1 in o1 from c2 in o2 select $"{c2}{c1}");

        private void AssertSome<T>(IOption<T> option, T expected) => Assert.True(option.IsDefined && option.Get().Equals(expected));

        [Fact]
        public void TestSelect() => AssertParser.SucceedsWith(ParserOptionalSelect, "a", o => AssertSome(o, 'A'));

        [Fact]
        public void TestSelectManySome() => AssertParser.SucceedsWith(ParserOptionalSelectMany, "ab", o => AssertSome(o, "ba"));

        [Fact]
        public void TestSelectManyNone() => AssertParser.SucceedsWith(ParserOptionalSelectMany, "b", o => Assert.True(o.IsEmpty));

        [Fact]
        public void TestSelectManyLinq() => AssertParser.SucceedsWith(ParserOptionalLinq, "ab", o => AssertSome(o, "ba"));
    }
}

Add unit test for OptionExtensions

Add unit test for OptionExtensions


using System.Data;

namespace ZocMonLib
{
    public interface IRecordReduce
    {
        /// <summary>
        /// Reduce all known data.
        /// </summary>
        string ReduceAll(bool deleteReducedData);

        /// <summary>
        /// Calculate and store all reductions for the given configuration.
        /// </summary>
        /// <param name="configName"></param>
        /// <param name="deleteReducedData">If true, will actually delete the reduced data</param>
        /// <param name="conn">s</param>
        /// <param name="isInner"></param>
        string Reduce(string configName, bool deleteReducedData, IDbConnection conn, bool isInner);
    }
}

using System.Data;

namespace ZocMonLib
{
    public interface IRecordReduce
    {
        /// <summary>
        /// Reduce all known data.
        /// </summary>
        string ReduceAll(bool deleteReducedData);

        /// <summary>
        /// Calculate and store all reductions for the given configuration.
        /// </summary>
        /// <param name="configName"></param>
        /// <param name="deleteReducedData">If true, will actually delete the reduced data</param>
        /// <param name="conn">s</param>
        /// <param name="isInner"></param>
        string Reduce(string configName, bool deleteReducedData = false, IDbConnection conn = null, bool isInner = false);
    }
}

Update reducer so that the interface has defaults


using System.Text;

namespace Atata
{
    /// <summary>
    /// Provides a set of extension methods for <see cref="StringBuilder"/>.
    /// </summary>
    public static class StringBuilderExtensions
    {
        /// <summary>
        /// Appends the space character.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <returns>A reference to the same <see cref="StringBuilder"/> instance after the append operation has completed.</returns>
        public static StringBuilder AppendSpace(this StringBuilder builder)
        {
            builder.CheckNotNull(nameof(builder));

            return builder.Append(' ');
        }
    }
}

Add AppendSpace extension method for StringBuilder


// 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 osu.Game.Graphics.Backgrounds;
using osu.Framework.Graphics;
using osuTK.Graphics;
using osu.Framework.Graphics.Shapes;

namespace osu.Game.Tests.Visual.Background
{
    public class TestSceneTrianglesBackground : OsuTestScene
    {
        private readonly Triangles triangles;

        public TestSceneTrianglesBackground()
        {
            Children = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = Color4.Black
                },
                triangles = new Triangles
                {
                    RelativeSizeAxes = Axes.Both,
                    ColourLight = Color4.White,
                    ColourDark = Color4.Gray
                }
            };
        }

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

            AddSliderStep("Triangle scale", 0f, 10f, 1f, s => triangles.TriangleScale = s);
        }
    }
}

Add test scene for Triangles

Add test scene for Triangles