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

namespace osu.Game.Utils
{
    public static class FormatUtils
    {
        /// <summary>
        /// Turns the provided accuracy into a percentage with 2 decimal places.
        /// Omits all decimal places when <paramref name="accuracy"/> equals 1d.
        /// </summary>
        /// <param name="accuracy">The accuracy to be formatted</param>
        /// <returns>formatted accuracy in percentage</returns>
        public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}";

        /// <summary>
        /// Turns the provided accuracy into a percentage with 2 decimal places.
        /// Omits all decimal places when <paramref name="accuracy"/> equals 100m.
        /// </summary>
        /// <param name="accuracy">The accuracy to be formatted</param>
        /// <returns>formatted accuracy in percentage</returns>
        public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%";
    }
}

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

namespace osu.Game.Utils
{
    public static class FormatUtils
    {
        /// <summary>
        /// Turns the provided accuracy into a percentage with 2 decimal places.
        /// </summary>
        /// <param name="accuracy">The accuracy to be formatted</param>
        /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 1d</param>
        /// <returns>formatted accuracy in percentage</returns>
        public static string FormatAccuracy(this double accuracy, bool alwaysShowDecimals = false) => accuracy == 1 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00%}";

        /// <summary>
        /// Turns the provided accuracy into a percentage with 2 decimal places.
        /// </summary>
        /// <param name="accuracy">The accuracy to be formatted</param>
        /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 100m</param>
        /// <returns>formatted accuracy in percentage</returns>
        public static string FormatAccuracy(this decimal accuracy, bool alwaysShowDecimals = false) => accuracy == 100 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00}%";
    }
}

Add alwaysShowDecimals param to FormatAccuracy

This allows us to specify whether we want it to show decimal places if accuracy is 100%.


Use DotNetCoreBuild in Cake script.

Use DotNetCoreBuild in Cake script.


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

namespace ECS
{
    public class EntityComponentSystem
    {
        private EntityManager entityManager;
        private SystemManager systemManager;

        public EntityComponentSystem()
        {
            entityManager = new EntityManager();

            systemManager = new SystemManager();
            systemManager.context = this;
        }

        public Entity CreateEntity()
        {
            return entityManager.CreateEntity();
        }

        public void AddSystem(System system, int priority = 0)
        {
            systemManager.SetSystem(system, priority);
        }

        public void Update(float deltaTime)
        {
            foreach (var systems in systemManager.SystemsByPriority())
            {
                entityManager.ProcessQueues();

                foreach (var system in systems)
                {
                    system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime);
                }
            }

            systemManager.ProcessQueues();
        }
    }
}

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

namespace ECS
{
    public class EntityComponentSystem
    {
        private EntityManager entityManager;
        private SystemManager systemManager;

        public EntityComponentSystem()
        {
            entityManager = new EntityManager();

            systemManager = new SystemManager();
            systemManager.context = this;
        }

        public Entity CreateEntity()
        {
            return entityManager.CreateEntity();
        }

        public void AddSystem(System system, int priority = 0)
        {
            systemManager.SetSystem(system, priority);
        }

        // TODO: Is this needed and is this right place for this method?
        public IEnumerable<Entity> QueryActiveEntities(Aspect aspect)
        {
            return entityManager.GetEntitiesForAspect(aspect);
        }

        public void Update(float deltaTime)
        {
            foreach (var systems in systemManager.SystemsByPriority())
            {
                entityManager.ProcessQueues();

                foreach (var system in systems)
                {
                    system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime);
                }
            }

            systemManager.ProcessQueues();
        }
    }
}

Add method for querying active entities

Add method for querying active entities


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Starboard">
//   Copyright © 2011 All Rights Reserved
// </copyright>
// <summary>
//   AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------

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

// 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("starboard-remote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("starboard-remote")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]

[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Starboard">
//   Copyright © 2011 All Rights Reserved
// </copyright>
// <summary>
//   AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------

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

// 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("starboard-remote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ascend")]
[assembly: AssemblyProduct("starboard-remote")]
[assembly: AssemblyCopyright("Copyright © Ascend 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]

[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]

Change remote app version to v0.1

Change remote app version to v0.1


// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;

namespace MiniCube
{
    /// <summary>
    /// Simple MiniCube application using SharpDX.Toolkit.
    /// </summary>
    class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
#if NETFX_CORE
        [MTAThread]
#else
        [STAThread]
#endif
        static void Main()
        {
            using (var program = new SphereGame())
                program.Run();
        }
    }
}

// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;

namespace MiniCube
{
    /// <summary>
    /// Simple MiniCube application using SharpDX.Toolkit.
    /// </summary>
    class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
#if NETFX_CORE
        [MTAThread]
#else
        [STAThread]
#endif
        static void Main()
        {
            using (var program = new MiniCubeGame())
                program.Run();
        }
    }
}

Fix compilation error in sample

[Build] Fix compilation error in sample


using System;
using System.Collections.Generic;
using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens;

namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers
{
    public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver
    {
        private readonly IEnumerable<Type> _functionTypeSamples;

        private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap;

        public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples)
        {
            _functionTypeSamples = functionTypeSamples;

            _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap);
        }

        public Type Resolve(FunctionCall functionCall)
        {
            Type result;

            return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result)
                       ? null
                       : result;
        }

        private IDictionary<string, Type> InitializeFunctionNameToTypeMap()
        {
            var result = new Dictionary<string, Type>();

            foreach (var functionTypeSample in _functionTypeSamples)
            {
                // TODO: Scan sample's assembly for function types
                // TODO: Fill result with type names without "Function" suffix
            }

            return result;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Manisero.DSLExecutor.Domain.FunctionsDomain;
using Manisero.DSLExecutor.Extensions;
using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens;

namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers
{
    public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver
    {
        private readonly IEnumerable<Type> _functionTypeSamples;

        private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap;

        public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples)
        {
            _functionTypeSamples = functionTypeSamples;

            _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap);
        }

        public Type Resolve(FunctionCall functionCall)
        {
            Type result;

            return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result)
                       ? null
                       : result;
        }

        private IDictionary<string, Type> InitializeFunctionNameToTypeMap()
        {
            var result = new Dictionary<string, Type>();

            var assembliesToScan = _functionTypeSamples.Select(x => x.Assembly).Distinct();
            var typesToScan = assembliesToScan.SelectMany(x => x.GetTypes());

            foreach (var type in typesToScan)
            {
                var functionDefinitionImplementation = type.GetGenericInterfaceDefinitionImplementation(typeof(IFunction<>));

                if (functionDefinitionImplementation == null)
                {
                    continue;
                }

                // TODO: Fill result with type names without "Function" suffix
            }

            return result;
        }
    }
}

Implement scanning assemblies for function types


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

using Microsoft.MixedReality.Toolkit.Physics;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Input
{
    /// <summary>
    /// The default implementation of IMixedRealityRaycastProvider.
    /// </summary>
    public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider
    {
        public DefaultRaycastProvider(
            IMixedRealityServiceRegistrar registrar,
            IMixedRealityInputSystem inputSystem,
            MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile)
        { }

        /// <inheritdoc />
        public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
        {
            var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
            hitInfo = new MixedRealityRaycastHit(physicsHit);
            return result;
        }

        /// <inheritdoc />
        public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
        {
            var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
            hitInfo = new MixedRealityRaycastHit(physicsHit);
            return result;
        }
    }
}

Add missing copyright header text.

Add missing copyright header text.


using System;
using UIKit;

namespace MyTrips.iOS
{
    public partial class TripSummaryViewController : UIViewController
    {
		public ViewModel.CurrentTripViewModel ViewModel { get; set; }

