using System;
using System.Collections.Generic;
using System.Web.Http;

namespace TokenAuthentification.Controllers
{
    [RoutePrefix("api/orders")]
    public class OrdersController : ApiController
    {
        [Authorize]
        [Route("")]
        public IHttpActionResult Get()
        {
            return Ok(Order.CreateOrders());
        }

    }

    #region Helpers

    public class Order
    {
        public int OrderID { get; set; }
        public string CustomerName { get; set; }
        public string ShipperCity { get; set; }
        public Boolean IsShipped { get; set; }

        public static List<Order> CreateOrders()
        {
            List<Order> OrderList = new List<Order>
            {
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };

            return OrderList;
        }
    }

    #endregion
}

Add order controller for authentified users


using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers.API
{
    [Route("api/[controller]"), Authorize]
    public class WeaponsController : Controller
    {
        private readonly Database db;

        public WeaponsController(Database db)
        {
            this.db = db;
        }

        [HttpGet]
        public async Task<IEnumerable<dynamic>> Get()
        {
            // GET: api/weapons

            return
                await db
                .Weapons
                .Select(_ => new
                {
                    _.Id,
                    _.OpticSerial,
                    _.OpticType,
                    _.Serial,
                    _.StockNumber,
                    _.Type,
                    _.UnitId
                })
                .ToListAsync();
        }

        [HttpPost]
        public async Task<IActionResult> Post(Weapon weapon)
        {
            await db.Weapons.AddAsync(weapon);

            await db.SaveChangesAsync();

            return Ok();
        }
    }
}

Add simple controller for weapons

Add simple controller for weapons


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

// General Information about an assembly is controlled through the following set of attributes.
// Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle("Certify - SSL Certificate Manager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Certify")]
[assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")]

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

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

// General Information about an assembly is controlled through the following set of attributes.
// Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle("Certify - SSL Certificate Manager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Certify")]
[assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")]

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

Increment release number to 2.0.14

Increment release number to 2.0.14


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

using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;

namespace osu.Game.Rulesets.Catch.Tests
{
    public class TestSceneCatchReplay : TestSceneCatchPlayer
    {
        protected override bool Autoplay => true;

        private const int object_count = 10;

        [Test]
        public void TestReplayCatcherPositionIsFramePerfect()
        {
            AddUntilStep("caught all fruits", () => Player.ScoreProcessor.Combo.Value == object_count);
        }

        protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
        {
            var beatmap = new Beatmap
            {
                BeatmapInfo =
                {
                    Ruleset = ruleset,
                }
            };

            beatmap.ControlPointInfo.Add(0, new TimingControlPoint());

            for (int i = 0; i < object_count / 2; i++)
            {
                beatmap.HitObjects.Add(new Fruit
                {
                    StartTime = (i + 1) * 1000,
                    X = 0
                });
                beatmap.HitObjects.Add(new Fruit
                {
                    StartTime = (i + 1) * 1000 + 1,
                    X = CatchPlayfield.WIDTH
                });
            }

            return beatmap;
        }
    }
}

Add a failing test to check catch replay accuracy


using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using A2BBCommon.Models;
using A2BBCommon;
using A2BBAPI.Data;
using IdentityModel.Client;
using A2BBAPI.DTO;
using Microsoft.Extensions.Logging;
using A2BBAPI.Models;
using System.Collections.Generic;
using A2BBAPI.Utils;
using static A2BBAPI.Utils.ClaimsUtils;
using Microsoft.Extensions.Caching.Memory;

namespace A2BBAPI.Controllers
{
    /// <summary>
    /// Controller to manage user devices.
    /// </summary>
    [Produces("application/json")]
    [Route("api/me/inout")]
    [Authorize("User")]
    public class MeInOutController : Controller
    {
        #region Private fields
        /// <summary>
        /// The DB context.
        /// </summary>
        private readonly A2BBApiDbContext _dbContext;

        /// <summary>
        /// The logger.
        /// </summary>
        private readonly ILogger _logger;
        #endregion

        #region Public methods
        /// <summary>
        /// Create a new isntance of this class.
        /// </summary>
        /// <param name="dbContext">The DI DB context.</param>
        /// <param name="loggerFactory">The DI logger factory.</param>
        public MeInOutController(A2BBApiDbContext dbContext, ILoggerFactory loggerFactory)
        {
            _dbContext = dbContext;
            _logger = loggerFactory.CreateLogger<MeController>();
        }

        [HttpGet]
        public ResponseWrapper<IEnumerable<InOut>> ListAll()
        {
            return new ResponseWrapper<IEnumerable<InOut>>(_dbContext.InOut.Where(io => io.Device.UserId == User.Claims.FirstOrDefault(c => c.Type == "sub").Value), Constants.RestReturn.OK);
        }

        [HttpGet]
        [Route("{deviceId}")]
        public ResponseWrapper<IEnumerable<InOut>> ListOfSpecificDevice([FromRoute] int deviceId)
        {
            return new ResponseWrapper<IEnumerable<InOut>>(_dbContext.InOut.Where(io => io.Device.UserId == User.Claims.FirstOrDefault(c => c.Type == "sub").Value && io.DeviceId == deviceId),
                Constants.RestReturn.OK);
        }
        #endregion
    }
}

Add user controller on API to check in/outs.


using Mollie.Api.Client;
using Mollie.Api.Models;
using NUnit.Framework;
using System.Net.Http;
using System.Threading.Tasks;

namespace Mollie.Tests.Unit.Client {
    [TestFixture]
    public class PaymentMethodClientTests : BaseClientTests {
        private const string defaultPaymentMethodJsonResponse = @"{
            ""count"": 13,
            ""_embedded"": {
                ""methods"": [
                    {
                         ""resource"": ""method"",
                         ""id"": ""ideal"",
                         ""description"": ""iDEAL""
                    }
                ]
            }
        }";

        [Test]
        public async Task GetPaymentMethodListAsync_NoAmountParameter_QueryStringIsEmpty() {
            // Given: We make a request to retrieve a order without wanting any extra data
            var mockHttp = this.CreateMockHttpMessageHandler(HttpMethod.Get, $"{BaseMollieClient.ApiEndPoint}methods/all", defaultPaymentMethodJsonResponse);
            HttpClient httpClient = mockHttp.ToHttpClient();
            PaymentMethodClient paymentMethodClient = new PaymentMethodClient("abcde", httpClient);

            // When: We send the request
            await paymentMethodClient.GetAllPaymentMethodListAsync();

            // Then
            mockHttp.VerifyNoOutstandingExpectation();
        }

        [Test]
        public async Task GetPaymentMethodListAsync_AmountParameterIsAdded_QueryStringContainsAmount() {
            // Given: We make a request to retrieve a order without wanting any extra data
            var mockHttp = this.CreateMockHttpMessageHandler(HttpMethod.Get, $"{BaseMollieClient.ApiEndPoint}methods/all?amount[value]=100.00&amount[currency]=EUR", defaultPaymentMethodJsonResponse);
            HttpClient httpClient = mockHttp.ToHttpClient();
            PaymentMethodClient paymentMethodClient = new PaymentMethodClient("abcde", httpClient);

            // When: We send the request
            await paymentMethodClient.GetAllPaymentMethodListAsync(amount: new Amount("EUR", 100));

            // Then
            mockHttp.VerifyNoOutstandingExpectation();
        }
    }
}

Add unit tests to verify that the amount parameters are added to the query string when they are added as parameter


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;

namespace MultipleKinectsPlatform.MultipleKinectsPlatform.Data
{
    [DataContract(Name="Joint")]
    public class Joint
    {
        [DataMember]
        public float X;

        [DataMember]
        public float Y;

        [DataMember]
        public float Z;

        public Joint(float i_x, float i_y, float i_z)
        {
            X = i_x;
            Y = i_y;
            Z = i_z;
        }
    }
}

Add a new datatype for joints

Add a new datatype for joints


using System.Collections.Generic;
using System.Net.Http;

namespace Amazon.S3
{
    internal static class HttpResponseMessageExtensions
    {
        public static Dictionary<string, string> GetProperties(this HttpResponseMessage response)
        {
#if NET5_0
            var result = new Dictionary<string, string>(16);

            foreach (var header in response.Headers)
            {
                result.Add(header.Key, string.Join(';', header.Value));
            }

            foreach (var header in response.Content.Headers)
            {
                result.Add(header.Key, string.Join(';', header.Value));
            }

#else
            var baseHeaders = response.Headers.NonValidated;
            var contentHeaders = response.Content.Headers.NonValidated;

            var result = new Dictionary<string, string>(baseHeaders.Count + contentHeaders.Count);

            foreach (var header in baseHeaders)
            {
                result.Add(header.Key, header.Value.ToString());
            }

            foreach (var header in contentHeaders)
            {
                result.Add(header.Key, header.Value.ToString());
            }
#endif

            return result;
        }
    }
}

[S3] Add shared helper to flatten response headers


using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using SolidworksAddinFramework.Geometry;
using SolidWorks.Interop.sldworks;

namespace SolidworksAddinFramework
{
    public static class RefAxisExtensions
    {
        public static Edge3 Edge(this IRefAxis axis)
        {
            var axisParams = axis.GetRefAxisParams().DirectCast<double[]>();
            return new Edge3(new Vector3((float) axisParams[0], (float) axisParams[1], (float) axisParams[2])
                ,new Vector3((float) axisParams[3], (float) axisParams[4], (float) axisParams[5]));
        }
    }
}

Add method to return Edge from IRefAxis

Add method to return Edge from IRefAxis


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

namespace NBi.Core.Members
{
    public class PredefinedMembersFactory
    {
        private readonly ICollection<BuilderRegistration> registrations;

        public PredefinedMembersFactory()
        {
            registrations = new List<BuilderRegistration>();
            RegisterDefaults();
        }

        private void RegisterDefaults()
        {
            Register(PredefinedMembers.DaysOfWeek, new DaysOfWeekBuilder());
            Register(PredefinedMembers.MonthsOfYear, new MonthsOfYearBuilder());
        }

        /// <summary>
        /// Register a new builder for corresponding types. If a builder was already existing for this association, it's replaced by the new one
        /// </summary>
        /// <param name="sutType">Type of System Under Test</param>
        /// <param name="ctrType">Type of Constraint</param>
        /// <param name="builder">Instance of builder deicated for these types of System Under Test and Constraint</param>
        public void Register(PredefinedMembers value, IPredefinedMembersBuilder builder)
        {
            if (IsHandling(value))
                registrations.FirstOrDefault(reg => reg.Value == value).Builder = builder;
            else
                registrations.Add(new BuilderRegistration(value, builder));
        }

        private bool IsHandling(PredefinedMembers value)
        {
            var existing = registrations.FirstOrDefault(reg => reg.Value == value);
            return (existing != null);
        }

        private class BuilderRegistration
        {
            public PredefinedMembers Value { get; set; }
            public IPredefinedMembersBuilder Builder { get; set; }

            public BuilderRegistration(PredefinedMembers value, IPredefinedMembersBuilder builder)
            {
                Value = value;
                Builder = builder;
            }
        }

        /// <summary>
        /// Create a new instance of a test case
        /// </summary>
        /// <param name="sutXml"></param>
        /// <param name="ctrXml"></param>
        /// <returns></returns>
        public IEnumerable<string> Instantiate(PredefinedMembers value, string cultureName)
        {

            if (!Enum.IsDefined(typeof(PredefinedMembers), value))
                throw new ArgumentOutOfRangeException();
            if (string.IsNullOrEmpty(cultureName))
                throw new ArgumentNullException("cultureName");

            var culture = new CultureInfo(cultureName);

            IPredefinedMembersBuilder builder = null;

            //Look for registration ...
            var registration = registrations.FirstOrDefault(reg => reg.Value == value);
            if (registration == null)
                throw new ArgumentException(string.Format("'{0}' has no builder registred.", Enum.GetName(typeof(PredefinedMembers), value)));

            //Get Builder and initiate it
            builder = registration.Builder;
            builder.Setup(culture);

            //Build
            builder.Build();
            var list = builder.GetResult();

            return list;
        }
    }
}

Define the factory to handle the build of list


using System;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Projects;

namespace MonoDevelop.ResXEditor.Gui
{
	class ResXEditorDisplayBinding : IViewDisplayBinding
	{
		public string Name {
			get {
				return "ResX Editor";
			}
		}

		public bool CanUseAsDefault {
			get { return true; }
		}

		//AssemblyBrowserViewContent viewContent = null;

		//internal AssemblyBrowserViewContent GetViewContent ()
		//{
		//	if (viewContent == null || viewContent.IsDisposed) {
		//		viewContent = new AssemblyBrowserViewContent ();
		//		viewContent.Disposed += HandleDestroyed;
		//	}
		//	return viewContent;
		//}

		//void HandleDestroyed (object sender, EventArgs e)
		//{
		//	((AssemblyBrowserViewContent)sender).Disposed -= HandleDestroyed;
		//	this.viewContent = null;
		//}

		public bool CanHandle (FilePath fileName, string mimeType, Project ownerProject)
		{
            return mimeType == "text/microsoft-resx";
		}

		public ViewContent CreateContent (FilePath fileName, string mimeType, Project ownerProject)
		{
			return null;
		}
	}
}

Add file that wasn't in repo

Add file that wasn't in repo


using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGameUtils.UI
{
    /// <summary>
    /// Represents a rectangular button that can be clicked in a game.
    /// </summary>
    public class Button : DrawableGameComponent
    {
        public SpriteFont Font { get; set; }
        public Color TextColor { get; set; }
        public string Text { get; set; }
        public Rectangle Bounds { get; set; }
        public Color BackgroundColor { get; set; }

        private Texture2D ButtonTexture;

        private SpriteBatch spriteBatch;

        public Button(Game game, SpriteFont font, Color textColor, string text,
                      Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game)
        {
            this.Font = font;
            this.TextColor = textColor;
            this.Text = text;
            this.Bounds = bounds;
            this.BackgroundColor = backgroundColor;
            this.spriteBatch = spriteBatch;
        }

        public override void Initialize()
        {
            this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1);
            this.ButtonTexture.SetData<Color>(new Color[] { Color.White });

            base.Initialize();
        }

        public override void Draw(GameTime gameTime)
        {
            // Draw the button background.
            spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor);

            // Draw the button text.
            spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor);

            base.Draw(gameTime);
        }
    }
}

Add a very basic class to allow placing buttons on-screen.


using System;
using System.Collections.Generic;
using Calculation.ExtensionMethods;
using Operators = Calculation.ShuntingYardOperators;

namespace Calculation
{
    class SmashTheState
    {
        public int OpCount
        {
            get { return opStack.Count; }
        }

        public bool NextIsFunction
        {
            get { return NextTypeIs(TokenType.Function); }
        }

        readonly Stack<CalcToken> opStack;
        readonly Stack<double> output;
        readonly Action<string, double> assignVariable;

        public SmashTheState() : this(null) {}

        public SmashTheState(Action<string, double> assignVar)
        {
            opStack = new Stack<CalcToken>();
            output = new Stack<double>();
            assignVariable = assignVar;
        }

        public void Push(CalcToken t)
        {
            opStack.Push(t);
        }
        public void Push(double n)
        {
            output.Push(n);
        }

        public CalcToken PopOpStack()
        {
            return opStack.Pop();
        }
        public double PopOutput()
        {
            return output.Pop();
        }

        public TokenType OpPeekType()
        {
            return opStack.PeekType();
        }

        public bool NextTypeIs(TokenType type)
        {
            if (opStack.Count > 0)
                return opStack.PeekType() == type;

            return false;
        }

        // Mostly boilerplate, the heart of the ToPopStack-decision is contained in the next function.
        public bool ToPopStack(CalcOpToken newToken)
        {
            if (opStack.Count > 0)
            {
                var stackToken = opStack.Peek();
                // Only pop operators from the stack.
                if (stackToken.Type == TokenType.Operator)
                {
                    var stackOp = ((CalcOpToken)stackToken).OpType;
                    var newOp = newToken.OpType;
                    return ToPopStack(newOp, stackOp);
                }
            }

            return false;
        }

        static bool ToPopStack(OperatorType newOp, OperatorType stackOp)
        {
            // If op on the stack has higher precedence, it needs to get popped.
            if (Operators.ComparePrecedence(newOp, stackOp) == 1)
                return true;

            // It also needs to get popped when they have equal precedence and the op is left-associative.
            if (Operators.ComparePrecedence(newOp, stackOp) == 0 &&
                Operators.GetAssociativity(newOp) == Operators.Associativity.Left)
                return true;

            return false;
        }
    }
}

Prepare ShuntingYard for a state object

IrcCalc: Prepare ShuntingYard for a state object

With the prospect of assignment being a valid calculation we need to
expose variable assignment to the ShuntingYard calculator. I was already
passing state aroung (2 stacks) and managing a 3rd state object seemed
like too much clutter. Hence the collection of state in a single object.


using Newtonsoft.Json;
using NUnit.Framework;

namespace JsonSubTypes.Tests
{
    [TestFixture]
    public class DeeplyNestedDeserializationTests
    {
        [JsonConverter(typeof(JsonSubtypes), nameof(SubTypeClass.Discriminator))]
        [JsonSubtypes.KnownSubType(typeof(SubTypeClass), "SubTypeClass")]
        public abstract class MainClass
        {
        }

        public class SubTypeClass : MainClass
        {
            public string Discriminator => "SubTypeClass";

            public MainClass Child { get; set; }
        }

        [Test]
        public void DeserializingDeeplyNestedJsonWithHighMaxDepthParsesCorrectly()
        {
            var root = new SubTypeClass();

            var current = root;
            for (var i = 0; i < 64; i++)
            {
                var child = new SubTypeClass();
                current.Child = child;
                current = child;
            }

            var json = JsonConvert.SerializeObject(root);

            var obj = JsonConvert.DeserializeObject<MainClass>(json, new JsonSerializerSettings { MaxDepth = 65 });
            Assert.That(obj, Is.Not.Null);
        }
    }
}

Add failing test of deserializing deeply nested JSON with higher-than-default MaxDepth set


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using RapID.ClassLibrary;