		public TripSummaryViewController(IntPtr handle) : base(handle) { }

		public override void ViewDidLoad()
		{
			lblDateTime.Text = $"{DateTime.Now.ToString("M")}  {DateTime.Now.ToString("t")}";
			lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}";
			lblDuration.Text = ViewModel.ElapsedTime;
			lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}";

			lblDistance.Alpha = 0;
			lblDuration.Alpha = 0;
			lblTopSpeed.Alpha = 0;
			lblFuelConsumed.Alpha = 0;
		}

		public override void ViewDidAppear(bool animated)
		{
			base.ViewDidAppear(animated);

			lblDistance.FadeIn(0.4, 0.1f);
			lblDuration.FadeIn(0.4, 0.2f);
			lblTopSpeed.FadeIn(0.4, 0.3f);
			lblFuelConsumed.FadeIn(0.4, 0.4f);
		}

		async partial void BtnClose_TouchUpInside(UIButton sender)
		{
			await DismissViewControllerAsync(true);
			await ViewModel.SaveRecordingTripAsync();
		}
	}
}

using System;
using UIKit;

namespace MyTrips.iOS
{
    public partial class TripSummaryViewController : UIViewController
    {
		public ViewModel.CurrentTripViewModel ViewModel { get; set; }

		public TripSummaryViewController(IntPtr handle) : base(handle) { }

		public override void ViewDidLoad()
		{
			lblDateTime.Text = $"{DateTime.Now.ToString("M")}  {DateTime.Now.ToString("t")}";
			lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}";
			lblDuration.Text = ViewModel.ElapsedTime;
			lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}";

			lblDistance.Alpha = 0;
			lblDuration.Alpha = 0;
			lblTopSpeed.Alpha = 0;
			lblFuelConsumed.Alpha = 0;
		}

		public override void ViewDidAppear(bool animated)
		{
			base.ViewDidAppear(animated);

			lblDistance.FadeIn(0.4, 0.1f);
			lblDuration.FadeIn(0.4, 0.2f);
			lblTopSpeed.FadeIn(0.4, 0.3f);
			lblFuelConsumed.FadeIn(0.4, 0.4f);
		}

		async partial void BtnClose_TouchUpInside(UIButton sender)
		{
			await ViewModel.SaveRecordingTripAsync();
			await DismissViewControllerAsync(true);
		}
	}
}

Save trip before dismissing summary.

[iOS] Save trip before dismissing summary.


using Nito.AsyncEx;
using WalletWasabi.Crypto;

namespace WalletWasabi.Io
{
	public class MutexIoManager : IoManager
	{
		public MutexIoManager(string filePath) : base(filePath)
		{
			var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(1, 7);

			// https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
			// On a server that is running Terminal Services, a named system mutex can have two levels of visibility.
			// If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions.
			// If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created.
			// In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server.
			// If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\".
			// Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes,
			// and both are visible to all processes in the terminal server session.
			// That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.
			Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}");
		}

		public AsyncMutex Mutex { get; }
	}
}

using Nito.AsyncEx;
using WalletWasabi.Crypto;

namespace WalletWasabi.Io
{
	public class MutexIoManager : IoManager
	{
		public MutexIoManager(string filePath) : base(filePath)
		{
			var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(0, 7);

			// https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
			// On a server that is running Terminal Services, a named system mutex can have two levels of visibility.
			// If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions.
			// If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created.
			// In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server.
			// If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\".
			// Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes,
			// and both are visible to all processes in the terminal server session.
			// That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.
			Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}");
		}

		public AsyncMutex Mutex { get; }
	}
}

Fix off by one bug

Fix off by one bug


using FluentAssertions;
using MergableMigrations.EF6;
using MergableMigrations.Specification.Implementation;
using System;
using System.Linq;
using Xunit;

namespace Mathematicians.UnitTests
{
    public class SqlGeneratorTests
    {
        [Fact]
        public void CanGenerateSql()
        {
            var migrations = new Migrations();
            var migrationHistory = new MigrationHistory();
            var sqlGenerator = new SqlGenerator(migrations, migrationHistory);
            var sql = sqlGenerator.Generate();

            sql.Length.Should().Be(3);
            sql[0].Should().Be("CREATE DATABASE [Mathematicians]");
            sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]");
            sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]");
        }
    }
}

using FluentAssertions;
using MergableMigrations.EF6;
using MergableMigrations.Specification;
using MergableMigrations.Specification.Implementation;
using System;
using System.Linq;
using Xunit;

namespace Mathematicians.UnitTests
{
    public class SqlGeneratorTests
    {
        [Fact]
        public void CanGenerateSql()
        {
            var migrations = new Migrations();
            var migrationHistory = new MigrationHistory();
            var sqlGenerator = new SqlGenerator(migrations, migrationHistory);
            var sql = sqlGenerator.Generate();

            sql.Length.Should().Be(3);
            sql[0].Should().Be("CREATE DATABASE [Mathematicians]");
            sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]");
            sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]");
        }

        [Fact]
        public void GeneratesNoSqlWhenUpToDate()
        {
            var migrations = new Migrations();
            var migrationHistory = GivenCompleteMigrationHistory(migrations);
            var sqlGenerator = new SqlGenerator(migrations, migrationHistory);
            var sql = sqlGenerator.Generate();

            sql.Length.Should().Be(0);
        }

        private MigrationHistory GivenCompleteMigrationHistory(Migrations migrations)
        {
            var model = new ModelSpecification();
            migrations.AddMigrations(model);
            return model.MigrationHistory;
        }
    }
}

Test for migrations up to date.

Test for migrations up to date.


using System;
using System.Threading;

namespace Criteo.Profiling.Tracing.Utils
{
    /// <summary>
    /// Thread-safe random long generator.
    ///
    /// See "Correct way to use Random in multithread application"
    /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application
    /// </summary>
    internal static class RandomUtils
    {
        private static int seed = Environment.TickCount;

        private static readonly ThreadLocal<Random> rand = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));

        public static long NextLong()
        {
            return (long)((rand.Value.NextDouble() * 2.0 - 1.0) * long.MaxValue);
        }

    }
}

using System;
using System.Threading;

namespace Criteo.Profiling.Tracing.Utils
{
    /// <summary>
    /// Thread-safe random long generator.
    ///
    /// See "Correct way to use Random in multithread application"
    /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application
    /// </summary>
    internal static class RandomUtils
    {
        private static int _seed = Guid.NewGuid().GetHashCode();

        private static readonly ThreadLocal<Random> LocalRandom = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref _seed)));

        public static long NextLong()
        {
            var buffer = new byte[8];
            LocalRandom.Value.NextBytes(buffer);
            return BitConverter.ToInt64(buffer, 0);
        }

    }
}

Change random to avoid identical seed

Change random to avoid identical seed

It seems it is possible for two processes started at the exact same time to get the same seed.
This could be the case for IIS where 2 handlers are started simultaneously.

Change-Id: I156fac5fe8c91c0931d38b0b6e5fe5cfb0e83665


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

namespace NuPack {
    public class PackageAuthoring {
        private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" },
                                                                              StringComparer.OrdinalIgnoreCase);

        public static void Main(string[] args) {
            // Review: Need to use a command-line parsing library instead of parsing it this way.
            string executable = Path.GetFileName(Environment.GetCommandLineArgs().First());
            string Usage = String.Format(CultureInfo.InvariantCulture,
                "Usage: {0} <manifest-file>", executable);
            if (!args.Any()) {
                Console.Error.WriteLine(Usage);
                return;
            }

            try {
                // Parse the arguments. The last argument is the content to be added to the package
                var manifestFile = args.First();
                PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile);
                builder.Created = DateTime.Now;
                builder.Modified = DateTime.Now;
                var outputFile = String.Join(".", builder.Id, builder.Version, "nupack");

                // Remove the output file or the package spec might try to include it (which is default behavior)
                builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path)));

                using (Stream stream = File.Create(outputFile)) {
                    builder.Save(stream);
                }

                Console.WriteLine("{0} created successfully", outputFile);
            }
            catch (Exception exception) {
                Console.Error.WriteLine(exception.Message);
            }
        }
    }
}

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

namespace NuPack {
    public class PackageAuthoring {
        private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" },
                                                                              StringComparer.OrdinalIgnoreCase);

        public static void Main(string[] args) {
            // Review: Need to use a command-line parsing library instead of parsing it this way.
            string executable = Path.GetFileName(Environment.GetCommandLineArgs().First());
            string Usage = String.Format(CultureInfo.InvariantCulture,
                "Usage: {0} <manifest-file>", executable);
            if (!args.Any()) {
                Console.Error.WriteLine(Usage);
                return;
            }

            try {
                var manifestFile = args.First();
                string outputDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory();
                PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile);
                builder.Created = DateTime.Now;
                builder.Modified = DateTime.Now;
                var outputFile = String.Join(".", builder.Id, builder.Version, "nupack");

                // Remove the output file or the package spec might try to include it (which is default behavior)
                builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path)));

                string outputPath = Path.Combine(outputDirectory, outputFile);

                using (Stream stream = File.Create(outputPath)) {
                    builder.Save(stream);
                }

                Console.WriteLine("{0} created successfully", outputPath);
            }
            catch (Exception exception) {
                Console.Error.WriteLine(exception.Message);
            }
        }
    }
}

Allow output directory to be specified as a second parameter.


// 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.Collections.Generic;
using System.Threading.Tasks;
using osu.Framework.Statistics;

namespace osu.Framework.Allocation
{
    /// <summary>
    /// A queue which batches object disposal on threadpool threads.
    /// </summary>
    internal static class AsyncDisposalQueue
    {
        private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal");

        private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();

        private static Task runTask;

        public static void Enqueue(IDisposable disposable)
        {
            lock (disposal_queue)
                disposal_queue.Enqueue(disposable);

            if (runTask?.Status < TaskStatus.Running)
                return;

            runTask = Task.Run(() =>
            {
                IDisposable[] itemsToDispose;

                lock (disposal_queue)
                {
                    itemsToDispose = disposal_queue.ToArray();
                    disposal_queue.Clear();
                }

                foreach (var item in itemsToDispose)
                {
                    last_disposal.Value = item.ToString();
                    item.Dispose();
                }
            });
        }
    }
}

// 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.Collections.Generic;
using System.Threading.Tasks;
using osu.Framework.Statistics;

namespace osu.Framework.Allocation
{
    /// <summary>
    /// A queue which batches object disposal on threadpool threads.
    /// </summary>
    internal static class AsyncDisposalQueue
    {
        private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal");

        private static readonly List<IDisposable> disposal_queue = new List<IDisposable>();

        private static Task runTask;

        public static void Enqueue(IDisposable disposable)
        {
            lock (disposal_queue)
                disposal_queue.Add(disposable);

            if (runTask?.Status < TaskStatus.Running)
                return;

            runTask = Task.Run(() =>
            {
                IDisposable[] itemsToDispose;

                lock (disposal_queue)
                {
                    itemsToDispose = disposal_queue.ToArray();
                    disposal_queue.Clear();
                }

                foreach (var item in itemsToDispose)
                {
                    last_disposal.Value = item.ToString();
                    item.Dispose();
                }
            });
        }
    }
}

Make the queue into a list

Make the queue into a list


using System.Diagnostics;
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
	public class PerformanceCounterTest
	{
		[Fact]
		public void Performance_counter_without_instance_name()
		{
			var performanceCounter = new PerformanceCounter("Memory", "Available Bytes");

			var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
				PerformanceCounterConfig.Build("Memory", "Available Bytes"));

			monitor.GetValue()
				.Should()
				.BeGreaterThan(0)
				.And.BeApproximately(performanceCounter.NextValue(), 500000,
					"Because memory usage can change between the two values");
		}

		[Fact]
		public void Performance_counter_with_instance_name()
		{
			var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName);

			var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
				PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName));

			monitor.GetValue()
				.Should()
				.BeGreaterThan(0)
				.And.BeApproximately(performanceCounter.NextValue(), 500000,
					"Because memory usage can change between the two values");
		}
	}
}

using System.Diagnostics;
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
	public class PerformanceCounterTest
	{
		[Fact]
		public void Performance_counter_without_instance_name()
		{
			var performanceCounter = new PerformanceCounter("Memory", "Available Bytes");

			var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
				PerformanceCounterConfig.Build("Memory", "Available Bytes"));

			monitor.GetValue()
				.Should()
				.BeGreaterThan(0)
				.And.BeApproximately(performanceCounter.NextValue(), 1000000,
					"Because memory usage can change between the two values");
		}

		[Fact]
		public void Performance_counter_with_instance_name()
		{
			var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName);

			var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
				PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName));

			monitor.GetValue()
				.Should()
				.BeGreaterThan(0)
				.And.BeApproximately(performanceCounter.NextValue(), 1000000,
					"Because memory usage can change between the two values");
		}
	}
}

Make performance counter tests more stable


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace mvcWebApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            string domain =
                Request.Url.Scheme +
                System.Uri.SchemeDelimiter +
                Request.Url.Host +
                (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);

            // NICE-TO-HAVE Sort images by height.
            string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images");
            string[] files = Directory.EnumerateFiles(imagesDir).Select(p => domain + "/Images/" + Path.GetFileName(p)).ToArray();

            ViewBag.ImageVirtualPaths = files;

            return View();
        }

    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace mvcWebApp.Controllers
{
    public class HomeController : Controller
    {

        public string domain
        {
            get
            {
                string domain =
                    Request.Url.Scheme +
                    System.Uri.SchemeDelimiter +
                    Request.Url.Host +
                    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);

                return domain;
            }
        }

        //
        // GET: /Home/

        public ActionResult Index()
        {

            // NICE-TO-HAVE Sort images by height.
            string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images");
            string[] files = Directory.EnumerateFiles(imagesDir).Select(p => this.domain + "/Images/" + Path.GetFileName(p)).ToArray();

            ViewBag.ImageVirtualPaths = files;

            return View();
        }

    }
}

Make domain a property for reuse.

Make domain a property for reuse.