namespace RapID.Auth
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // callback& app
            var callback = DecodeUrlString(args[0]);
            var app = Crypt.Decrypt(Crypt.Decrypt(Crypt.Decrypt(args[1])));
            var waitFrm = new Wait(callback, app);
            Application.Run(waitFrm);
        }

        /*
         * (C) 2015 @ogi from StackOverflow
         * Original Post: http://stackoverflow.com/questions/1405048/how-do-i-decode-a-url-parameter-using-c
         */
        private static string DecodeUrlString(string url)
        {
            string newUrl;
            while ((newUrl = Uri.UnescapeDataString(url)) != url)
                url = newUrl;
            return newUrl;
        }
    }
}

Reset the Application Entry Point

Reset the Application Entry Point


// Copyright 2021 Google LLC
//
// 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
//
//     https://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 Google.Cloud.Tools.Common;
using System;
using System.IO;

namespace Google.Cloud.Tools.ReleaseManager
{
    public sealed class UpdateDependenciesCommand : CommandBase
    {
        public UpdateDependenciesCommand()
            : base("update-dependencies", "Updates dependencies for all APIs")
        {
        }

        protected override void ExecuteImpl(string[] args)
        {
            var catalog = ApiCatalog.Load();
            var apiNames = catalog.CreateIdHashSet();

            foreach (var api in catalog.Apis)
            {
                GenerateProjectsCommand.UpdateDependencies(catalog, api);
                var layout = DirectoryLayout.ForApi(api.Id);
                GenerateProjectsCommand.GenerateMetadataFile(layout.SourceDirectory, api);
                GenerateProjectsCommand.GenerateProjects(layout.SourceDirectory, api, apiNames);
            }
            string formatted = catalog.FormatJson();
            File.WriteAllText(ApiCatalog.CatalogPath, formatted);
            Console.WriteLine("Updated apis.json");
        }
    }
}

Add tool to update all dependencies

Add tool to update all dependencies

This is typically useful after a GAX or gRPC release.


using KenticoInspector.Core;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Models;
using System;
using System.Collections.Generic;

namespace KenticoInspector.Reports.WebPartPerformanceAnalysis
{
    class Report : IReport
    {
        public string Codename => nameof(WebPartPerformanceAnalysis);

        public IList<Version> CompatibleVersions => new List<Version>
        {
            new Version("10.0"),
            new Version("11.0")
        };

        public IList<Version> IncompatibleVersions => new List<Version>();

        public string LongDescription => @"
Displays list of web parts where 'columns' property is not specified.

Web parts without specified 'columns' property must load all field from the database.

By specifying this property, you can significantly lower the data transmission from database to the server and improve the load times.

For more information, see documentation.";

        public string Name => "Web Part Performance Analysis";

        public string ShortDescription => "Shows potential optimization opportunities.";

        public IList<string> Tags => new List<string> {
            ReportTags.PortalEngine,
            ReportTags.Performance,
            ReportTags.WebParts,
        };

        public ReportResults GetResults(Guid InstanceGuid)
        {
            throw new NotImplementedException();
        }
    }
}

Add empty report for web part performance analysis


using SCPI.System;
using System.Text;
using Xunit;

namespace SCPI.Tests.System
{
    public class SYSTEM_LANGUAGE_Tests
    {
        [Theory]
        [InlineData("ENGL")]
        [InlineData("GERM")]
        public void LanguageIsSetToProperty(string expected)
        {
            // Arrange
            var cmd = new SYSTEM_LANGUAGE();

            // Act
            var result = cmd.Parse(Encoding.ASCII.GetBytes($"{expected}\n"));

            // Assert
            Assert.Equal(expected, cmd.Language);
        }
    }
}

Add unit test for SYSTEM_LANGUAGE SCPI command


using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }
        }
    }
}

using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                // We're going to get errors - that's kinda the point of monitoring
                // No need to log every one here unless for crazy debugging
                //ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }
        }
    }
}

Comment out per-error logging, now only needed for logging


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

using NUnit.Framework;

namespace osu.Game.Rulesets.Osu.Tests
{
    [TestFixture]
    public class TestCaseOsuPlayer : Game.Tests.Visual.TestCasePlayer
    {
        public TestCaseOsuPlayer()
            : base(new OsuRuleset())
        {
        }
    }
}

Add player test for osu! ruleset

Add player test for osu! ruleset


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

using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestScenePlayerScorePreparation : OsuPlayerTestScene
    {
        protected override bool AllowFail => false;

        protected new PreparingPlayer Player => (PreparingPlayer)base.Player;

        [SetUpSteps]
        public override void SetUpSteps()
        {
            base.SetUpSteps();

            // Ensure track has actually running before attempting to seek
            AddUntilStep("wait for track to start running", () => Beatmap.Value.Track.IsRunning);
        }

        [Test]
        public void TestPreparationOnResults()
        {
            AddUntilStep("wait for preparation", () => Player.PreparationCompleted);
        }

        [Test]
        public void TestPreparationOnExit()
        {
            AddStep("exit", () => Player.Exit());
            AddUntilStep("wait for preparation", () => Player.PreparationCompleted);
        }

        protected override TestPlayer CreatePlayer(Ruleset ruleset) => new PreparingPlayer();

        public class PreparingPlayer : TestPlayer
        {
            public bool PreparationCompleted { get; private set; }

            public bool ResultsCreated { get; private set; }

            public PreparingPlayer()
                : base(true, true)
            {
            }

            protected override ResultsScreen CreateResults(ScoreInfo score)
            {
                var results = base.CreateResults(score);
                ResultsCreated = true;
                return results;
            }

            protected override Task PrepareScoreForResultsAsync(Score score)
            {
                PreparationCompleted = true;
                return base.PrepareScoreForResultsAsync(score);
            }
        }
    }
}

Add tests covering score preparation flow


using System;
using System.Threading.Tasks;
using Microsoft.R.Host.Client;

namespace Microsoft.VisualStudio.R.Package.Repl.Session {
    public static class RSessionEvaluationCommands {
        public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) {
            return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n");
        }

        public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) {
            return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n");
        }

        public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) {
            return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n");
        }

        public static Task<REvaluationResult> GetGlobalEnvironmentVariables(this IRSessionEvaluation evaluation) {
            return evaluation.EvaluateNonReentrantAsync($".rtvs.datainspect.env_vars(.GlobalEnv)\n");
        }

        public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) {
            var script = @"
vsgd <- function() {
   .External('C_vsgd', 5, 5)
}
options(device='vsgd')
";

            return evaluation.EvaluateAsync(script, reentrant: false);
        }

        private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) {
            return evaluation.EvaluateAsync(FormattableString.Invariant(commandText), reentrant: false);
        }
    }
}

using System;
using System.Threading.Tasks;
using Microsoft.R.Host.Client;

namespace Microsoft.VisualStudio.R.Package.Repl.Session {
    public static class RSessionEvaluationCommands {
        public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) {
            return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n");
        }

        public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) {
            return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n");
        }

        public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) {
            return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n");
        }

        public static Task<REvaluationResult> GetGlobalEnvironmentVariables(this IRSessionEvaluation evaluation) {
            return evaluation.EvaluateNonReentrantAsync($".rtvs.datainspect.env_vars(.GlobalEnv)\n");
        }

        public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) {
            var script = @"
.rtvs.vsgd <- function() {
   .External('C_vsgd', 5, 5)
}
options(device='.rtvs.vsgd')
";

            return evaluation.EvaluateAsync(script, reentrant: false);
        }

        private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) {
            return evaluation.EvaluateAsync(FormattableString.Invariant(commandText), reentrant: false);
        }
    }
}

Hide 'vsgd' graphic devie function from Environment window

- change 'vsgd' to '.rtvs.vsgd' to hide


using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Refactorings.Specific.Rename;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches;
using JetBrains.ReSharper.Psi;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.Refactorings.Rename
{
    [ShellFeaturePart]
    public class UnityEventTargetAtomicRenameFactory : IAtomicRenameFactory
    {
        public bool IsApplicable(IDeclaredElement declaredElement)
        {
            if (declaredElement is IMethod method)
            {
                var eventHandlerCache = declaredElement.GetSolution().GetComponent<UnityEventHandlerReferenceCache>();
                return eventHandlerCache.IsEventHandler(method);
            }

            return false;
        }

        // Disable rename completely for Unity event handlers
        public RenameAvailabilityCheckResult CheckRenameAvailability(IDeclaredElement element)
        {
            if (IsApplicable(element))
                return RenameAvailabilityCheckResult.CanNotBeRenamed;

            return RenameAvailabilityCheckResult.CanBeRenamed;
        }

        public IEnumerable<AtomicRenameBase> CreateAtomicRenames(IDeclaredElement declaredElement, string newName, bool doNotAddBindingConflicts)
        {
            return EmptyList<AtomicRenameBase>.Instance;
        }
    }
}

Disable rename for Unity event handlers

Disable rename for Unity event handlers


using System.Net;
using System.Net.Sockets;

namespace PSql.Tests
{
    internal static class TcpPort
    {
        public static bool IsListening(ushort port)
        {
            const int TimeoutMs = 1000;

            try
            {
                using var client = new TcpClient();

                return client.ConnectAsync(IPAddress.Loopback, port).Wait(TimeoutMs)
                    && client.Connected;
            }
            catch (SocketException)
            {
                return false;
            }
        }
    }
}