using System.Collections.Generic;
using Nest.Domain;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System;
using System.Linq;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	public interface ISearchShardsResponse : IResponse
	{
		[JsonProperty("shards")]
		IEnumerable<IEnumerable<SearchShard>> Shards { get; }

		[JsonProperty("nodes")]
		IDictionary<string, SearchNode> Nodes { get; }
	}

	public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
	{
		public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }
		public IDictionary<string, SearchNode> Nodes { get; internal set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchNode
	{
		[JsonProperty("name")]
		public string Name { get; set; }
		[JsonProperty("transport_address")]
		public string TransportAddress { get; set; }

	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchShard
	{
		[JsonProperty("name")]
		public string State { get; set;}
		[JsonProperty("primary")]
		public bool Primary { get; set;}
		[JsonProperty("node")]
		public string Node { get; set;}
		[JsonProperty("relocating_node")]
		public string RelocatingNode { get; set;}
		[JsonProperty("shard")]
		public int Shard { get; set;}
		[JsonProperty("index")]
		public string Index { get; set;}
	}
}

using Nest.Domain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	public interface ISearchShardsResponse : IResponse
	{
		[JsonProperty("shards")]
		IEnumerable<IEnumerable<SearchShard>> Shards { get; }

		[JsonProperty("nodes")]
		IDictionary<string, SearchNode> Nodes { get; }
	}

	public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
	{
		public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }

		public IDictionary<string, SearchNode> Nodes { get; internal set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchNode
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("transport_address")]
		public string TransportAddress { get; set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchShard
	{
		[JsonProperty("state")]
		public string State { get; set; }

		[JsonProperty("primary")]
		public bool Primary { get; set; }

		[JsonProperty("node")]
		public string Node { get; set; }

		[JsonProperty("relocating_node")]
		public string RelocatingNode { get; set; }

		[JsonProperty("shard")]
		public int Shard { get; set; }

		[JsonProperty("index")]
		public string Index { get; set; }
	}
}

Fix wrong property mapping in SearchShard


using System.Collections.Generic;
using Glimpse.Core.Extensibility;
using Nancy.Bootstrapper;

namespace Glimpse.Nancy
{
    public class GlimpseRegistrations : IApplicationRegistrations
    {
        public GlimpseRegistrations()
        {
            AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly);
        }

        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations
        {
            get
            {
                var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>();
                var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>();
                return new[] {
                    new CollectionTypeRegistration(typeof(ITab), tabs),
                    new CollectionTypeRegistration(typeof(IInspector), inspectors)
                };
            }
        }

        public IEnumerable<InstanceRegistration> InstanceRegistrations
        {
            get { return null; }
        }

        public IEnumerable<TypeRegistration> TypeRegistrations
        {
            get { return null; }
        }
    }
}

using System.Collections.Generic;
using Glimpse.Core.Extensibility;
using Nancy.Bootstrapper;

namespace Glimpse.Nancy
{
    public class GlimpseRegistrations : IRegistrations
    {
        public GlimpseRegistrations()
        {
            AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly);
        }

        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations
        {
            get
            {
                var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>();
                var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>();
                return new[] {
                    new CollectionTypeRegistration(typeof(ITab), tabs),
                    new CollectionTypeRegistration(typeof(IInspector), inspectors)
                };
            }
        }

        public IEnumerable<InstanceRegistration> InstanceRegistrations
        {
            get { return null; }
        }

        public IEnumerable<TypeRegistration> TypeRegistrations
        {
            get { return null; }
        }
    }
}

Remove usage of obsolete IApplicationRegistration


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

namespace BatteryCommander.Web.Models
{
    public class EvaluationListViewModel
    {
        public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>();

        [Display(Name = "Delinquent > 60 Days")]
        public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count();

        public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count();

        [Display(Name = "Next 30")]
        public int Next30 => Evaluations.Where(_ => _.ThruDate > DateTime.Today).Where(_ => DateTime.Today.AddDays(30) < _.ThruDate).Count();

        [Display(Name = "Next 60")]
        public int Next60 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(30)).Where(_ => DateTime.Today.AddDays(60) <= _.ThruDate).Count();

        [Display(Name = "Next 90")]
        public int Next90 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(60)).Where(_ => DateTime.Today.AddDays(90) <= _.ThruDate).Count();
    }
}

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

namespace BatteryCommander.Web.Models
{
    public class EvaluationListViewModel
    {
        public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>();

        [Display(Name = "Delinquent > 60 Days")]
        public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count();

        public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count();

        [Display(Name = "Next 30")]
        public int Next30 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count();

        [Display(Name = "Next 60")]
        public int Next60 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count();

        [Display(Name = "Next 90")]
        public int Next90 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count();
    }
}

Fix logic on 30/60/90 day buckets

Fix logic on 30/60/90 day buckets


using System;
using System.Linq;
using FluentAssertions;
using NSaga;
using Xunit;

namespace Tests
{
    public class NamespaceTests
    {
        [Fact]
        public void NSaga_Contains_Only_One_Namespace()
        {
            //Arrange
            var assembly = typeof(ISagaMediator).Assembly;

            // Act
            var namespaces = assembly.GetTypes()
                                     .Where(t => t.IsPublic)
                                     .Select(t => t.Namespace)
                                     .Distinct()
                                     .ToList();

            // Assert
            var names = String.Join(", ", namespaces);
            namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'");
        }

        [Fact]
        public void PetaPoco_Stays_Internal()
        {
            //Arrange
            var petapocoTypes = typeof(SqlSagaRepository).Assembly
                                .GetTypes()
                                .Where(t => !String.IsNullOrEmpty(t.Namespace))
                                .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase))
                                .Where(t => t.IsPublic)
                                .ToList();

            petapocoTypes.Should().BeEmpty();
        }
    }
}

using System;
using System.Linq;
using FluentAssertions;
using NSaga;
using Xunit;

namespace Tests
{
    public class NamespaceTests
    {
        [Fact]
        public void NSaga_Contains_Only_One_Namespace()
        {
            //Arrange
            var assembly = typeof(ISagaMediator).Assembly;

            // Act
            var namespaces = assembly.GetTypes()
                                     .Where(t => t.IsPublic)
                                     .Select(t => t.Namespace)
                                     .Distinct()
                                     .ToList();

            // Assert
            var names = String.Join(", ", namespaces);
            namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'");
        }

        [Fact]
        public void PetaPoco_Stays_Internal()
        {
            //Arrange
            var petapocoTypes = typeof(SqlSagaRepository).Assembly
                                .GetTypes()
                                .Where(t => !String.IsNullOrEmpty(t.Namespace))
                                .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase))
                                .Where(t => t.IsPublic)
                                .ToList();

            petapocoTypes.Should().BeEmpty();
        }

        [Fact]
        public void TinyIoc_Stays_Internal()
        {
            typeof(TinyIoCContainer).IsPublic.Should().BeFalse();
        }
    }
}

Test to check tinyioc is internal

Test to check tinyioc is internal


@{
    var version = "";
    var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString();

    if(Yio.Data.Constants.VersionConstant.Patch == 0) {
        version = Yio.Data.Constants.VersionConstant.Release.ToString();
    } else {
        version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." +
            Yio.Data.Constants.VersionConstant.Patch.ToString();
    }
}

About

            Curl your paw round your dick, and get clicking!

            Filled with furry (and more) porn, stripped from many sources — tumblr, e621, 4chan, 8chan, etc. — Yiff.co is the never-ending full-width stream of NSFW images. Built by Zyrio.

            Running on version @version '@(versionName)'

@{
    var version = "";
    var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString();

    if(Yio.Data.Constants.VersionConstant.Patch == 0) {
        version = Yio.Data.Constants.VersionConstant.Release.ToString();
    } else {
        version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." +
            Yio.Data.Constants.VersionConstant.Patch.ToString();
    }
}

About

            Curl your paw round your dick, and get clicking!

            Filled with furry (and more) porn, stripped from many sources — tumblr, e621, 4chan, 8chan, etc. — Yiff.co is the never-ending full-width stream of NSFW images.

            Built by Zyrio. Licensed under the MIT license, with code available on Zyrio Git. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money.

            Running on version @version '@(versionName)'

Add license and disclaimer to About panel


// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using System.Security.Permissions;

namespace Microsoft.Azure.Commands.Profile
{
    [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")]
    [Alias("Enable-AzureDataCollection")]
    public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet
    {
        protected override void ProcessRecord()
        {
            SetDataCollectionProfile(true);
        }

        protected void SetDataCollectionProfile(bool enable)
        {
            var profile = GetDataCollectionProfile();
            profile.EnableAzureDataCollection = enable;
            SaveDataCollectionProfile();
        }
    }
}

// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using System.Security.Permissions;

namespace Microsoft.Azure.Commands.Profile
{
    [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")]
    [Alias("Enable-AzureDataCollection")]
    public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet
    {
        protected override void BeginProcessing()
        {
            // do not call begin processing there is no context needed for this cmdlet
        }

        protected override void ProcessRecord()
        {
            SetDataCollectionProfile(true);
        }

        protected void SetDataCollectionProfile(bool enable)
        {
            var profile = GetDataCollectionProfile();
            profile.EnableAzureDataCollection = enable;
            SaveDataCollectionProfile();
        }
    }
}

Fix data collection cmdlets to not require login


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

using System;
using System.Linq;

namespace osu.Game.Rulesets.Osu.Mods
{
    public class OsuModSingleTap : InputBlockingMod
    {
        public override string Name => @"Single Tap";
        public override string Acronym => @"ST";
        public override string Description => @"You must only use one key!";
        public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray();

        protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action;
    }
}

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

using System;
using System.Linq;

namespace osu.Game.Rulesets.Osu.Mods
{
    public class OsuModSingleTap : InputBlockingMod
    {
        public override string Name => @"Single Tap";
        public override string Acronym => @"SG";
        public override string Description => @"You must only use one key!";
        public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray();

        protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action;
    }
}

Change "single tap" mod acronym to not conflict with "strict tracking"


// 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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseMapPool : LadderTestCase
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            var round = Ladder.Groupings.First(g => g.Name == "Finals");

            Add(new MapPoolScreen(round));
        }
    }

    public class MapPoolScreen : CompositeDrawable
    {
        public MapPoolScreen(TournamentGrouping round)
        {
            FillFlowContainer maps;

            InternalChildren = new Drawable[]
            {
                maps = new FillFlowContainer
                {
                    Direction = FillDirection.Full,
                    RelativeSizeAxes = Axes.Both,
                },
            };

            foreach (var b in round.Beatmaps)
                maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo));
        }
    }
}

// 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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Screens;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
using OpenTK;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseMapPool : LadderTestCase
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            var round = Ladder.Groupings.First(g => g.Name == "Finals");

            Add(new MapPoolScreen(round));
        }
    }

    public class MapPoolScreen : OsuScreen
    {
        public MapPoolScreen(TournamentGrouping round)
        {
            FillFlowContainer maps;

            InternalChildren = new Drawable[]
            {
                maps = new FillFlowContainer
                {
                    Spacing = new Vector2(20),
                    Padding = new MarginPadding(50),
                    Direction = FillDirection.Full,
                    RelativeSizeAxes = Axes.Both,
                },
            };

            foreach (var b in round.Beatmaps)
                maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo)
                {
                    Anchor = Anchor.TopCentre,
                    Origin = Anchor.TopCentre,
                });
        }
    }
}

Make map pool layout more correct

Make map pool layout more correct


using System;
using System.Dynamic;

namespace BobTheBuilder
{
    public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
    {
        private readonly IDynamicBuilder<T> wrappedBuilder;
        private readonly IArgumentStore argumentStore;

        internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore)
        {
            if (wrappedBuilder == null)
            {
                throw new ArgumentNullException("wrappedBuilder");
            }

            if (argumentStore == null)
            {
                throw new ArgumentNullException("argumentStore");
            }

            this.wrappedBuilder = wrappedBuilder;
            this.argumentStore = argumentStore;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            return wrappedBuilder.TryInvokeMember(binder, args, out result);
        }

        public T Build()
        {
            return wrappedBuilder.Build();
        }
    }
}

using System;
using System.Dynamic;
using System.Linq;

namespace BobTheBuilder
{
    public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
    {
        private readonly IDynamicBuilder<T> wrappedBuilder;
        private readonly IArgumentStore argumentStore;

        internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore)
        {
            if (wrappedBuilder == null)
            {
                throw new ArgumentNullException("wrappedBuilder");
            }

            if (argumentStore == null)
            {
                throw new ArgumentNullException("argumentStore");
            }

            this.wrappedBuilder = wrappedBuilder;
            this.argumentStore = argumentStore;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (binder.Name == "With")
            {
                ParseNamedArgumentValues(binder.CallInfo, args);
            }

            return wrappedBuilder.TryInvokeMember(binder, args, out result);
        }

        private void ParseNamedArgumentValues(CallInfo callInfo, object[] args)
        {
            var argumentName = callInfo.ArgumentNames.First();
            argumentName = argumentName.First().ToString().ToUpper() + argumentName.Substring(1);
            argumentStore.SetMemberNameAndValue(argumentName, args.First());
        }

        public T Build()
        {
            return wrappedBuilder.Build();
        }
    }
}

Add support for named argument parsing.

Add support for named argument parsing.

The argument name munging is not pretty and needs improving (and perhaps
breaking out into another class?), but it does at least currently work.


// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
#if !PCL
using System.Diagnostics;
using JetBrains.Annotations;
using NodaTime.Utility;

namespace NodaTime.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="Stopwatch"/>.
    /// </summary>
    public static class StopwatchExtensions
    {
        /// <summary>
        /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>.
        /// </summary>
        /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param>
        /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns>
        public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch)
        {
            Preconditions.CheckNotNull(stopwatch, nameof(stopwatch));
            return stopwatch.Elapsed.ToDuration();
        }
    }
}
#endif

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

namespace NodaTime.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="Stopwatch"/>.
    /// </summary>
    public static class StopwatchExtensions
    {
        /// <summary>
        /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>.
        /// </summary>
        /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param>
        /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns>
        public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch)
        {
            Preconditions.CheckNotNull(stopwatch, nameof(stopwatch));
            return stopwatch.Elapsed.ToDuration();
        }
    }
}

Enable stopwatch extension methods for .NET Core

I suspect Stopwatch wasn't available in earlier versions of .NET
Standard - or possibly not in netstandard1.1 when we targeted that.
But it's fine for netstandard1.3.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RedCard.API.Contexts;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace RedCard.API.Controllers
{
    [Route("api/[controller]")]
    public class StatsController : Controller
    {
        public StatsController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        readonly ApplicationDbContext _dbContext;

        [HttpGet]
        public IActionResult RedCardCountForCountry()
        {
            var redCardCount = _dbContext.Players
                .GroupBy(player => player.Country)
                .Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) })
                .ToArray();

            return new ObjectResult(new { redCardCountForCountry = redCardCount });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RedCard.API.Contexts;
using RedCard.API.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace RedCard.API.Controllers
{
    [Route("api/[controller]")]
    public class StatsController : Controller
    {
        public StatsController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        readonly ApplicationDbContext _dbContext;

        [Route("redcards")]
        [HttpGet]
        public IActionResult RedCardCountForCountry()
        {
            Func<IGrouping<string, Player>, object> getRedCardsForCountry =
                (grouping) => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) };

            var redCardCount = _CardsForCountry(getRedCardsForCountry);

            return new ObjectResult(new { redCardCountForCountry = redCardCount });
        }

        [Route("yellowcards")]
        [HttpGet]
        public IActionResult YellowCardCountForCountry()
        {
            Func<IGrouping<string, Player>, object> getYellowCardsForCountry =
                (grouping) => new { country = grouping.Key, yellowCardCount = grouping.Sum(player => player.YellowCards) };

            var yellowCardCount = _CardsForCountry(getYellowCardsForCountry);

            return new ObjectResult(new { yellowCardCountForCountry = yellowCardCount });
        }

        IEnumerable<object> _CardsForCountry(Func<IGrouping<string, Player>, object> getInfo)
        {
            return _dbContext.Players
                .GroupBy(player => player.Country)
                .Select(getInfo)
                .ToArray();
        }
    }
}