Add helper to check TCP port status.

Add helper to check TCP port status.


using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace BatteryCommander.Web.Controllers.API
{
    public class JobsController : ApiController
    {
        public JobsController(Database db) : base(db)
        {
            // Nothing to do here
        }

        [HttpGet]
        public IEnumerable<Schedule> List()
        {
            return JobManager.AllSchedules;
        }

        [HttpPost("{name}")]
        public IActionResult Post(String name)
        {
            JobManager.GetSchedule(name)?.Execute();

            return Ok();
        }
    }
}

Add endpoints to view jobs

Add endpoints to view jobs


using System;
using System.Linq;
using Content.Shared.Administration.Logs;
using NUnit.Framework;

namespace Content.Tests.Shared.Administration.Logs;

[TestFixture]
public class LogTypeTests
{
    [Test]
    public void Unique()
    {
        var types = Enum.GetValues<LogType>();
        var duplicates = types
            .GroupBy(x => x)
            .Where(g => g.Count() > 1)
            .Select(g => g.Key)
            .ToArray();

        Assert.That(duplicates.Length, Is.Zero, $"{nameof(LogType)} has duplicate values for: " + string.Join(", ", duplicates));
    }
}

Add unit test to check for duplicate log types


using System;
using System.Globalization;
using System.Windows.Data;

namespace Mastoon.Conveters
{
    public class DataGridContentConveter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml((string) value);
            return doc.DocumentNode.InnerText;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            => throw new NotImplementedException();
    }
}

Add content conveter to show DataGrid

:+1: Add content conveter to show DataGrid


using System;
using System.Collections.Generic;

namespace Blaze.Randomization.Lab
{
    public static class ExponentialDistribution
    {
        static readonly Random random = new Random();

        public static double Next(double mean) =>
            -mean * Math.Log(1 - random.NextDouble());
    }
}

Add class for exponential distribution

Add class for exponential distribution


#!/usr/bin/csexec -r:System.Windows.Forms.dll

using System;
using System.IO;
using System.Resources;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;

public static class Program
{
	public static void Main (string [] args)
	{
		try {
			var script = new EmptyEntriesRemover () {
				PackageName = args [1],
				CultureCode = args [2].Replace ("_", "-")
			};

			script.Run ();
		}
		catch (Exception ex) {
			Console.WriteLine (ex.Message);
		}
	}
}

internal class EmptyEntriesRemover
{
	#region Parameters

	public string CultureCode { get; set; }
	public string PackageName { get; set; }

	#endregion

	public void Run ()
	{
		try {
			// get translation files
			Directory.SetCurrentDirectory (Path.Combine (PackageName, CultureCode));
			var files = Directory.GetFiles (".",
				string.Format ("*.{0}.resx", CultureCode), SearchOption.AllDirectories);

			foreach (var file in files) {
				RemoveEmptyEntries (file);
			}
		}
		catch (Exception ex) {
			throw ex;
		}
	}

	private void RemoveEmptyEntries (string file)
	{
		try {
			var newFile = file + ".out";
			using (ResXResourceWriter resxWriter = new ResXResourceWriter (newFile)) {
				var resxReader = new ResXResourceReader(file);
				resxReader.UseResXDataNodes = true;
				foreach (DictionaryEntry entry in resxReader) {
					var node = (ResXDataNode) entry.Value;
					if (!string.IsNullOrEmpty (node.GetValue((ITypeResolutionService) null).ToString ())) {
						resxWriter.AddResource (node);
					}
				}
				resxReader.Close ();
			}

			if (new FileInfo (newFile).Length < new FileInfo (file).Length) {
				File.Delete (file);
				File.Move (newFile, file);
			}
			else {
				File.Delete (newFile);
			}
		}
		catch (Exception ex) {
			Console.WriteLine ("{0}: {1}", file, ex.Message);
		}
	}
}

Add alternate empty entries remover

WIP: Add alternate empty entries remover


// ------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Identity.Client.AppConfig;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Identity.Test.Unit.CacheTests
{
    [TestClass]
    public class ManualCacheLoadTest
    {
        // This is a manual run test to be able to load a cache file from python manually until we get automated tests across the other languages/platforms.
        [TestMethod]
        [Ignore]
        public async Task TestLoadCacheAsync()
        {
            // string authority = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/";
            string authority = "https://login.microsoftonline.com/organizations/";
            string scope = "https://graph.microsoft.com/.default";
            string clientId = "b945c513-3946-4ecd-b179-6499803a2167";
            string accountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb";

            string filePathCacheBin = @"C:\Users\mark\Downloads\python_msal_cache.bin";

            var pca = PublicClientApplicationBuilder.Create(clientId).WithAuthority(authority).Build();
            pca.UserTokenCache.DeserializeMsalV3(File.ReadAllBytes(filePathCacheBin));

            var account = await pca.GetAccountAsync(accountId).ConfigureAwait(false);
            var result = await pca.AcquireTokenSilent(new List<string> { scope }, account).ExecuteAsync().ConfigureAwait(false);

            Console.WriteLine();
        }
    }
}

Add manual test to validate python cache


using HarmonyLib;
using NUnit.Framework;
using System.Diagnostics;
using System.Reflection;

namespace HarmonyLibTests.Extras
{
	[TestFixture]
	class RetrieveOriginalMethod : TestLogger
	{
		[Test]
		public void Test0()
		{
			var harmony = new Harmony("test-original-method");

			var originalMethod = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget));
			var dummyPrefix = AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.DummyPrefix));

			_ = harmony.Patch(originalMethod, new HarmonyMethod(dummyPrefix));

			PatchTarget();
		}

		private static void ChecksStackTrace()
		{
			var st = new StackTrace(1, false);
			var method = Harmony.GetMethodFromStackframe(st.GetFrame(0));

			// Replacement will be HarmonyLibTests.Extras.RetrieveOriginalMethod.PatchTarget_Patch1
			// We should be able to go from this method, back to HarmonyLibTests.Extras.PatchTarget
			if (method is MethodInfo replacement)
			{
				var original = Harmony.GetOriginalMethod(replacement);
				Assert.NotNull(original);
				Assert.Equals(original, AccessTools.Method(typeof(RetrieveOriginalMethod), nameof(RetrieveOriginalMethod.PatchTarget)));
			}
		}

		internal static void PatchTarget()
		{
			ChecksStackTrace();
		}

		internal static void DummyPrefix()
		{

		}
	}
}

Add failing test which demonstrates bug with current implementation


using System;
using System.Collections.Generic;

namespace CBojar.Acceptors
{
	public class EnumerableAcceptor<T> : IAcceptor<T>
	{
		protected IEnumerable<T> _value;

		public EnumerableAcceptor(IEnumerable<T> value) {
			_value = value;
		}

		public IAcceptor<T> Accept(Action<T> visitor) {
			foreach(T member in _value) {
				new Acceptor<T>(member).Accept(visitor);
			}
			return this;
		}

		public IAcceptor<T> Accept<U>(Action<U> visitor) where U : T {
			foreach(T member in _value) {
				new Acceptor<T>(member).Accept(visitor);
			}
			return this;
		}

		public IAcceptor<T> Accept<U, V>(Action<V> visitor) where U : T, V {
			foreach(T member in _value) {
				new Acceptor<T>(member).Accept<U, V>(visitor);
			}
			return this;
		}
	}
}

Add Acceptor for an Enumerable of objects.


using System;

namespace DeclarativeSql.Internals
{
    /// <summary>
    /// Provides helper methods for numeric.
    /// </summary>
    internal static class NumericHelper
    {
        /// <summary>
        /// Gets the number of digits of the specified value.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <remarks>http://smdn.jp/programming/netfx/tips/get_number_of_digits/</remarks>
        public static byte GetDigit(int value)
        {
            //--- 0 is special
            if (value == 0)
                return 1;

            //--- If smaller value, dividing by 10 is faster
            if (value <= 10000)
            {
                byte digit = 1;
                while (value >= 10)
                {
                    value /= 10;
                    digit++;
                }
                return digit;
            }

            //--- When the number is large, calculates from the logarithm
            return (byte)(unchecked((byte)Math.Log10(value)) + 1);
        }
    }
}

Add helper methods for numeric

Add helper methods for numeric


using System;
using System.Linq;
using NBitcoin;
using NBitcoin.Protocol;
using NBitcoin.Protocol.Behaviors;

namespace Stratis.Bitcoin.Connection
{
    /// <summary>
    /// If the light wallet is only connected to nodes behind
    /// it cannot progress progress to the tip to get the full balance
    /// this behaviour will make sure place is kept for nodes higher then
    /// current tip.
    /// </summary>
    public class DropNodesBehaviour : NodeBehavior
    {
        private readonly ConcurrentChain chain;
        private readonly IConnectionManager connection;
        private readonly decimal dropTrashold;

        public DropNodesBehaviour(ConcurrentChain chain, IConnectionManager connectionManager)
        {
            this.chain = chain;
            this.connection = connectionManager;

            // 80% of current max connections, the last 20% will only
            // connect to nodes ahead of the current best chain
            this.dropTrashold = 0.8M;
        }