Add group by yellow cards count

Add group by yellow cards count


using System;
using System.Collections;
using UnityEngine;

namespace LunaClient.Utilities
{
    public class CoroutineUtil
    {
        public static void StartDelayedRoutine(string routineName, Action action, float delayInSec)
        {
            Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec));
        }

        private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec)
        {
            yield return new WaitForSeconds(delayInSec);
            try
            {
                action();
            }
            catch (Exception e)
            {
                LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}");
            }
        }
    }
}

using System;
using System.Collections;
using UnityEngine;

namespace LunaClient.Utilities
{
    public class CoroutineUtil
    {
        public static void StartDelayedRoutine(string routineName, Action action, float delayInSec)
        {
            Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec));
        }

        private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec)
        {
            if (delayInSec > 0)
                yield return new WaitForSeconds(delayInSec);
            try
            {
                action();
            }
            catch (Exception e)
            {
                LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}");
            }
        }
    }
}

Allow coroutines of 0 sec delay

Allow coroutines of 0 sec delay


namespace uSync
{
    /// <summary>
    ///  we only have this class, so there is a dll in the root
    ///  uSync package.
    ///
    ///  With a root dll, the package can be stopped from installing
    ///  on .netframework sites.
    /// </summary>
    public static class uSync
    {
        // private static string Welcome = "uSync all the things";
    }
}

using System;

using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Migrations;
using Umbraco.Cms.Infrastructure.Packaging;

namespace uSync
{
    /// <summary>
    ///  we only have this class, so there is a dll in the root
    ///  uSync package.
    ///
    ///  With a root dll, the package can be stopped from installing
    ///  on .netframework sites.
    /// </summary>
    public static class uSync
    {
        public static string PackageName = "uSync";
        // private static string Welcome = "uSync all the things";
    }

    /// <summary>
    ///  A package migration plan, allows us to put uSync in the list
    ///  of installed packages. we don't actually need a migration
    ///  for uSync (doesn't add anything to the db). but by doing
    ///  this people can see that it is insalled.
    /// </summary>
    public class uSyncMigrationPlan : PackageMigrationPlan
    {
        public uSyncMigrationPlan() :
            base(uSync.PackageName)
        { }

        protected override void DefinePlan()
        {
            To<SetupuSync>(new Guid("65735030-E8F2-4F34-B28A-2201AF9792BE"));
        }
    }

    public class SetupuSync : PackageMigrationBase
    {
        public SetupuSync(
            IPackagingService packagingService,
            IMediaService mediaService,
            MediaFileManager mediaFileManager,
            MediaUrlGeneratorCollection mediaUrlGenerators,
            IShortStringHelper shortStringHelper,
            IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
            IMigrationContext context)
            : base(packagingService, mediaService, mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, context)
        {
        }

        protected override void Migrate()
        {
            // we don't actually need to do anything, but this means we end up
            // on the list of installed packages.
        }
    }
}

Add blank package migration (to get into the list)


using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;

namespace Web.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public async Task<string> Index()
        {
            var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));

            var response = await client.GetAsync("api/home");
            if (response.IsSuccessStatusCode)
            {
                using(var stream = await response.Content.ReadAsStreamAsync())
                {
                    var model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream);
                    return $"{model.Name}, {model.StringValue}, {model.Id}";
                }
            }

            return "Failed";
        }
    }
}

using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Web.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public async Task<string> Index()
        {
            var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await client.GetAsync("api/home");
            if (response.IsSuccessStatusCode)
            {
                using(var stream = await response.Content.ReadAsStreamAsync())
                {
                    ProtobufModelDto model = null;
                    if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf")
                    {
                        model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream);
                        return $"{model.Name}, {model.StringValue}, {model.Id}";
                    }

                    var content = await response.Content.ReadAsStringAsync();
                    model = JsonConvert.DeserializeObject<ProtobufModelDto>(content);
                    return $"{model.Name}, {model.StringValue}, {model.Id}";
                }
            }

            return "Failed";
        }
    }
}

Add check for content type when parsing in client. Fallback to Json if Protobuf is not available


using System;
using System.IO;
using System.Runtime.CompilerServices;
using ExpressionToCodeLib;
using Xunit;
//requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core

namespace ExpressionToCodeTest
{
    public class ExceptionsSerialization
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        static void IntentionallyFailingMethod()
            => PAssert.That(() => false);

        [Fact]
        public void PAssertExceptionIsSerializable()
            => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod);

        static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod)
        {
            var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod);

            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            var ms = new MemoryStream();
            formatter.Serialize(ms, original);
            var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray()));
            Assert.Equal(original.ToString(), deserialized.ToString());
        }
    }
}

using System;
using System.IO;
using System.Runtime.CompilerServices;
using ExpressionToCodeLib;
using Xunit;
//requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core

namespace ExpressionToCodeTest
{
    public class ExceptionsSerialization
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        static void IntentionallyFailingMethod()
            => PAssert.That(() => false);

        [Fact]
        public void PAssertExceptionIsSerializable()
            => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod);

#pragma warning disable SYSLIB0011 // BinaryFormatter is Obsolete
        static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod)
        {
            var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod);
            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            var ms = new MemoryStream();
            formatter.Serialize(ms, original);
            var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray()));
            Assert.Equal(original.ToString(), deserialized.ToString());
        }
#pragma warning restore SYSLIB0011
    }
}

Disable warnings about obsoletion since the point is testing the obsolete stuff still works


////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using log4net;
using Careminster;
using OpenMetaverse;

namespace Careminster
{
    public interface IAttachmentsService
    {
        string Get(string id);
        void Store(string id, string data);
    }
}

////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;

namespace OpenSim.Services.Interfaces
{
    public interface IAttachmentsService
    {
        string Get(string id);
        void Store(string id, string data);
    }
}

Remove some usings that stopped compilation


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using IntermediatorBotSample.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;