        private void AttachedNodeOnMessageReceived(Node node, IncomingMessage message)
        {
            message.Message.IfPayloadIs<VersionPayload>(version =>
            {
                var nodeGroup = this.connection.DiscoveredNodeGroup ?? this.connection.ConnectNodeGroup;
                // find how much 20% max nodes
                var connectAbove = Math.Round(nodeGroup.MaximumNodeConnection * this.dropTrashold, MidpointRounding.ToEven);

                if (connectAbove < this.connection.ConnectedNodes.Count())
                    if (version.StartHeight < this.chain.Height)
                        this.AttachedNode.DisconnectAsync($"Node too far behind height = {version.StartHeight}");
            });
        }

        protected override void AttachCore()
        {
            this.AttachedNode.MessageReceived += this.AttachedNodeOnMessageReceived;
        }

        protected override void DetachCore()
        {
            this.AttachedNode.MessageReceived -= this.AttachedNodeOnMessageReceived;
        }

        public override object Clone()
        {
            return new DropNodesBehaviour(this.chain, this.connection);
        }
    }
}

Add a behaviour to drop nodes if all the current connected nodes are behind.


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

using Xunit;

[assembly: CollectionBehavior(DisableTestParallelization = true)]

Disable concurrency for storage integration tests

Basically, it makes timing issues harder to diagnose


// 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Objects.Drawables;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Catch.Tests
{
    public class TestSceneComboCounter : CatchSkinnableTestScene
    {
        private ScoreProcessor scoreProcessor;
        private GameplayBeatmap gameplayBeatmap;
        private readonly Bindable<bool> isBreakTime = new BindableBool();

        [BackgroundDependencyLoader]
        private void load()
        {
            gameplayBeatmap = new GameplayBeatmap(CreateBeatmapForSkinProvider());
            gameplayBeatmap.IsBreakTime.BindTo(isBreakTime);
            Dependencies.Cache(gameplayBeatmap);
            Add(gameplayBeatmap);
        }

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            scoreProcessor = new ScoreProcessor();

            SetContents(() => new CatchComboDisplay
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Scale = new Vector2(2.5f),
            });
        });

        [Test]
        public void TestCatchComboCounter()
        {
            AddRepeatStep("perform hit", () => performJudgement(HitResult.Perfect), 20);
            AddStep("perform miss", () => performJudgement(HitResult.Miss));
            AddToggleStep("toggle gameplay break", v => isBreakTime.Value = v);
        }

        private void performJudgement(HitResult type, Judgement judgement = null)
        {
            var judgedObject = new TestDrawableCatchHitObject(new TestCatchHitObject());
            var result = new JudgementResult(judgedObject.HitObject, judgement ?? new Judgement()) { Type = type };
            scoreProcessor.ApplyResult(result);

            foreach (var counter in CreatedDrawables.Cast<CatchComboDisplay>())
                counter.OnNewResult(judgedObject, result);
        }

        private class TestDrawableCatchHitObject : DrawableCatchHitObject
        {
            public TestDrawableCatchHitObject(CatchHitObject hitObject)
                : base(hitObject)
            {
                AccentColour.Value = Color4.White;
            }
        }

        private class TestCatchHitObject : CatchHitObject
        {
        }
    }
}

Add test scene showing off the skinnable catch-specific combo counter


// ---------------------------------------------------------------------------------------
// <copyright file="ColoreProvider.cs" company="Corale">
//     Copyright © 2015-2017 by Adam Hellberg and Brandon Scott.
//
//     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.
//
//     "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------

namespace Corale.Colore
{
    using Corale.Colore.Api;
    using Corale.Colore.Implementations;
    using Corale.Colore.Native;

    using JetBrains.Annotations;

    /// <summary>
    /// Provides helper methods to instantiate a new <see cref="IChroma" /> instance.
    /// </summary>
    [PublicAPI]
    public static class ColoreProvider
    {
        /// <summary>
        /// Creates a new <see cref="IChroma" /> instance using the native Razer Chroma SDK.
        /// </summary>
        /// <returns>A new instance of <see cref="IChroma" />.</returns>
        public static IChroma CreateNative()
        {
            return Create(new NativeApi());
        }

        /// <summary>
        /// Creates a new <see cref="IChroma" /> instance using the specified API instance.
        /// </summary>
        /// <param name="api">The API instance to use to route SDK calls.</param>
        /// <returns>A new instance of <see cref="IChroma" />.</returns>
        public static IChroma Create(IChromaApi api)
        {
            return new Chroma(api);
        }
    }
}

Add an instance provider for Colore