namespace IntermediatorBotSample.Controllers.Api
{
    [Route("api/[controller]")]
    public class ConversationsController : Controller
    {
        [HttpGet]
        public IEnumerable<Conversation> Get()
        {
            return Builder<Conversation>.CreateListOfSize(2)
                .All()
                    .With(o =>  o.ConversationInformation   = Builder<ConversationInformation>.CreateNew().Build())
                    .With(o =>  o.ConversationReference     = Builder<ConversationReference>.CreateNew().Build())
                    .With(o =>  o.UserInformation           = Builder<UserInformation>.CreateNew().Build())
                .Build()
                .ToList();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using IntermediatorBotSample.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;

namespace IntermediatorBotSample.Controllers.Api
{
    [Route("api/[controller]")]
    public class ConversationsController : Controller
    {
        [HttpGet]
        public IEnumerable<Conversation> Get(int convId, int top)
        {
            var channels = new[] { "facebook", "skype", "skype for business", "directline" };
            var random = new RandomGenerator();

            return Builder<Conversation>.CreateListOfSize(5)
                .All()
                    .With(o =>  o.ConversationInformation   = Builder<ConversationInformation>.CreateNew()
                    .With(ci => ci.MessagesCount = random.Next(2, 30))
                    .With(ci => ci.SentimentScore = random.Next(0.0d, 1.0d))
                    .Build())
                    .With(o =>  o.ConversationReference     = Builder<ConversationReference>.CreateNew()
                    .With(cr => cr.ChannelId = channels[random.Next(0, channels.Count())])
                    .Build())
                    .With(o =>  o.UserInformation           = Builder<UserInformation>.CreateNew()
                    .Build())
                .Build()
                .ToList();
        }

        //TODO: Retrieve ALL the conversation

        //TOOD: Forward conersation

        //TODO: DELETE Conversation = immediate kill by conversationId
    }
}

Add intermediate comments to help explain what to do


//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------

datablock AudioProfile(MinigunProjectileImpactSound)
{
	filename = "share/sounds/rotc/impact1.wav";
	description = AudioDefault3D;
	preload = true;
};

datablock AudioProfile(MinigunProjectileFlybySound)
{
	filename = "share/sounds/rotc/flyby1.wav";
	description = AudioCloseLooping3D;
	preload = true;
};

datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
	filename = "share/sounds/rotc/flyby1.wav";
	description = AudioClose3D;
	preload = true;
};

//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------

datablock AudioProfile(MinigunProjectileImpactSound)
{
	filename = "share/sounds/rotc/impact1.wav";
	description = AudioDefault3D;
	preload = true;
};

datablock AudioProfile(MinigunProjectileFlybySound)
{
	filename = "share/sounds/rotc/flyby1.wav";
	description = AudioCloseLooping3D;
	preload = true;
};

datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
	filename = "share/sounds/rotc/ricochet1-1.wav";
	alternate[0] = "share/sounds/rotc/ricochet1-1.wav";
	alternate[1] = "share/sounds/rotc/ricochet1-2.wav";
	alternate[2] = "share/sounds/rotc/ricochet1-3.wav";
	alternate[3] = "share/sounds/rotc/ricochet1-4.wav";
	alternate[4] = "share/sounds/rotc/ricochet1-5.wav";
	alternate[5] = "share/sounds/rotc/ricochet1-6.wav";
	description = AudioClose3D;
	preload = true;
};

Use different sounds for minigun's missed enemy effect.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EchoServer
{
	class Program
	{
		static void Main(string[] args)
		{
			Task main = MainAsync(args);
			main.Wait();
		}

		static async Task MainAsync(string[] args)
		{
			Console.WriteLine("Starting server");

			CancellationToken cancellationToken = new CancellationTokenSource().Token;

			TcpListener listener = new TcpListener(IPAddress.IPv6Loopback, 8080);

			listener.Start();

			TcpClient client = await listener.AcceptTcpClientAsync();
			client.ReceiveTimeout = 30;
			NetworkStream stream = client.GetStream();
			StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
			StreamReader reader = new StreamReader(stream, Encoding.ASCII);

			while (true)
			{
				string line = await reader.ReadLineAsync();
				Console.WriteLine($"Received {line}");
				await writer.WriteLineAsync(line);

				if (cancellationToken.IsCancellationRequested)
					break;
			}

			listener.Stop();
		}
	}
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EchoServer
{
	class Program
	{
		static void Main(string[] args)
		{
			Task main = MainAsync(args);
			main.Wait();
		}

		static async Task MainAsync(string[] args)
		{
			Console.WriteLine("Starting server");

			TcpListener server = new TcpListener(IPAddress.IPv6Loopback, 8080);
			Console.WriteLine("Starting listener");
			server.Start();

			while (true)
			{
				TcpClient client = await server.AcceptTcpClientAsync();

				Task.Factory.StartNew(() => HandleConnection(client));
			}

			server.Stop();
		}

		static async Task HandleConnection(TcpClient client)
		{
			Console.WriteLine($"New connection from {client.Client.RemoteEndPoint}");
			client.ReceiveTimeout = 30;
			client.SendTimeout = 30;

			NetworkStream stream = client.GetStream();
			StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
			StreamReader reader = new StreamReader(stream, Encoding.ASCII);

			string line = await reader.ReadLineAsync();
			Console.WriteLine($"Received {line}");
			await writer.WriteLineAsync(line);
		}
	}
}

Move client handling into a separate method.


using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;

namespace CppSharp.Passes
{
    public class FieldToPropertyPass : TranslationUnitPass
    {
        public override bool VisitClassDecl(Class @class)
        {
            if (@class.CompleteDeclaration != null)
                return VisitClassDecl(@class.CompleteDeclaration as Class);

            return base.VisitClassDecl(@class);
        }

        public override bool VisitFieldDecl(Field field)
        {
            if (!VisitDeclaration(field))
                return false;

            var @class = field.Namespace as Class;
            if (@class == null)
                return false;

            if (ASTUtils.CheckIgnoreField(field))
                return false;

            // Check if we already have a synthetized property.
            var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field);
            if (existingProp != null)
                return false;

            field.GenerationKind = GenerationKind.Internal;

            var prop = new Property
            {
                Name = field.Name,
                Namespace = field.Namespace,
                QualifiedType = field.QualifiedType,
                Access = field.Access,
                Field = field
            };

            // do not rename value-class fields because they would be
            // generated as fields later on even though they are wrapped by properties;
            // that is, in turn, because it's cleaner to write
            // the struct marshalling logic just for properties
            if (!prop.IsInRefTypeAndBackedByValueClassField())
                field.Name = Generator.GeneratedIdentifier(field.Name);

            @class.Properties.Add(prop);

            Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name,
                field.Name);

            return false;
        }
    }
}

using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;

namespace CppSharp.Passes
{
    public class FieldToPropertyPass : TranslationUnitPass
    {
        public override bool VisitClassDecl(Class @class)
        {
            if (@class.CompleteDeclaration != null)
                return VisitClassDecl(@class.CompleteDeclaration as Class);

            return base.VisitClassDecl(@class);
        }

        public override bool VisitFieldDecl(Field field)
        {
            if (!VisitDeclaration(field))
                return false;

            var @class = field.Namespace as Class;
            if (@class == null)
                return false;

            if (ASTUtils.CheckIgnoreField(field))
                return false;

            // Check if we already have a synthetized property.
            var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field);
            if (existingProp != null)
                return false;

            field.GenerationKind = GenerationKind.Internal;

            var prop = new Property
            {
                Name = field.Name,
                Namespace = field.Namespace,
                QualifiedType = field.QualifiedType,
                Access = field.Access,
                Field = field
            };

            // do not rename value-class fields because they would be
            // generated as fields later on even though they are wrapped by properties;
            // that is, in turn, because it's cleaner to write
            // the struct marshalling logic just for properties
            if (!prop.IsInRefTypeAndBackedByValueClassField())
                field.Name = Generator.GeneratedIdentifier(field.Name);

            @class.Properties.Add(prop);

            Diagnostics.Debug($"Property created from field: {field.QualifiedName}");

            return false;
        }
    }
}

Clean up the diagnostic in FieldToProperty pass.


using System;
using NUnit.Framework;

namespace HttpMock.Unit.Tests
{
	[TestFixture]
	public class HttpFactoryTests
	{
		[Test]
		public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed()
		{
			var serverFactory = new HttpServerFactory();

			var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting()));
			IHttpServer server1, server2 = null;
			server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
			try
			{
				server1.Start();
				server1.Dispose();
				server1 = null;

				server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
				Assert.DoesNotThrow(server2.Start);
			}
			finally
			{
				if (server1 != null)
				{
					server1.Dispose();
				}
				if (server2 != null)
				{
					server2.Dispose();
				}
			}
		}
	}
}

using System;
using NUnit.Framework;

namespace HttpMock.Unit.Tests
{
	[TestFixture]
	public class HttpFactoryTests
	{
		[Test]
		[Ignore ("Makes the test suite flaky (???)")]
		public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed()
		{
			var serverFactory = new HttpServerFactory();

			var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting()));
			IHttpServer server1, server2 = null;
			server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
			try
			{
				server1.Start();
				server1.Dispose();
				server1 = null;

				server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
				Assert.DoesNotThrow(server2.Start);
			}
			finally
			{
				if (server1 != null)
				{
					server1.Dispose();
				}
				if (server2 != null)
				{
					server2.Dispose();
				}
			}
		}
	}
}