Add an instance provider for Colore


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace DotNetFrontEnd.Contracts
{
  public static class ContractExtensions
  {
    [Pure]
    public static bool Implies(this bool antecedent, bool consequent)
    {
      Contract.Ensures(Contract.Result<bool>() == (!antecedent || consequent));
      return !antecedent || consequent;
    }

    [Pure]
    public static bool OneOf<T>(this T x, T first, params T[] rest)
    {
      Contract.Requires(x != null);
      Contract.Requires(rest != null);
      Contract.Ensures(Contract.Result<bool>() == (x.Equals(first) || Contract.Exists(rest, e => x.Equals(e))));
      return x.Equals(first) || rest.Any(e => x.Equals(e));
    }

    // The type parameter K is inferred automatically from type of dictionary
    [Pure, System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
    public static bool SetEquals<K,V>(this Dictionary<K, V>.KeyCollection keys, ISet<K> set)
    {
      Contract.Requires(keys != null);
      Contract.Requires(set != null);
      Contract.Ensures(Contract.Result<bool>() ==
          Contract.ForAll(keys, k => set.Contains(k)) && Contract.ForAll(set, k => keys.Contains(k)));
      return keys.All(k => set.Contains(k)) && set.All(k => keys.Contains(k));
    }
  }
}

Add missing Contract helper function file


using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Queries;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace BatteryCommander.Web.Commands
{
    public class AddSUTAComment : IRequest
    {
        [FromRoute]
        public int Id { get; set; }

        [FromForm]
        public string Comment { get; set; }

        private class Handler : AsyncRequestHandler<AddSUTAComment>
        {
            private readonly Database db;
            private readonly IMediator dispatcher;

            public Handler(Database db, IMediator dispatcher)
            {
                this.db = db;
                this.dispatcher = dispatcher;
            }

            protected override async Task Handle(AddSUTAComment request, CancellationToken cancellationToken)
            {
                var suta =
                    await db
                    .SUTAs
                    .Where(s => s.Id == request.Id)
                    .SingleOrDefaultAsync(cancellationToken);

                var current_user = await dispatcher.Send(new GetCurrentUser { });

                suta.Events.Add(new SUTA.Event
                {
                    Author = $"{current_user}",
                    Message = request.Comment
                });

                await db.SaveChangesAsync(cancellationToken);
            }
        }
    }
}

Fix add signature and comment

Fix add signature and comment


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Structure
{
    internal class ArrowExpressionClauseStructureProvider : AbstractSyntaxNodeStructureProvider<ArrowExpressionClauseSyntax>
    {
        protected override void CollectBlockSpans(
            ArrowExpressionClauseSyntax node,
            ArrayBuilder<BlockSpan> spans,
            OptionSet options,
            CancellationToken cancellationToken)
        {
            var previousToken = node.ArrowToken.GetPreviousToken();
            spans.Add(new BlockSpan(
                isCollapsible: true,
                textSpan: TextSpan.FromBounds(previousToken.Span.End, node.Span.End),
                hintSpan: node.Parent.Span,
                type: BlockTypes.Member));
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Structure
{
    internal class ArrowExpressionClauseStructureProvider : AbstractSyntaxNodeStructureProvider<ArrowExpressionClauseSyntax>
    {
        protected override void CollectBlockSpans(
            ArrowExpressionClauseSyntax node,
            ArrayBuilder<BlockSpan> spans,
            OptionSet options,
            CancellationToken cancellationToken)
        {
            var previousToken = node.ArrowToken.GetPreviousToken();
            spans.Add(new BlockSpan(
                isCollapsible: true,
                textSpan: TextSpan.FromBounds(previousToken.Span.End, node.Span.End),
                hintSpan: node.Parent.Span,
                type: BlockTypes.Nonstructural));
        }
    }
}

Make the BlockSpan non-structural. We don't want to show an indent-guide for them.


using System.Collections.Generic;
using AutoMapper.EquivalencyExpression;
using FluentAssertions;
using Xunit;

namespace AutoMapper.Collection
{
    public class NullableIdTests
    {
        [Fact]
        public void Should_Work_With_Null_Id()
        {
            Mapper.Reset();
            Mapper.Initialize(x =>
            {
                x.AddCollectionMappers();
                x.CreateMap<ThingWithStringIdDto, ThingWithStringId>().EqualityComparison((dto, entity) => dto.ID == entity.ID);
            });

            var original = new List<ThingWithStringId>
            {
                new ThingWithStringId { ID = "1", Title = "test0" },
                new ThingWithStringId { ID = "2", Title = "test2" },
            };

            var dtos = new List<ThingWithStringIdDto>
            {
                new ThingWithStringIdDto { ID = "1", Title = "test0" },
                new ThingWithStringIdDto { ID = "2", Title = "test2" },
                new ThingWithStringIdDto { Title = "test3" }
            };

            Mapper.Map(dtos, original);

            original.Should().HaveSameCount(dtos);
        }

        public class ThingWithStringId
        {
            public string ID { get; set; }
            public string Title { get; set; }
            public override string ToString() { return Title; }
        }

        public class ThingWithStringIdDto
        {
            public string ID { get; set; }
            public string Title { get; set; }
        }
    }
}

Add tests for nullable keys

Add tests for nullable keys


using System.Data;

namespace ZocMonLib
{
    public interface IRecordFlush
    {
        /// <summary>
        /// Flush all data accumulated thus far.
        /// </summary>
        void FlushAll();

        /// <summary>
        /// Flush data for the lowest reduce resolution for the given configuration.
        /// (The rest is only written on Reduce.)
        /// </summary>
        /// <param name="configName"></param>
        /// <param name="conn"></param>
        void Flush(string configName, IDbConnection conn);
    }
}

using System.Data;

namespace ZocMonLib
{
    public interface IRecordFlush
    {
        /// <summary>
        /// Flush all data accumulated thus far.
        /// </summary>
        void FlushAll();

        /// <summary>
        /// Flush data for the lowest reduce resolution for the given configuration.
        /// (The rest is only written on Reduce.)
        /// </summary>
        /// <param name="configName"></param>
        /// <param name="conn"></param>
        void Flush(string configName, IDbConnection conn = null);
    }
}

Update flusher to have defaults

Update flusher to have defaults


@page Test

RazorPages Test

This file should give you a quick view of a Mvc Raor Page in action.

Add missing file to samples

Add missing file to samples


//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 2014-04-24
// Autor
//
// Make copy of job and open it in temporary path.
//-----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;

namespace PCBIScript
{
	public class PScript : IPCBIScript
	{
		public PScript()
		{
		}

		public void Execute(IPCBIWindow parent)
		{

			  string pathForWorkingODB = Path.GetTempPath() + "\\example\\WorkingJob_diehl";
            parent.SaveJob(pathForWorkingODB, false);

            if (!parent.LoadODBJob(pathForWorkingODB))
                MessageBox.Show("Can't create a temporary working copy of ODB-Data.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			else
				MessageBox.Show("Workingcopy is loaded.", "Finish", MessageBoxButtons.OK, MessageBoxIcon.None);
        }

    }
}

Make a working copy of an PCB design

Make a working copy of an PCB design


using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Web;
using dashing.net.common;

namespace dashing.net.App_Start
{
    public class JobConfig
    {
        public static void RegisterJobs()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(HttpContext.Current.Server.MapPath("~/Jobs/")));
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            var container = new CompositionContainer(catalog);
            container.ComposeParts();

            var exports = container.GetExportedValues<IJob>();

            foreach (var job in exports)
            {
                Jobs.Add(job);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Web;
using dashing.net.common;

namespace dashing.net.App_Start
{
    using System.IO;

    public class JobConfig
    {
        public static void RegisterJobs()
        {
            var jobsPath = HttpContext.Current.Server.MapPath("~/Jobs/");
            if (!Directory.Exists(jobsPath))
            {
                return;
            }

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(jobsPath));
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            var container = new CompositionContainer(catalog);
            container.ComposeParts();

            var exports = container.GetExportedValues<IJob>();

            foreach (var job in exports)
            {
                Jobs.Add(job);
            }
        }
    }
}

Update to avoid an execption if there are no jobs and therefore no jobs folder.


using FluentAssertions;
using NFugue.Parser;
using NFugue.Theory;
using Staccato.Subparsers.NoteSubparser;
using Xunit;

namespace Staccato.Tests.Subparsers
{
    public class NoteSubparserTests : SubparserTestBase<NoteSubparser>
    {
        [Fact]
        public void Should_match_simple_notes()
        {
            subparser.Matches("A").Should().BeTrue();
            subparser.Matches("R").Should().BeTrue();
            subparser.Matches("S").Should().BeFalse();

            subparser.Matches("Cb").Should().BeTrue();
            subparser.Matches("B#").Should().BeTrue();
            subparser.Matches("bC").Should().BeFalse();
            subparser.Matches("A%").Should().BeTrue();

            subparser.Matches("Ebb").Should().BeTrue();
            subparser.Matches("A##").Should().BeTrue();
            subparser.Matches("A#b").Should().BeTrue();
            subparser.Matches("I&&").Should().BeFalse();

            subparser.Matches("Eb5").Should().BeTrue();
        }

        [Fact]
        public void Should_raise_note_parsed_on_simple_notes()
        {
            ParseWithSubparser("C");
            VerifyEventRaised(nameof(Parser.NoteParsed))
                .WithArgs<NoteEventArgs>(e => e.Note.Equals(new Note(60) { IsOctaveExplicitlySet = false }));
        }
    }
}

Add tests class for NoteSubparser

Add tests class for NoteSubparser


using DotNetNuke.Security.Roles;
using System;

namespace Dnn.PersonaBar.Prompt.Models
{
    public class RoleModel : RoleModelBase
    {
        public string Description;
        public DateTime CreatedDate;
        public int CreatedBy;

        #region Constructors
        public RoleModel()
        {
        }
        public RoleModel(RoleInfo role)
        {
            CreatedDate = role.CreatedOnDate;
            CreatedBy = role.CreatedByUserID;
            Description = role.Description;
        }
        #endregion

        #region Command Links
        public string __CreatedBy
        {
            get
            {
                return $"get-user {CreatedBy}";
            }
        }
        #endregion
    }
}

Change file name to reflect new class name


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

using osu.Game.Graphics.UserInterface;

namespace osu.Game.Graphics.UserInterfaceV2
{
    public class LabelledNumberBox : LabelledTextBox
    {
        protected override OsuTextBox CreateTextBox() => new OsuNumberBox();
    }
}

Add labelled number box control

Add labelled number box control


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

namespace WundergroundClient.Autocomplete
{
    class AutocompleteResponse
    {
        public Boolean IsSuccessful { get; private set; }
        public IList<AutocompleteResponseObject> Results;
    }
}

Add skeleton for Autocomplete Responses.


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

namespace Csla.Security
{
  /// <summary>
  /// Maintains a list of all object level
  /// authorization roles.
  /// </summary>
  internal class ObjectAuthorizationRules
  {
    private static Dictionary<Type, RolesForType> _managers =
      new Dictionary<Type, RolesForType>();

    internal static RolesForType GetRoles(Type objectType)
    {
      RolesForType result = null;
      if (!_managers.TryGetValue(objectType, out result))
      {
        bool createdManager = false;
        lock (_managers)
        {
          if (!_managers.TryGetValue(objectType, out result))
          {
            result = new RolesForType();
            _managers.Add(objectType, result);
            createdManager = true;
          }
        }
        // if necessary, create instance to trigger
        // static constructor
        if (createdManager)
        {
          lock (objectType)
          {
            var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
            MethodInfo method = objectType.GetMethod(
              "AddObjectAuthorizationRules", flags);
            if (method != null)
              method.Invoke(null, null);
          }
        }
      }
      return result;
    }

    public static bool RulesExistFor(Type objectType)
    {
      return _managers.ContainsKey(objectType);
    }
  }
}

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

namespace Csla.Security
{
  /// <summary>
  /// Maintains a list of all object level
  /// authorization roles.
  /// </summary>
  internal class ObjectAuthorizationRules
  {
    private static Dictionary<Type, RolesForType> _managers =
      new Dictionary<Type, RolesForType>();

    internal static RolesForType GetRoles(Type objectType)
    {
      RolesForType result = null;
      if (!_managers.TryGetValue(objectType, out result))
      {
        lock (_managers)
        {
          if (!_managers.TryGetValue(objectType, out result))
          {
            result = new RolesForType();
            _managers.Add(objectType, result);
            // invoke method to add auth roles
            var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
            MethodInfo method = objectType.GetMethod(
              "AddObjectAuthorizationRules", flags);
            if (method != null)
              method.Invoke(null, null);
          }
        }
      }
      return result;
    }

    public static bool RulesExistFor(Type objectType)
    {
      return _managers.ContainsKey(objectType);
    }
  }
}

Move initialization code into the original lock to avoid a race condition.


/*
 * Editors/SoftFocus.cs
 *
 * Copyright 2007 Novell Inc.
 *
 * Author
 *   Larry Ewing <lewing@novell.com>
 *
 * See COPYING for license information.
 *
 */
using Gtk;
using System;

namespace FSpot.Editors {
	public class SoftFocus : EffectEditor {
		Widgets.SoftFocus soft;
		Scale scale;
		bool double_buffer;

		public SoftFocus (PhotoImageView view) : base (view)
		{
		}

		protected override void SetView (PhotoImageView value)
		{

			if (view != null)
				view.DoubleBuffered = double_buffer;

			base.SetView (value);

			if (value == null)
				return;

			soft = new Widgets.SoftFocus (info);
			effect = (IEffect) soft;
			double_buffer = (view.WidgetFlags & WidgetFlags.DoubleBuffered) == WidgetFlags.DoubleBuffered;
			view.DoubleBuffered = true;
		}

		protected override Widget CreateControls ()
		{
			VBox box = new VBox ();
			scale = new HScale (0, 45, 1);
			scale.Value = 0.0;
			scale.ValueChanged += HandleValueChanged;
			scale.WidthRequest = 250;
			box.PackStart (scale);
			HBox actions = new HBox ();
			Button apply = new Button ("Apply");
			apply.Clicked += HandleApply;
			actions.PackStart (apply);
			Button cancel = new Button ("Cancel");
			cancel.Clicked += HandleCancel;
			actions.PackStart (cancel);
			box.PackStart (actions);

			return box;
		}

		private void HandleCancel (object sender, EventArgs args)
		{
			Close ();
		}

		private void HandleApply (object sender, EventArgs args)
		{
			Console.WriteLine ("wake up man, this is never going to work ;)");
			Close ();
		}

		private void HandleValueChanged (object sender, EventArgs args)
		{
			soft.Radius = ((Scale)sender).Value;
			if (view != null)
				view.QueueDraw ();
		}
	}
}

Add the soft focus editor to the repository.

svn path=/trunk/; revision=2830


namespace SharpexGL.Framework.Game.Timing
{
    public enum RenderMode
    {
        /// <summary>
        /// Limits the render call to a fixed fps amount.
        /// </summary>
        Limited,
        /// <summary>
        /// No limitations.
        /// </summary>
        Unlimited
    }
}

Enable limitation control for rendering

Enable limitation control for rendering

There is now the ability to set the rendering thread to unlimited, which
means, the fps have no limit.


using Mofichan.Backend;
using Mofichan.Core.Interfaces;
using Moq;
using Serilog;
using Shouldly;
using Xunit;

namespace Mofichan.Tests
{
    public class BackendSpec
    {
        private class MockBackend : BaseBackend
        {
            public bool OnStartCalled { get; private set; }
            public string RoomId { get; private set; }
            public string UserId { get; private set; }

            public MockBackend(ILogger logger) : base(logger)
            {
            }

            public override void Start()
            {
                this.OnStartCalled = true;
            }

            protected override IRoom GetRoomById(string roomId)
            {
                this.RoomId = roomId;
                return Mock.Of<IRoom>();
            }

            protected override IUser GetUserById(string userId)
            {
                this.UserId = userId;
                return Mock.Of<IUser>();
            }
        }

        [Fact]
        public void Backend_Should_Try_To_Get_Room_Id_When_Join_Requested()
        {
            // GIVEN a mock backend.
            var backend = new MockBackend(Mock.Of<ILogger>());
            backend.RoomId.ShouldBeNull();

            // GIVEN a room ID.
            var roomId = "foo";

            // WHEN I try to join a room using the room ID.
            backend.Join(roomId);

            // THEN the backend should have attempted to find a room using that identifier.
            backend.RoomId.ShouldBe(roomId);
        }

        [Fact]
        public void Backend_Should_Try_To_Get_Room_Id_When_Leave_Requested()
        {
            // GIVEN a mock backend.
            var backend = new MockBackend(Mock.Of<ILogger>());
            backend.RoomId.ShouldBeNull();

            // GIVEN a room ID.
            var roomId = "foo";

            // WHEN I try to leave a room using the room ID.
            backend.Leave(roomId);

            // THEN the backend should have attempted to find a room using that identifier.
            backend.RoomId.ShouldBe(roomId);
        }
    }
}

Add a few base backend tests

Add a few base backend tests


using System;
using System.Linq;

using Microsoft.WindowsAzure.Storage.Table;

namespace Streamstone
{
    public class Partition
    {
        static readonly string[] separator = {"|"};

        public readonly CloudTable Table;
        public readonly string PartitionKey;
        public readonly string RowKeyPrefix;

        public Partition(CloudTable table, string key)
        {
            Requires.NotNull(table, "table");
            Requires.NotNullOrEmpty(key, "key");

            var parts = key.Split(separator, 2,
                StringSplitOptions.RemoveEmptyEntries);

            Table = table;
            PartitionKey = parts[0];
            RowKeyPrefix = parts.Length > 1
                            ? parts[1] + separator[0]
                            : "";
        }

        public string StreamRowKey()
        {
            return string.Format("{0}{1}", RowKeyPrefix, StreamEntity.FixedRowKey);
        }

        public string EventVersionRowKey(int version)
        {
            return string.Format("{0}{1}{2:d10}", RowKeyPrefix, EventEntity.RowKeyPrefix, version);
        }

        public string EventIdRowKey(string id)
        {
            return string.Format("{0}{1}{2}", RowKeyPrefix, EventIdEntity.RowKeyPrefix, id);
        }

        public override string ToString()
        {
            return string.Format("{0}.{1}{2}", Table.Name, PartitionKey, RowKeyPrefix);
        }
    }
}

using System;
using System.Linq;

using Microsoft.WindowsAzure.Storage.Table;

namespace Streamstone
{
    public class Partition
    {
        static readonly string[] separator = {"|"};

        public readonly CloudTable Table;
        public readonly string PartitionKey;
        public readonly string RowKeyPrefix;
        public readonly string Key;

        public Partition(CloudTable table, string key)
        {
            Requires.NotNull(table, "table");
            Requires.NotNullOrEmpty(key, "key");

            var parts = key.Split(separator, 2,
                StringSplitOptions.RemoveEmptyEntries);

            Table = table;

            PartitionKey = parts[0];
            RowKeyPrefix = parts.Length > 1
                            ? parts[1] + separator[0]
                            : "";
            Key = key;
        }

        public string StreamRowKey()
        {
            return string.Format("{0}{1}", RowKeyPrefix, StreamEntity.FixedRowKey);
        }

        public string EventVersionRowKey(int version)
        {
            return string.Format("{0}{1}{2:d10}", RowKeyPrefix, EventEntity.RowKeyPrefix, version);
        }

        public string EventIdRowKey(string id)
        {
            return string.Format("{0}{1}{2}", RowKeyPrefix, EventIdEntity.RowKeyPrefix, id);
        }

        public override string ToString()
        {
            return string.Format("{0}.{1}", Table.Name, Key);
        }
    }
}

Store and provide full original partition key


using System.ComponentModel;

namespace Merq
{
    /// <summary>
    /// Usability overloads for <see cref="IEventStream"/>.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class IEventStreamExtensions
    {
        /// <summary>
        /// Pushes a new instance of <typeparamref name="TEvent"/> through the stream.
        /// </summary>
        public static void Push<TEvent>(this IEventStream events) where TEvent : new()
            => events.Push(new TEvent());
    }
}

Allow pushing a TEvent that has new() constraint


using System;
using System.Collections.Generic;
using Seq.Api.Model;
using Xunit;

namespace Seq.Api.Tests
{
    public class LinkTests
    {
        [Fact]
        public void ALinkWithNoParametersIsLiteral()
        {
            const string uri = "https://example.com";
            var link = new Link(uri);
            var constructed = link.GetUri();
            Assert.Equal(uri, constructed);
        }

        [Fact]
        public void AParameterizedLinkCanBeConstructed()
        {
            const string template = "https://example.com/{name}";
            var link = new Link(template);
            var constructed = link.GetUri(new Dictionary<string, object> {["name"] = "test"});
            Assert.Equal("https://example.com/test", constructed);
        }

        [Fact]
        public void InvalidParametersAreDetected()
        {
            const string template = "https://example.com";
            var link = new Link(template);
            Assert.Throws<ArgumentException>(() => link.GetUri(new Dictionary<string, object> {["name"] = "test"}));
        }
    }
}

Add some very basic tests for Link

Add some very basic tests for Link


//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 27.05.2015
// Autor Gruber Fabio
//
// Clear Attributes of components.
//-----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;

namespace PCBIScript
{
   public class PScript : IPCBIScript
	{
		public PScript()
		{
		}

		public void Execute(IPCBIWindow parent)
		{
            IMatrix m = parent.GetMatrix();
            IStep step = parent.GetCurrentStep();

            foreach (ICMPObject comp in step.GetAllCMPObjects())
            {
                Dictionary<string ,string> attv = comp.GetComponentAttributeDictionary();

                foreach (string att in attv.Keys)
                {
                    comp.RemoveAttribute(att);
                }
            }
            parent.UpdateView();
         }
    }
}

Remove attributes of an ODB++ job

Remove attributes of an ODB++ job


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

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osuTK;

namespace osu.Framework.Tests.Visual.Drawables
{
    public class TestSceneBorderColour : FrameworkTestScene
    {
        [Test]
        public void TestSolidBorder()
        {
            Container container = null;

            AddStep("create box with solid border", () => Child = container = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Size = new Vector2(200),
                Masking = true,
                BorderThickness = 5,
                BorderColour = Colour4.Red,
                Child = new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = Colour4.Blue
                }
            });

            AddSliderStep("change corner radius", 0, 100, 0, radius =>
            {
                if (container != null)
                    container.CornerRadius = radius;
            });

            AddSliderStep("change corner exponent", 0.1f, 10, 1, exponent =>
            {
                if (container != null)
                    container.CornerExponent = exponent;
            });
        }
    }
}

Add basic test coverage for solid border colour


// The MIT License (MIT)
//
// Copyright (c) 2015 Jabavu W. Adams.
//
// 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.

// DebugDrawSpringJoints.cs

using UnityEngine;
using System.Collections;

public class DebugDrawSpringJoints : MonoBehaviour
{
	public Color stretchedColor = Color.red;
	public Color compressedColor = Color.green;
	public Color neutralColor = Color.cyan;

	void Update()
	{
		foreach (SpringJoint spring in GetComponents<SpringJoint>())
		{
			Vector3 p0 = transform.TransformPoint(spring.anchor);

			Vector3 p1 = spring.connectedBody.transform.TransformPoint(
				spring.connectedAnchor);

			// Draw the spring with varying colours depending on whether
			// it's stretched, compressed, or neither.

			float currentLength = Vector3.Distance(p0, p1);
			Color springColor;

			if (currentLength > spring.maxDistance)
			{
				springColor = stretchedColor;
			}
			else if (currentLength < spring.minDistance)
			{
				springColor = compressedColor;
			}
			else
			{
				springColor = neutralColor;
			}

			Debug.DrawLine(p0, p1, springColor);
		}
	}
}

Add a script to draw all spring joints connected to an object, for debugging.


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

using System;
using System.Composition;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.InlineHints;
using Microsoft.CodeAnalysis.Options;
using System.Threading.Tasks;
using System.Threading;

namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Options
{
    /// <summary>
    /// Enables legacy APIs to access global options from workspace.
    /// </summary>
    [ExportWorkspaceService(typeof(ILegacyGlobalOptionsWorkspaceService)), Shared]
    internal sealed class OmnisharpLegacyGlobalOptionsWorkspaceService : ILegacyGlobalOptionsWorkspaceService
    {
        private readonly CleanCodeGenerationOptionsProvider _provider;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public OmnisharpLegacyGlobalOptionsWorkspaceService()
        {
            _provider = new OmniSharpCleanCodeGenerationOptionsProvider();
        }

        public bool RazorUseTabs
            => LineFormattingOptions.Default.UseTabs;

        public int RazorTabSize
            => LineFormattingOptions.Default.TabSize;

        public CleanCodeGenerationOptionsProvider CleanCodeGenerationOptionsProvider
            => _provider;

        /// TODO: remove. https://github.com/dotnet/roslyn/issues/57283
        public bool InlineHintsOptionsDisplayAllOverride
        {
            get => false;
            set { }
        }

        public bool GenerateOverrides
        {
            get => true;
            set { }
        }

        public bool GetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language)
            => false;

        public void SetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language, bool value)
        {
        }

        public bool GetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language)
            => false;

        public void SetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language, bool value)
        {
        }

        public bool GetGenerateConstructorFromMembersOptionsAddNullChecks(string language)
            => false;

        public void SetGenerateConstructorFromMembersOptionsAddNullChecks(string language, bool value)
        {
        }

        internal sealed class OmniSharpCleanCodeGenerationOptionsProvider : AbstractCleanCodeGenerationOptionsProvider
        {
            public override ValueTask<CleanCodeGenerationOptions> GetCleanCodeGenerationOptionsAsync(HostLanguageServices languageServices, CancellationToken cancellationToken)
            {
                return new ValueTask<CleanCodeGenerationOptions>(CleanCodeGenerationOptions.GetDefault(languageServices));
            }
        }
    }
}

Add LegacyGlobalOptionsWorkspaceService for OmniSharp EA


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

namespace NBi.Core.Etl
{
    public interface IEtlRunCommand: IEtl
    {
    }
}

Define interface for a command in setup or cleanup


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows;
using System.Windows.Input;

namespace FreeSCADA.Schema.Manipulators
{
    class GeometryHilightManipulator:BaseManipulator
    {
        Rectangle hilightRect = new Rectangle();
        public GeometryHilightManipulator(UIElement element, SchemaDocument doc)
            : base(element, doc)
        {
            VisualBrush brush = new VisualBrush(AdornedElement);
            //hilightRect.Opacity = 0.5;
          //  hilightRect.Fill = brush;

            visualChildren.Add(hilightRect);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {

            Rect r=AdornedElement.TransformToVisual(this).TransformBounds(new Rect(new Point(0, 0), AdornedElement.DesiredSize));
            r.X = 0;
            r.Y = 0;
            hilightRect.Arrange(r);
            return finalSize;
        }

    }
}

Fix on previous commit ...

Fix on previous commit ...


// 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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osuTK;

namespace osu.Framework.Tests.Visual.Drawables
{
    [Ignore("This test needs a game host to be useful.")]
    public class TestSceneStressGLDisposal : FrameworkTestScene
    {
        private FillFlowContainer fillFlow;