Mark evil test as ignore, again

UnitTest: Mark evil test as ignore, again


// 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 osu.Game.Rulesets.Osu.Difficulty.Preprocessing;

namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
    /// <summary>
    /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
    /// </summary>
    public class Speed : Skill
    {
        protected override double SkillMultiplier => 1400;
        protected override double StrainDecayBase => 0.3;

        protected override double StrainValueOf(OsuDifficultyHitObject current)
        {
            double distance = current.TravelDistance + current.JumpDistance;
            return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
        }
    }
}

// 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 osu.Game.Rulesets.Osu.Difficulty.Preprocessing;

namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
    /// <summary>
    /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
    /// </summary>
    public class Speed : Skill
    {
        protected override double SkillMultiplier => 1400;
        protected override double StrainDecayBase => 0.3;

        protected override double StrainValueOf(OsuDifficultyHitObject current)
        {
            double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
            return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
        }
    }
}

Make sure distance is clamped to sane values


using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Qart.Testing
{
    public class TestSystem
    {
        public IDataStore DataStorage { get; private set; }

        public TestSystem(IDataStore dataStorage)
        {
            DataStorage = dataStorage;
        }

        public TestCase GetTestCase(string id)
        {
            return new TestCase(id, this);
        }

        public IEnumerable<TestCase> GetTestCases()
        {
            return DataStorage.GetAllGroups().Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this));
        }
    }
}

using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Qart.Testing
{
    public class TestSystem
    {
        public IDataStore DataStorage { get; private set; }

        public TestSystem(IDataStore dataStorage)
        {
            DataStorage = dataStorage;
        }

        public TestCase GetTestCase(string id)
        {
            return new TestCase(id, this);
        }

        public IEnumerable<TestCase> GetTestCases()
        {
            return DataStorage.GetAllGroups().Concat(new[]{"."}).Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this));
        }
    }
}

Fix for GetTestCases not returning current folder


using System;
using System.ComponentModel.DataAnnotations;

namespace JoyOI.OnlineJudge.Models
{
    public class VirtualJudgeUser
    {
        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        public Guid Id { get; set; }

        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        /// <value>The username.</value>
        [MaxLength(32)]
        public string Username { get; set; }

        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        [MaxLength(64)]
        public string Password { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use.
        /// </summary>
        /// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value>
        public bool IsInUse { get; set; }

        /// <summary>
        /// Gets or sets the source.
        /// </summary>
        /// <value>The source of this user.</value>
        public ProblemSource Source { get; set; }
    }
}

using System;
using System.ComponentModel.DataAnnotations;

namespace JoyOI.OnlineJudge.Models
{
    public class VirtualJudgeUser
    {
        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        public Guid Id { get; set; }

        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        /// <value>The username.</value>
        [MaxLength(32)]
        public string Username { get; set; }

        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        [MaxLength(64)]
        public string Password { get; set; }

        /// <summary>
        /// Gets or sets the locker id.
        /// </summary>
        /// <value>The locker id.</value>
        public Guid? LockerId { get; set; }

        /// <summary>
        /// Gets or sets the source.
        /// </summary>
        /// <value>The source of this user.</value>
        public ProblemSource Source { get; set; }
    }
}

Refactor virtual judge user table schema


// 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 osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Beatmaps.Drawables
{
    public class BeatmapSetCover : Sprite
    {
        private readonly BeatmapSetInfo set;
        private readonly BeatmapSetCoverType type;

        public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover)
        {
            if (set == null)
                throw new ArgumentNullException(nameof(set));

            this.set = set;
            this.type = type;
        }

        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            string resource = null;

            switch (type)
            {
                case BeatmapSetCoverType.Cover:
                    resource = set.OnlineInfo.Covers.Cover;
                    break;
                case BeatmapSetCoverType.Card:
                    resource = set.OnlineInfo.Covers.Card;
                    break;
                case BeatmapSetCoverType.List:
                    resource = set.OnlineInfo.Covers.List;
                    break;
            }

            if (resource != null)
                Texture = textures.Get(resource);
        }
    }

    public enum BeatmapSetCoverType
    {
        Cover,
        Card,
        List,
    }
}

// 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 osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Beatmaps.Drawables
{
    public class BeatmapSetCover : Sprite
    {
        private readonly BeatmapSetInfo set;
        private readonly BeatmapSetCoverType type;

        public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover)
        {
            if (set == null)
                throw new ArgumentNullException(nameof(set));

            this.set = set;
            this.type = type;
        }

        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            string resource = null;

            switch (type)
            {
                case BeatmapSetCoverType.Cover:
                    resource = set.OnlineInfo.Covers.Cover;
                    break;
                case BeatmapSetCoverType.Card:
                    resource = set.OnlineInfo.Covers.Card;
                    break;
                case BeatmapSetCoverType.List:
                    resource = set.OnlineInfo.Covers.List;
                    break;
            }

            if (resource != null)
                Texture = textures.Get(resource);
        }
    }

    public enum BeatmapSetCoverType
    {
        Cover,
        Card,
        List,
    }
}

Use LargeTextureStore for online retrievals


// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using System.Collections.Generic;

namespace EOLib.Net.Handlers
{
	public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder
	{
		private readonly List<FamilyActionPair> _inBandPackets;
		private readonly List<FamilyActionPair> _outOfBandPackets;

		public PacketHandlingTypeFinder()
		{
			_inBandPackets = new List<FamilyActionPair>
			{
				new FamilyActionPair(PacketFamily.Init, PacketAction.Init),
				new FamilyActionPair(PacketFamily.Account, PacketAction.Reply),
				new FamilyActionPair(PacketFamily.Character, PacketAction.Reply),
				new FamilyActionPair(PacketFamily.Login, PacketAction.Reply)
			};

			_outOfBandPackets = new List<FamilyActionPair>
			{
				new FamilyActionPair(PacketFamily.Connection, PacketAction.Player)
			};
		}

		public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action)
		{
			var fap = new FamilyActionPair(family, action);

			if (_inBandPackets.Contains(fap))
				return PacketHandlingType.InBand;

			if (_outOfBandPackets.Contains(fap))
				return PacketHandlingType.OutOfBand;

			return PacketHandlingType.NotHandled;
		}
	}
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

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

namespace EOLib.Net.Handlers
{
	public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder
	{
		private readonly List<FamilyActionPair> _inBandPackets;
		private readonly List<FamilyActionPair> _outOfBandPackets;

		public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers)
		{
			_inBandPackets = new List<FamilyActionPair>
			{
				new FamilyActionPair(PacketFamily.Init, PacketAction.Init),
				new FamilyActionPair(PacketFamily.Account, PacketAction.Reply),
				new FamilyActionPair(PacketFamily.Character, PacketAction.Reply),
				new FamilyActionPair(PacketFamily.Login, PacketAction.Reply)
			};

			_outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList();
		}

		public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action)
		{
			var fap = new FamilyActionPair(family, action);

			if (_inBandPackets.Contains(fap))
				return PacketHandlingType.InBand;

			if (_outOfBandPackets.Contains(fap))
				return PacketHandlingType.OutOfBand;

			return PacketHandlingType.NotHandled;
		}
	}
}

Use registered types for Out of Band handlers in packet handling type finder

Replaces manually built up collection. Should be able to eventually have just 1 collection where it is either in-band or not in-band.