        protected override double TimePerAction => 0.001;

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            Add(fillFlow = new FillFlowContainer
            {
                RelativeSizeAxes = Axes.Both,
                Direction = FillDirection.Full
            });
        });

        [Test]
        public void TestAddRemoveDrawable()
        {
            AddRepeatStep("add/remove drawables", () =>
            {
                for (int i = 0; i < 50; i++)
                {
                    fillFlow.Add(new Box { Size = new Vector2(5) });

                    if (fillFlow.Count > 100)
                    {
                        fillFlow.Remove(fillFlow.First());
                    }
                }
            }, 100000);
        }
    }
}

Add failing GL disposal stress test

Add failing GL disposal stress test

Co-authored-by: voidedWarranties <8703afe59310e2b76940dbf42498d5eec85dac67@gmail.com>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Http;
using Moq;
using NUnit.Framework;
using NUnit.Framework.Internal;
using SFA.DAS.CommitmentsV2.Api.Authentication;
using SFA.DAS.CommitmentsV2.Authentication;
using SFA.DAS.CommitmentsV2.Types;

namespace SFA.DAS.CommitmentsV2.Api.UnitTests.Authentication
{
    [TestFixture]
    public class AuthenticationServiceTests
    {
        [TestCase(Originator.Employer, Role.Employer)]
        [TestCase(Originator.Provider, Role.Provider)]
        [TestCase(Originator.Unknown, Role.Provider, Role.Employer)]
        [TestCase(Originator.Unknown, "someOtherRole")]
        public void GetUserRole(Originator expectedRole, params string[] roles)
        {
            // arrange
            Mock<IHttpContextAccessor> httpContextAccessorMock = new Mock<IHttpContextAccessor>();
            Mock<HttpContext> httpContextMock = new Mock<HttpContext>();
            Mock<ClaimsPrincipal> userMock = new Mock<ClaimsPrincipal>();

            httpContextAccessorMock
                .Setup(hca => hca.HttpContext)
                .Returns(httpContextMock.Object);

            httpContextMock
                .Setup(hcm => hcm.User)
                .Returns(userMock.Object);

            userMock
                .Setup(um => um.IsInRole(It.IsAny<string>()))
                .Returns<string>(roles.Contains);

            var sut = new AuthenticationService(httpContextAccessorMock.Object);

            // act
            var actualRole = sut.GetUserRole();

            // assert
            Assert.AreEqual(expectedRole, actualRole);
        }
    }
}

Add unit test for getuserrole

Add unit test for getuserrole


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

using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Lines;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Utils;
using osuTK;
using osuTK.Graphics;

namespace osu.Framework.Tests.Visual.Drawables
{
    public class TestSceneCircularArcBoundingBox : FrameworkTestScene
    {
        private SmoothPath path;
        private Box boundingBox;

        private readonly BindableList<Vector2> controlPoints = new BindableList<Vector2>();

        private float startAngle, endAngle, radius;

        [BackgroundDependencyLoader]
        private void load()
        {
            Children = new Drawable[]
            {
                boundingBox = new Box
                {
                    RelativeSizeAxes = Axes.None,
                    Colour = Color4.Red
                },
                path = new SmoothPath
                {
                    Colour = Color4.White,
                    PathRadius = 2
                }
            };

            AddSliderStep("starting angle", 0, 360, 90, angle =>
            {
                startAngle = angle;
                generateControlPoints();
            });

            AddSliderStep("end angle", 0, 360, 270, angle =>
            {
                endAngle = angle;
                generateControlPoints();
            });

            AddSliderStep("radius", 1, 300, 150, radius =>
            {
                this.radius = radius;
                generateControlPoints();
            });
        }

        protected override void LoadComplete()
        {
            controlPoints.BindCollectionChanged((_, __) =>
            {
                var copy = controlPoints.ToArray();
                if (copy.Length != 3)
                    return;

                path.Vertices = PathApproximator.ApproximateCircularArc(copy);

                var bounds = PathApproximator.CircularArcBoundingBox(copy);
                boundingBox.Size = bounds.Size;
            });
        }

        private void generateControlPoints()
        {
            float midpoint = (startAngle + endAngle) / 2;

            Vector2 polarToCartesian(float r, float theta) =>
                new Vector2(
                    r * MathF.Cos(MathHelper.DegreesToRadians(theta)),
                    r * MathF.Sin(MathHelper.DegreesToRadians(theta)));

            controlPoints.Clear();
            controlPoints.AddRange(new[]
            {
                polarToCartesian(radius, startAngle),
                polarToCartesian(radius, midpoint),
                polarToCartesian(radius, endAngle)
            });
        }
    }
}

Add test scene for arc bounding box computation