Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Add accelerometer reader example script
using UnityEngine; using System.Collections; public class AccelerometerReader : MonoBehaviour { public float Filter = 5.0f; public GUIText Label; private Vector3 accel; void Start() { accel = Input.acceleration; } void Update() { // filter the jerky acceleration in the variable accel: accel = Vector3.Lerp(accel, Input.acceleration, Filter * Time.deltaTime); var dir = new Vector3(accel.x, accel.y, 0); // limit dir vector to magnitude 1: if (dir.sqrMagnitude > 1) dir.Normalize(); // sync to framerate Label.text = (dir * Time.deltaTime * 100).ToString(); } }
Convert int to string column
// http://careercup.com/question?id=5690323227377664 // // Write a function which takes an integer and convert to string as: // 1 - A 0001 // 2 - B 0010 // 3 - AA 0011 // 4 - AB 0100 // 5 - BA 0101 // 6 - BB 0110 // 7 - AAA 0111 // 8 - AAB 1000 // 9 - ABA 1001 // 10 - ABB // 11 - BAA // 12 - BAB // 13 - BBA // 14 - BBB // 15 - AAAA using System; static class Program { static String ToS(this int i) { String result = String.Empty; while (i > 0) { if ((i & 1) == 0) { result += "B"; i -= 1; } else { result += "A"; } i >>= 1; } return result; } static void Main() { for (int i = 1; i < 16; i++) { Console.WriteLine("{0} - {1}", i, i.ToS()); } } }
Add Eric Lippert's backport of Zip() to .NET 3.5.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace open3mod { // Zip() was added in .NET 4.0. // http://blogs.msdn.com/b/ericlippert/archive/2009/05/07/zip-me-up.aspx public static class LinqZipNet4Backport { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); if (resultSelector == null) throw new ArgumentNullException("resultSelector"); return ZipIterator(first, second, resultSelector); } private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult> (IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { using (IEnumerator<TFirst> e1 = first.GetEnumerator()) using (IEnumerator<TSecond> e2 = second.GetEnumerator()) while (e1.MoveNext() && e2.MoveNext()) yield return resultSelector(e1.Current, e2.Current); } } }
Add test coverage of accuracy formatting function
// 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.Utils; namespace osu.Game.Tests.NonVisual { [TestFixture] public class FormatUtilsTest { [TestCase(0, "0.00%")] [TestCase(0.01, "1.00%")] [TestCase(0.9899, "98.99%")] [TestCase(0.989999, "99.00%")] [TestCase(0.99, "99.00%")] [TestCase(0.9999, "99.99%")] [TestCase(0.999999, "99.99%")] [TestCase(1, "100.00%")] public void TestAccuracyFormatting(double input, string expectedOutput) { Assert.AreEqual(expectedOutput, input.FormatAccuracy()); } } }
Add too few players exception
// TooFewPlayersException.cs // <copyright file="TooFewPlayersException.cs"> This code is protected under the MIT License. </copyright> using System; namespace CardGames { /// <summary> /// An exception raised when TooFewPlayers are added to a game. /// </summary> [Serializable] public class TooFewPlayersException : Exception { /// <summary> /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class. /// </summary> public TooFewPlayersException() { } /// <summary> /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> public TooFewPlayersException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> /// <param name="inner"> The exception that caused the TooFewPlayersException. </param> public TooFewPlayersException(string message, Exception inner) : base(message, inner) { } } }
Set up results output interface
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TimeNetSync.Services { public interface IResultsOutput { } }
Fix autosave and refresh on shared projects
using JetBrains.Annotations; using JetBrains.Application.changes; using JetBrains.Application.FileSystemTracker; using JetBrains.Application.Threading; using JetBrains.DocumentManagers; using JetBrains.DocumentModel; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.ReSharper.Host.Features.Documents; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.Rider.Model; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [SolutionComponent] public class RiderUnityDocumentOperationsImpl : RiderDocumentOperationsImpl { [NotNull] private readonly ILogger myLogger; public RiderUnityDocumentOperationsImpl(Lifetime lifetime, [NotNull] SolutionModel solutionModel, [NotNull] SettingsModel settingsModel, [NotNull] ISolution solution, [NotNull] IShellLocks locks, [NotNull] ChangeManager changeManager, [NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage, [NotNull] IFileSystemTracker fileSystemTracker, [NotNull] ILogger logger) : base(lifetime, solutionModel, settingsModel, solution, locks, changeManager, documentToProjectFileMappingStorage, fileSystemTracker, logger) { myLogger = logger; } public override void SaveDocumentAfterModification(IDocument document, bool forceSaveOpenDocuments) { Locks.Dispatcher.AssertAccess(); if (forceSaveOpenDocuments) { var projectFile = DocumentToProjectFileMappingStorage.TryGetProjectFile(document); var isUnitySharedProjectFile = projectFile != null && projectFile.IsShared() && projectFile.GetProject().IsUnityProject(); if (isUnitySharedProjectFile) { myLogger.Info($"Trying to save document {document.Moniker}. Force = true"); myLogger.Verbose("File is shared and contained in Unity project. Skip saving."); return; } } base.SaveDocumentAfterModification(document, forceSaveOpenDocuments); } } }
Verify NotifyFault called will properly fail a filter execution
namespace MassTransit.Tests { using System; using System.Threading.Tasks; using MassTransit.Testing; using Microsoft.Extensions.DependencyInjection; using Middleware; using NUnit.Framework; using TestFramework.Messages; [TestFixture] public class Using_a_request_filter_with_request_client { [Test] public async Task Should_fault_instead_of_timeout() { await using var provider = new ServiceCollection() .AddMassTransitTestHarness(x => { x.AddConsumer<PingConsumer>(); x.UsingInMemory((context, cfg) => { cfg.UseConsumeFilter(typeof(RequestValidationScopedFilter<>), context); cfg.ConfigureEndpoints(context); }); }) .BuildServiceProvider(true); var harness = provider.GetTestHarness(); harness.TestInactivityTimeout = TimeSpan.FromSeconds(1); await harness.Start(); IRequestClient<PingMessage> client = harness.GetRequestClient<PingMessage>(); Assert.That(async () => await client.GetResponse<PongMessage>(new { CorrelationId = InVar.Id, }), Throws.TypeOf<RequestFaultException>()); } public class PingConsumer : IConsumer<PingMessage> { public Task Consume(ConsumeContext<PingMessage> context) { return context.RespondAsync(new PongMessage(context.Message.CorrelationId)); } } public class RequestValidationScopedFilter<T> : IFilter<ConsumeContext<T>> where T : class { public void Probe(ProbeContext context) { context.CreateFilterScope("RequestValidationScopedFilter<TMessage> scope"); } public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next) { try { throw new IntentionalTestException("Failed to validate request"); } catch (Exception exception) { await context.NotifyFaulted(context.ReceiveContext.ElapsedTime, TypeCache<RequestValidationScopedFilter<T>>.ShortName, exception) .ConfigureAwait(false); throw; } } } } }
Add models for notification emails.
using System; namespace CompetitionPlatform.Models { public class Initiative { public string FirstName { get; set; } public string ProjectId { get; set; } public DateTime ProjectCreatedDate { get; set; } public string ProjectAuthorName { get; set; } public string ProjectName { get; set; } public string ProjectStatus { get; set; } public string ProjectDescription { get; set; } public double ProjectFirstPrize { get; set; } public double ProjectSecondPrize { get; set; } } public class Competition { public string FirstName { get; set; } public string ProjectId { get; set; } public DateTime ProjectCreatedDate { get; set; } public DateTime ProjectCompetitionDeadline { get; set; } public string ProjectAuthorName { get; set; } public string ProjectName { get; set; } public string ProjectStatus { get; set; } public string ProjectDescription { get; set; } public double ProjectFirstPrize { get; set; } public double ProjectSecondPrize { get; set; } } public class Implementation { public string FirstName { get; set; } public string ProjectId { get; set; } public DateTime ProjectCreatedDate { get; set; } public DateTime ProjectImplementationDeadline { get; set; } public string ProjectAuthorName { get; set; } public string ProjectName { get; set; } public string ProjectStatus { get; set; } public string ProjectDescription { get; set; } public double ProjectFirstPrize { get; set; } public double ProjectSecondPrize { get; set; } } public class Voting { public string FirstName { get; set; } public string ProjectId { get; set; } public DateTime ProjectCreatedDate { get; set; } public DateTime ProjectVotingDeadline { get; set; } public string ProjectAuthorName { get; set; } public string ProjectName { get; set; } public string ProjectStatus { get; set; } public string ProjectDescription { get; set; } public double ProjectFirstPrize { get; set; } public double ProjectSecondPrize { get; set; } } }
Add a function to compute hit object position in catch editor
// 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.Rulesets.Catch.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Catch.Edit { /// <summary> /// Utility functions used by the editor. /// </summary> public static class CatchHitObjectUtils { /// <summary> /// Get the position of the hit object in the playfield based on <see cref="CatchHitObject.OriginalX"/> and <see cref="HitObject.StartTime"/>. /// </summary> public static Vector2 GetStartPosition(ScrollingHitObjectContainer hitObjectContainer, CatchHitObject hitObject) { return new Vector2(hitObject.OriginalX, hitObjectContainer.PositionAtTime(hitObject.StartTime)); } } }
Add a new datatype for skeletons
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using Microsoft.Kinect; using System.IO; namespace MultipleKinectsPlatform.MultipleKinectsPlatform.Data { [DataContract(Name="Skeleton")] public class Skeleton { [DataMember(Name="Joints")] public List<Joint> Joints; [DataMember] public float pos_x; [DataMember] public float pos_y; [DataMember] public float pos_z; public Skeleton(List<Joint> givenJoints,float i_x,float i_y,float i_z) { Joints = givenJoints; pos_x = i_x; pos_y = i_y; pos_z = i_z; } public static List<Skeleton> ConvertKinectSkeletons(Microsoft.Kinect.Skeleton[] obtainedSkeletons) { List<Skeleton> convertedSkeletons = new List<Skeleton>(); foreach (Microsoft.Kinect.Skeleton skeleton in obtainedSkeletons) { /* Get all joints of the skeleton */ List<Joint> convertedJoints = new List<Joint>(); foreach (Microsoft.Kinect.Joint joint in skeleton.Joints) { SkeletonPoint points = joint.Position; MultipleKinectsPlatform.Data.Joint convertedJoint = new MultipleKinectsPlatform.Data.Joint(points.X,points.Y,points.Z); convertedJoints.Add(convertedJoint); } /* Get the position of the skeleton */ SkeletonPoint skeletonPos = skeleton.Position; MultipleKinectsPlatform.Data.Skeleton convertedSkeleton = new Skeleton(convertedJoints,skeletonPos.X,skeletonPos.Y,skeletonPos.Z); convertedSkeletons.Add(convertedSkeleton); } return convertedSkeletons; } public static string ConvertToJSON(List<MultipleKinectsPlatform.Data.Skeleton> skeletonsToBeSerialise) { MemoryStream memStream = new MemoryStream(); DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(List<MultipleKinectsPlatform.Data.Skeleton>)); jsonSer.WriteObject(memStream, skeletonsToBeSerialise); string json = System.Text.Encoding.UTF8.GetString(memStream.GetBuffer(), 0, Convert.ToInt32(memStream.Length)); return json; } } }
Add some simple test cases for SetProperty.
using System; using GamesWithGravitas.Extensions; using Xunit; namespace GamesWithGravitas { public class NotifyPropertyChangedBaseTests { [Theory] [InlineData("Foo")] [InlineData("Bar")] public void SettingAPropertyWorks(string propertyValue) { var notifier = new Notifier(); var listener = notifier.ListenForPropertyChanged(nameof(Notifier.StringProperty)); notifier.StringProperty = propertyValue; Assert.Equal(propertyValue, notifier.StringProperty); Assert.True(listener.AllTrue); } [Theory] [InlineData("Foo")] [InlineData("Bar")] public void SettingADependentPropertyWorks(string propertyValue) { var notifier = new Notifier(); var listener = notifier.ListenForPropertyChanged(nameof(Notifier.DependentProperty), nameof(Notifier.DerivedProperty)); notifier.DependentProperty = propertyValue; Assert.Equal(propertyValue, notifier.DependentProperty); Assert.Equal(propertyValue + "!", notifier.DerivedProperty); Assert.True(listener.AllTrue); } } public class Notifier : NotifyPropertyChangedBase { private string _stringProperty; public string StringProperty { get => _stringProperty; set => SetProperty(ref _stringProperty, value); } private string _dependentProperty; public string DependentProperty { get => _dependentProperty; set => SetProperty(ref _dependentProperty, value, otherProperties: nameof(DerivedProperty)); } public string DerivedProperty => DependentProperty + "!"; } }
Add tests for losing audio devices
// 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.Threading; using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { /// <remarks> /// This unit will ALWAYS SKIP if the system does not have a physical audio device!!! /// A physical audio device is required to simulate the "loss" of it during playback. /// </remarks> [TestFixture] public class DeviceLosingAudioTest { private AudioThread thread; private NamespacedResourceStore<byte[]> store; private AudioManagerWithDeviceLoss manager; [SetUp] public void SetUp() { thread = new AudioThread(); store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.dll"), @"Resources"); manager = new AudioManagerWithDeviceLoss(thread, store, store); thread.Start(); // wait for any device to be initialized manager.WaitForDeviceChange(-1); // if the initialized device is "No sound", it indicates that no other physical devices are available, so this unit should be ignored if (manager.CurrentDevice == 0) Assert.Ignore("Physical audio devices are required for this unit."); // we don't want music playing in unit tests :) manager.Volume.Value = 0; } [TearDown] public void TearDown() { Assert.IsFalse(thread.Exited); thread.Exit(); Thread.Sleep(500); Assert.IsTrue(thread.Exited); } [Test] public void TestPlaybackWithDeviceLoss() => testPlayback(manager.SimulateDeviceRestore, manager.SimulateDeviceLoss); [Test] public void TestPlaybackWithDeviceRestore() => testPlayback(manager.SimulateDeviceLoss, manager.SimulateDeviceRestore); private void testPlayback(Action preparation, Action simulate) { preparation(); var track = manager.Tracks.Get("Tracks.sample-track.mp3"); // start track track.Restart(); Thread.Sleep(100); Assert.IsTrue(track.IsRunning); Assert.That(track.CurrentTime, Is.GreaterThan(0)); var timeBeforeLosing = track.CurrentTime; // simulate change (loss/restore) simulate(); Assert.IsTrue(track.IsRunning); Thread.Sleep(100); // playback should be continuing after device change Assert.IsTrue(track.IsRunning); Assert.That(track.CurrentTime, Is.GreaterThan(timeBeforeLosing)); // stop track track.Stop(); Thread.Sleep(100); Assert.IsFalse(track.IsRunning); // seek track track.Seek(0); Thread.Sleep(100); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.CurrentTime, 0); } } }
Add test that asserts records don't have RecordAttribute in reflection
using Amadevus.RecordGenerator.TestsBase; using Xunit; namespace Amadevus.RecordGenerator.Test { public class RecordClassTests : RecordTestsBase { [Fact] public void ReflectedClass_HasNo_RecordAttribute() { var recordType = typeof(Item); var recordAttributes = recordType.GetCustomAttributes(typeof(RecordAttribute), false); Assert.Empty(recordAttributes); } } }
Move connection strings to separate file
using Windows.UI.Xaml.Controls; namespace WeatherDataReporter { public sealed partial class MainPage : Page { static string iotHubUri = "{replace}"; static string deviceKey = "{replace}"; static string deviceId = "{replace}"; } }
Add partial implementation to PPCompletionCallback
using System; using System.Runtime.InteropServices; namespace PepperSharp { public partial struct PPCompletionCallback { public PPCompletionCallback(PPCompletionCallbackFunc func) { this.func = func; this.user_data = IntPtr.Zero; this.flags = (int)PPCompletionCallbackFlag.None; } public PPCompletionCallback(PPCompletionCallbackFunc func, object userData) { this.func = func; if (userData == null) this.user_data = IntPtr.Zero; else { GCHandle userHandle = GCHandle.Alloc(userData); this.user_data = (IntPtr)userHandle; } this.flags = (int)PPCompletionCallbackFlag.None; } public static object GetUserDataAsObject(IntPtr userData) { if (userData == IntPtr.Zero) return null; // back to object (in callback function): GCHandle userDataHandle = (GCHandle)userData; return userDataHandle.Target as object; } public static T GetUserData<T>(IntPtr userData) { if (userData == IntPtr.Zero) return default(T); GCHandle userDataHandle = (GCHandle)userData; return (T)userDataHandle.Target; } } }
Add extension methods to export the Data Center's content.
using System.IO; using System.Linq; using System.Xml.Linq; namespace Tera.Analytics { public static class DataCenterExtensions { private static XStreamingElement ToXStreamingElement(DataCenterElement element) { var xElement = new XStreamingElement(element.Name); xElement.Add(element.Attributes.Select(attribute => new XAttribute(attribute.Name, attribute.Value))); xElement.Add(element.Children.Select(ToXStreamingElement)); return xElement; } /// <summary> /// Exports the content of the specified element in XML format. /// </summary> /// <param name="element">The element to export.</param> /// <param name="outputPath">The path of the file that will contain the exported content.</param> public static void Export(this DataCenterElement element, string outputPath) { var xElement = ToXStreamingElement(element); using (var file = File.CreateText(outputPath)) { xElement.Save(file); } } /// <summary> /// Exports the contents of the Data Center in XML format. /// </summary> /// <param name="dataCenter">The Data Center to export.</param> /// <param name="outputPath">The path of the directory that will contain the exported content.</param> public static void Export(this DataCenter dataCenter, string outputPath) { var directory = Directory.CreateDirectory(outputPath); var groups = dataCenter.Root.Children.GroupBy(child => child.Name); foreach (var group in groups) if (group.Count() > 1) { var groupDirectory = directory.CreateSubdirectory(group.Key); var elementsAndFileNames = group.Select((element, index) => new { element, fileName = $"{element.Name}_{index}.xml" }); foreach (var o in elementsAndFileNames) { var fileName = Path.Combine(groupDirectory.FullName, o.fileName); o.element.Export(fileName); } } else { var element = group.Single(); var fileName = Path.Combine(directory.FullName, $"{element.Name}.xml"); element.Export(fileName); } } } }
Add top level test coverage of editor shortcuts
// 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.Rulesets; using osu.Game.Rulesets.Osu; using osuTK.Input; namespace osu.Game.Tests.Visual.Editing { /// <summary> /// Test editor hotkeys at a high level to ensure they all work well together. /// </summary> public class TestSceneEditorBindings : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestBeatDivisorChangeHotkeys() { AddStep("hold shift", () => InputManager.PressKey(Key.LShift)); AddStep("press 4", () => InputManager.Key(Key.Number4)); AddAssert("snap updated to 4", () => EditorBeatmap.BeatmapInfo.BeatDivisor, () => Is.EqualTo(4)); AddStep("press 6", () => InputManager.Key(Key.Number6)); AddAssert("snap updated to 6", () => EditorBeatmap.BeatmapInfo.BeatDivisor, () => Is.EqualTo(6)); AddStep("release shift", () => InputManager.ReleaseKey(Key.LShift)); } } }
Add a basic application test
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; namespace Tgstation.Server.Host.Core.Tests { [TestClass] public sealed class TestApplication { [TestMethod] public void TestMethodThrows() { Assert.ThrowsException<ArgumentNullException>(() => new Application(null, null)); var mockConfiguration = new Mock<IConfiguration>(); Assert.ThrowsException<ArgumentNullException>(() => new Application(mockConfiguration.Object, null)); var mockHostingEnvironment = new Mock<IHostingEnvironment>(); var app = new Application(mockConfiguration.Object, mockHostingEnvironment.Object); Assert.ThrowsException<ArgumentNullException>(() => app.ConfigureServices(null)); Assert.ThrowsException<ArgumentNullException>(() => app.Configure(null, null, null)); var mockAppBuilder = new Mock<IApplicationBuilder>(); Assert.ThrowsException<ArgumentNullException>(() => app.Configure(mockAppBuilder.Object, null, null)); var mockLogger = new Mock<ILogger<Application>>(); Assert.ThrowsException<ArgumentNullException>(() => app.Configure(mockAppBuilder.Object, mockLogger.Object, null)); } } }
Rearrange chars - prep work
// http://careercup.com/question?id=5693863291256832 // // Rearrange chars in a String so that no adjacent chars repeat // using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Program { static Random random = new Random(); static String Rearrange(this String s) { return null; } static String GenerateString() { return String.Join(String.Empty, Enumerable.Repeat(0, random.Next(20, 30)).Select(x => (char)random.Next('a', 'z'))); } static void Main() { for (int i = 0; i < 10; i++) { String s = GenerateString(); String p = s.Rearrange(); Console.WriteLine("{0} = {1}", s, p == null? "Not possible" : p); } } }
Add two extensions for RegionInfo.
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Finance { using System.Globalization; public static class RegionInfoExtensions { public static bool IsUsing(this RegionInfo @this, Currency currency) { Require.NotNull(@this, nameof(@this)); return @this.ISOCurrencySymbol == currency.Code; } public static bool IsUsing<TCurrency>(this RegionInfo @this, TCurrency currency) where TCurrency : CurrencyUnit<TCurrency> { Require.NotNull(@this, nameof(@this)); return @this.ISOCurrencySymbol == currency.Code; } } }
Add test coverage for common mime types
namespace AngleSharp.Core.Tests.Io { using AngleSharp.Io; using NUnit.Framework; [TestFixture] public class MimeTypeNameTests { [Test] public void CommonMimeTypesAreCorrectlyDefined() { Assert.AreEqual("image/avif", MimeTypeNames.FromExtension(".avif")); Assert.AreEqual("image/gif", MimeTypeNames.FromExtension(".gif")); Assert.AreEqual("image/jpeg", MimeTypeNames.FromExtension(".jpeg")); Assert.AreEqual("image/jpeg", MimeTypeNames.FromExtension(".jpg")); Assert.AreEqual("image/png", MimeTypeNames.FromExtension(".png")); Assert.AreEqual("image/svg+xml", MimeTypeNames.FromExtension(".svg")); Assert.AreEqual("image/webp", MimeTypeNames.FromExtension(".webp")); } } }
Add separate facility for bit commitment
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. /// </summary> public class BitCommitmentEngine { #region properties public Byte[] BobRandBytesR { get; set; } public Byte[] AliceEncryptedMessage { get; set; } #endregion } }
Add a basic kafka serilaizer
using System; using System.Text; using System.Threading.Tasks; using Confluent.Kafka; using Confluent.Kafka.SyncOverAsync; using Newtonsoft.Json; namespace Jasper.ConfluentKafka.Serialization { internal class DefaultJsonSerializer<T> : IAsyncSerializer<T> { public Task<byte[]> SerializeAsync(T data, SerializationContext context) { var json = JsonConvert.SerializeObject(data); return Task.FromResult(Encoding.UTF8.GetBytes(json)); } public ISerializer<T> AsSyncOverAsync() { return new SyncOverAsyncSerializer<T>(this); } } internal class DefaultJsonDeserializer<T> : IAsyncDeserializer<T> { public IDeserializer<T> AsSyncOverAsync() { return new SyncOverAsyncDeserializer<T>(this); } public Task<T> DeserializeAsync(ReadOnlyMemory<byte> data, bool isNull, SerializationContext context) { return Task.FromResult(JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data.ToArray()))); } } }
Add default web socket client unit tests
using System; using System.Threading; using System.Threading.Tasks; using Binance.WebSocket; using Xunit; namespace Binance.Tests.WebSocket { public class DefaultWebSocketClientTest { [Fact] public async Task Throws() { var uri = new Uri("wss://stream.binance.com:9443"); var client = new DefaultWebSocketClient(); using (var cts = new CancellationTokenSource()) { await Assert.ThrowsAsync<ArgumentNullException>("uri", () => client.StreamAsync(null, cts.Token)); await Assert.ThrowsAsync<ArgumentException>("token", () => client.StreamAsync(uri, CancellationToken.None)); } } [Fact] public async Task StreamAsync() { var uri = new Uri("wss://stream.binance.com:9443"); var client = new DefaultWebSocketClient(); using (var cts = new CancellationTokenSource()) { cts.Cancel(); await client.StreamAsync(uri, cts.Token); } } } }
Add the producer wrap to donet
using System; using System.Runtime.InteropServices; namespace RocketMQ.Interop { public static class ProducerWrap { // init [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr CreateProducer(string groupId); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int StartProducer(IntPtr producer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int ShutdownProducer(IntPtr producer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int DestroyProducer(IntPtr producer); // set parameters [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetProducerNameServerAddress(IntPtr producer, string nameServer); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetProducerLogPath(IntPtr producer, string logPath); [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)] public static extern int SetProducerLogLevel(IntPtr producer, CLogLevel level); //send [DllImport(ConstValues.RocketMQDriverDllName,CallingConvention = CallingConvention.Cdecl)] public static extern int SendMessageSync(IntPtr producer, IntPtr message, [Out]out CSendResult result); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSendResult { public int sendStatus; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string msgId; public long offset; } public enum CLogLevel { E_LOG_LEVEL_FATAL = 1, E_LOG_LEVEL_ERROR = 2, E_LOG_LEVEL_WARN = 3, E_LOG_LEVEL_INFO = 4, E_LOG_LEVEL_DEBUG = 5, E_LOG_LEVEL_TRACE = 6, E_LOG_LEVEL_LEVEL_NUM = 7 } }
Add the NBench visual studio test adapter project.
namespace NBench.VisualStudio.TestAdapter { using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System; using System.Collections.Generic; public class NBenchTestDiscoverer : ITestDiscoverer { public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { throw new NotImplementedException(); } } }
Add script for fixing tecture scaling
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class TextureTilingController : MonoBehaviour { // Give us the texture so that we can scale proportianally the width according to the height variable below // We will grab it from the meshRenderer //public Texture texture; //public float textureToMeshZ = 2f; // Use this to contrain texture to a certain size //Vector3 prevScale = Vector3.one; //float prevTextureToMeshZ = -1f; // Use this for initialization void Start () { //this.prevScale = gameObject.transform.lossyScale; //this.prevTextureToMeshZ = this.textureToMeshZ; this.UpdateTiling(); } // Update is called once per frame void Update () { // If something has changed //if(gameObject.transform.lossyScale != prevScale || !Mathf.Approximately(this.textureToMeshZ, prevTextureToMeshZ)) this.UpdateTiling(); // Maintain previous state variables //this.prevScale = gameObject.transform.lossyScale; //this.prevTextureToMeshZ = this.textureToMeshZ; } [ContextMenu("UpdateTiling")] void UpdateTiling() { // A Unity plane is 10 units x 10 units //float planeSizeX = gameObject.renderer.material.mainTextureScale.x; //float planeSizeZ = gameObject.renderer.material.mainTextureScale.y; // Figure out texture-to-mesh width based on user set texture-to-mesh height //float textureToMeshX = ((float)this.texture.width/this.texture.height)*this.textureToMeshZ; // gameObject.renderer.material.SetTextureScale ("", new Vector2 (1.0f .x, 1.0f / gameObject.transform.lossyScale.z)); gameObject.renderer.sharedMaterial.mainTextureScale = gameObject.transform.lossyScale * -1; //transform.renderer.material.mainTextureScale = new Vector2(XScale , YScale ); // gameObject.renderer.material.mainTextureScale = new Vector2(1.0f,1.0f); } }
Make primary key auto increment.
using System; namespace Toggl.Phoebe.Data.DataObjects { public abstract class CommonData { protected CommonData () { ModifiedAt = Time.UtcNow; } /// <summary> /// Initializes a new instance of the <see cref="Toggl.Phoebe.Data.DataObjects.CommonData"/> class copying /// the data from the other object. /// </summary> /// <param name="other">Instance to copy data from.</param> protected CommonData (CommonData other) { Id = other.Id; ModifiedAt = other.ModifiedAt; DeletedAt = other.DeletedAt; IsDirty = other.IsDirty; RemoteId = other.RemoteId; RemoteRejected = other.RemoteRejected; } [DontDirty] [SQLite.PrimaryKey] public Guid Id { get; set; } public DateTime ModifiedAt { get; set; } public DateTime? DeletedAt { get; set; } [DontDirty] public bool IsDirty { get; set; } [DontDirty] [SQLite.Unique] public long? RemoteId { get; set; } [DontDirty] public bool RemoteRejected { get; set; } } }
using System; using SQLite; namespace Toggl.Phoebe.Data.DataObjects { public abstract class CommonData { protected CommonData () { ModifiedAt = Time.UtcNow; } /// <summary> /// Initializes a new instance of the <see cref="Toggl.Phoebe.Data.DataObjects.CommonData"/> class copying /// the data from the other object. /// </summary> /// <param name="other">Instance to copy data from.</param> protected CommonData (CommonData other) { Id = other.Id; ModifiedAt = other.ModifiedAt; DeletedAt = other.DeletedAt; IsDirty = other.IsDirty; RemoteId = other.RemoteId; RemoteRejected = other.RemoteRejected; } [DontDirty] [PrimaryKey, AutoIncrement] public Guid Id { get; set; } public DateTime ModifiedAt { get; set; } public DateTime? DeletedAt { get; set; } [DontDirty] public bool IsDirty { get; set; } [DontDirty] [Unique] public long? RemoteId { get; set; } [DontDirty] public bool RemoteRejected { get; set; } } }
Add test coverage for ignoring null mods returned by rulesets
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Rulesets { [HeadlessTest] public class TestSceneBrokenRulesetHandling : OsuTestScene { [Resolved] private OsuGameBase gameBase { get; set; } = null!; [Test] public void TestNullModsReturnedByRulesetAreIgnored() { AddStep("set ruleset with null mods", () => Ruleset.Value = new TestRulesetWithNullMods().RulesetInfo); AddAssert("no null mods in available mods", () => gameBase.AvailableMods.Value.SelectMany(kvp => kvp.Value).All(mod => mod != null)); } #nullable disable // purposefully disabling nullability to simulate broken or unannotated API user code. private class TestRulesetWithNullMods : Ruleset { public override string ShortName => "nullmods"; public override string Description => "nullmods"; public override IEnumerable<Mod> GetModsFor(ModType type) => new Mod[] { null }; public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => null; public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => null; public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => null; } #nullable enable } }
Change the check range for BaseAddress and EntryPointAddress
// 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.Linq; using Xunit; namespace System.Diagnostics.Tests { public class ProcessModuleTests : ProcessTestBase { [Fact] public void TestModuleProperties() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.True(modules.Count > 0); foreach (ProcessModule module in modules) { Assert.NotNull(module); Assert.NotNull(module.FileName); Assert.NotEmpty(module.FileName); Assert.InRange(module.BaseAddress.ToInt64(), 0, long.MaxValue); Assert.InRange(module.EntryPointAddress.ToInt64(), 0, long.MaxValue); Assert.InRange(module.ModuleMemorySize, 0, long.MaxValue); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestModulesContainsCorerun() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("corerun")); } [Fact] [PlatformSpecific(PlatformID.Linux)] // OSX only includes the main module public void TestModulesContainsUnixNativeLibs() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("libcoreclr")); Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("System.Native")); } } }
// 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.Linq; using Xunit; namespace System.Diagnostics.Tests { public class ProcessModuleTests : ProcessTestBase { [Fact] public void TestModuleProperties() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.True(modules.Count > 0); foreach (ProcessModule module in modules) { Assert.NotNull(module); Assert.NotNull(module.FileName); Assert.NotEmpty(module.FileName); Assert.InRange(module.BaseAddress.ToInt64(), long.MinValue, long.MaxValue); Assert.InRange(module.EntryPointAddress.ToInt64(), long.MinValue, long.MaxValue); Assert.InRange(module.ModuleMemorySize, 0, long.MaxValue); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestModulesContainsCorerun() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("corerun")); } [Fact] [PlatformSpecific(PlatformID.Linux)] // OSX only includes the main module public void TestModulesContainsUnixNativeLibs() { ProcessModuleCollection modules = Process.GetCurrentProcess().Modules; Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("libcoreclr")); Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("System.Native")); } } }
Fix startup error - setup root view controller
using UIKit; using Foundation; namespace OpenGLESSampleGameView { // The name AppDelegate is referenced in the MainWindow.xib file. public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // If you have defined a view, add it here: // window.AddSubview (navigationController.View); glView.Run(60.0); window.MakeKeyAndVisible (); return true; } public override void OnResignActivation (UIApplication application) { glView.Stop(); glView.Run(5.0); } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { glView.Stop(); glView.Run(60.0); } } }
using UIKit; using Foundation; namespace OpenGLESSampleGameView { // The name AppDelegate is referenced in the MainWindow.xib file. public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { glView.Run (60.0); var rootViewController = new UIViewController { View = glView }; window.RootViewController = rootViewController; window.MakeKeyAndVisible (); return true; } public override void OnResignActivation (UIApplication application) { glView.Stop(); glView.Run(5.0); } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { glView.Stop(); glView.Run(60.0); } } }
Add unit tests for the P2pkhIssuanceImplicitLayout class
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading.Tasks; using Openchain.Ledger.Validation; using Xunit; namespace Openchain.Ledger.Tests { public class P2pkhIssuanceImplicitLayoutTests { private static readonly string address = "n12RA1iohYEerfXiBixSoERZG8TP8xQFL2"; private static readonly SignatureEvidence[] evidence = new[] { new SignatureEvidence(ByteString.Parse("abcdef"), ByteString.Empty) }; [Fact] public async Task GetPermissions_Root() { P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111)); PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse("/"), true, $"/asset/p2pkh/{address}/"); Assert.Equal(Access.Unset, result.AccountModify); Assert.Equal(Access.Permit, result.AccountNegative); Assert.Equal(Access.Unset, result.AccountSpend); Assert.Equal(Access.Unset, result.DataModify); } [Fact] public async Task GetPermissions_Modify() { P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111)); PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse($"/asset/p2pkh/mgToXgKQqY3asA76uYU82BXMLGrHNm5ZD9/"), true, $"/asset-path/"); Assert.Equal(Access.Permit, result.AccountModify); Assert.Equal(Access.Unset, result.AccountNegative); Assert.Equal(Access.Unset, result.AccountSpend); Assert.Equal(Access.Unset, result.DataModify); } [Fact] public async Task GetPermissions_Spend() { P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111)); PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse($"/asset/p2pkh/{address}/"), true, $"/asset-path/"); Assert.Equal(Access.Permit, result.AccountModify); Assert.Equal(Access.Unset, result.AccountNegative); Assert.Equal(Access.Permit, result.AccountSpend); Assert.Equal(Access.Permit, result.DataModify); } } }
Enable scanning at the assembly level for components for the dotnet CLI
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge { public class AssemblyComponentCatalog : IReadOnlyList<KeyValuePair<Guid, Func<Type>>> { private readonly IReadOnlyList<Assembly> _assemblies; private IReadOnlyList<KeyValuePair<Guid, Func<Type>>> _lookup; public AssemblyComponentCatalog(IReadOnlyList<Assembly> assemblies) { _assemblies = assemblies; } public KeyValuePair<Guid, Func<Type>> this[int index] { get { EnsureLoaded(); return _lookup[index]; } } public int Count { get { EnsureLoaded(); return _lookup.Count; } } public IEnumerator<KeyValuePair<Guid, Func<Type>>> GetEnumerator() { EnsureLoaded(); return _lookup.GetEnumerator(); } private void EnsureLoaded() { if(_lookup != null) { return; } Dictionary<Guid, Func<Type>> builder = new Dictionary<Guid, Func<Type>>(); foreach (Assembly asm in _assemblies) { foreach (Type type in asm.GetTypes()) { if (!typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(type) || type.GetTypeInfo().GetConstructor(Type.EmptyTypes) == null || !type.GetTypeInfo().IsClass) { continue; } IReadOnlyList<Type> registerFor = type.GetTypeInfo().ImplementedInterfaces.Where(x => x != typeof(IIdentifiedComponent) && typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(x)).ToList(); if (registerFor.Count == 0) { continue; } IIdentifiedComponent instance = (IIdentifiedComponent)Activator.CreateInstance(type); builder[instance.Id] = () => type; } } _lookup = builder.ToList(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
Add tests for the ConsoleWriter
using System; using Xunit; using OutputColorizer; using System.IO; namespace UnitTests { public partial class ConsoleWriterTests { [Fact] public void TestGetForegroundColor() { ConsoleWriter cw = new ConsoleWriter(); Assert.Equal(Console.ForegroundColor, cw.ForegroundColor); } [Fact] public void TestSetForegroundColor() { ConsoleWriter cw = new ConsoleWriter(); ConsoleColor before = Console.ForegroundColor; cw.ForegroundColor = ConsoleColor.Black; Assert.Equal(Console.ForegroundColor, ConsoleColor.Black); cw.ForegroundColor = before; Assert.Equal(Console.ForegroundColor, before); } [Fact] public void TestWrite() { ConsoleWriter cw = new ConsoleWriter(); StringWriter tw = new StringWriter(); Console.SetOut(tw); cw.Write("test"); cw.Write("bar"); Assert.Equal("testbar", tw.GetStringBuilder().ToString()); } [Fact] public void TestWriteLine() { ConsoleWriter cw = new ConsoleWriter(); StringWriter tw = new StringWriter(); Console.SetOut(tw); cw.WriteLine("test2"); cw.WriteLine("bar"); Assert.Equal("test2\nbar\n", tw.GetStringBuilder().ToString()); } } }
Add test that validates all reflected methods are non-null.
#region License // // Dasher // // Copyright 2015-2016 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/dasher // #endregion using System; using System.Reflection; using Xunit; namespace Dasher.Tests { public class MethodsTests { [Fact] public void AllReflectedMethodsNonNull() { var properties = typeof(DasherContext).GetTypeInfo().Assembly.GetType("Dasher.Methods", throwOnError: true).GetProperties(); foreach (var property in properties) { var value = property.GetValue(null); Assert.True(value != null, $"Dasher.Methods.{property.Name} shouldn't be null"); } } } }
Add work-in-progress ObjectOverrides pass that adds GetHashCode and Equals overrides.
using System; using System.Collections.Generic; using CppSharp.AST; using CppSharp.Generators; using CppSharp.Generators.CLI; using CppSharp.Passes; namespace CppSharp { public class ObjectOverridesPass : TranslationUnitPass { void OnUnitGenerated(GeneratorOutput output) { foreach (var template in output.Templates) { foreach (var block in template.FindBlocks(CLIBlockKind.MethodBody)) { var method = block.Declaration as Method; switch (method.Name) { case "GetHashCode": block.Write("return (int)NativePtr;"); break; case "Equals": block.WriteLine("if (!object) return false;"); block.Write("return Instance == safe_cast<ICppInstance^>({0})->Instance;", method.Parameters[0].Name); break; } } } } private bool isHooked; public override bool VisitClassDecl(Class @class) { // FIXME: Add a better way to hook the event if (!isHooked) { Driver.Generator.OnUnitGenerated += OnUnitGenerated; isHooked = true; } if (!VisitDeclaration(@class)) return false; if (AlreadyVisited(@class)) return true; if (@class.IsValueType) return false; var methodEqualsParam = new Parameter { Name = "object", QualifiedType = new QualifiedType(new CILType(typeof(Object))), }; var methodEquals = new Method { Name = "Equals", Namespace = @class, ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Bool)), Parameters = new List<Parameter> { methodEqualsParam }, IsSynthetized = true, IsOverride = true, IsProxy = true }; @class.Methods.Add(methodEquals); var methodHashCode = new Method { Name = "GetHashCode", Namespace = @class, ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Int32)), IsSynthetized = true, IsOverride = true, IsProxy = true }; @class.Methods.Add(methodHashCode); return true; } } }
Use PropertyInfo control in mobile apps
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Xamarin.Forms; namespace ProjectTracker.Ui.Xamarin.Xaml { public class BoolColorConverter : IValueConverter { public Color TrueColor { get; set; } public Color FalseColor { get; set; } public bool Invert { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var v = (bool)value; if (Invert) v = !v; if (v) return TrueColor; else return FalseColor; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Add a model for transitions
using System; using slang.Lexing.Tokens; namespace slang.Lexing.Trees.Nodes { public class Transition { public Transition (Node target, Func<Token> tokenProducer = null) { Target = target; TokenProducer = tokenProducer; } public Token GetToken() { if(TokenProducer != null) { return TokenProducer (); } return null; } public Func<Token> TokenProducer { get; private set; } public void Returns (Func<Token> tokenProducer) { TokenProducer = tokenProducer; } public Node Target { get; } } }
Add helper class to handle firing async multiplayer methods
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using osu.Framework.Logging; namespace osu.Game.Online.Multiplayer { public static class MultiplayerClientExtensions { public static void FireAndForget(this Task task, Action? onSuccess = null, Action<Exception>? onError = null) => task.ContinueWith(t => { if (t.IsFaulted) { Exception? exception = t.Exception; if (exception is AggregateException ae) exception = ae.InnerException; Debug.Assert(exception != null); string message = exception is HubException // HubExceptions arrive with additional message context added, but we want to display the human readable message: // "An unexpected error occurred invoking 'AddPlaylistItem' on the server.InvalidStateException: Can't enqueue more than 3 items at once." // We generally use the message field for a user-parseable error (eventually to be replaced), so drop the first part for now. ? exception.Message.Substring(exception.Message.IndexOf(':') + 1).Trim() : exception.Message; Logger.Log(message, level: LogLevel.Important); onError?.Invoke(exception); } else { onSuccess?.Invoke(); } }); } }
Add Singleton for the Session
using ScheduleManager.forms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ScheduleManager.model; namespace ScheduleManager.common { class SingletonSesion { private volatile static SingletonSesion objetoUsuarios; private static object bloqueoObjeto = new object(); private ScheduleManagerEntities contexto; private SingletonSesion() { } public static SingletonSesion CreacionInstancia() { if (objetoUsuarios == null) { lock (bloqueoObjeto) { if (objetoUsuarios == null) { objetoUsuarios = new SingletonSesion(); } } } return objetoUsuarios; } public void AñadirUsuarios(int usuario) { contexto = new ScheduleManagerEntities(); var query = contexto.Usuarios.FirstOrDefault(u => u.id_usuario == usuario && u.id_cuenta == 1); if (query != null) { UserAddForm forma = new UserAddForm(); forma.Show(); } else { MessageBox.Show("No tiene permiso"); } } } }
Check if the query is a projection-query before trying to add it to the cache (nhibernate will choke on that)
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate.Cache; using NHibernate.Cfg; using NHibernate.Engine; using NHibernate.Type; namespace BoC.Persistence.NHibernate.Cache { /// <summary> /// This class works around the bug that you can't request Projections /// when the query is set to cacheable... /// Should be fixed in the next nhibernate I hope, and then this class can be removed /// </summary> public class ProjectionEnabledQueryCache : StandardQueryCache, IQueryCache { public ProjectionEnabledQueryCache(Settings settings, IDictionary<string, string> props, UpdateTimestampsCache updateTimestampsCache, string regionName) : base(settings, props, updateTimestampsCache, regionName) {} bool IQueryCache.Put(QueryKey key, ICacheAssembler[] returnTypes, IList result, bool isNaturalKeyLookup, ISessionImplementor session) { //if the returntypes contains simple values, assume it's a projection: if (returnTypes.OfType<IType>().Any(t => t.ReturnedClass != null && (t.ReturnedClass.IsValueType || t.ReturnedClass.IsPrimitive || t.ReturnedClass == typeof(String)))) return false; return this.Put(key, returnTypes, result, isNaturalKeyLookup, session); } } public class ProjectionEnabledQueryCacheFactory : IQueryCacheFactory { public IQueryCache GetQueryCache(string regionName, UpdateTimestampsCache updateTimestampsCache, Settings settings, IDictionary<string, string> props) { return new ProjectionEnabledQueryCache(settings, props, updateTimestampsCache, regionName); } } }
Add the skeleton for the temp attachments module
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Attachments { /// <summary> /// A module that just holds commands for inspecting avatar appearance. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TempAttachmentsModule")] public class TempAttachmentsModule : INonSharedRegionModule { public void Initialise(IConfigSource configSource) { } public void AddRegion(Scene scene) { } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "TempAttachmentsModule"; } } } }
Revert change to message assertion as the message is consumer key dependent and the key in the CI build causes a failure
using System; using NUnit.Framework; using SevenDigital.Api.Wrapper.Exceptions; using SevenDigital.Api.Schema.ArtistEndpoint; using SevenDigital.Api.Schema.LockerEndpoint; namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions { [TestFixture] public class ApiXmlExceptionTests { [Test] public void Should_fail_correctly_if_xml_error_returned() { // -- Deliberate error response Console.WriteLine("Trying artist/details without artistId parameter..."); var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Artist>.Get.Please()); Assert.That(apiXmlException.Error.Code, Is.EqualTo(1001)); Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("Missing parameter artistId.")); } [Test] public void Should_fail_correctly_if_non_xml_error_returned_eg_unauthorised() { // -- Deliberate unauthorized response Console.WriteLine("Trying user/locker without any credentials..."); var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Locker>.Get.Please()); Assert.That(apiXmlException.Error.Code, Is.EqualTo(9001)); Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("OAuth authentication error: Not authorised - no user credentials provided")); } } }
using System; using NUnit.Framework; using SevenDigital.Api.Wrapper.Exceptions; using SevenDigital.Api.Schema.ArtistEndpoint; using SevenDigital.Api.Schema.LockerEndpoint; namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions { [TestFixture] public class ApiXmlExceptionTests { [Test] public void Should_fail_correctly_if_xml_error_returned() { // -- Deliberate error response Console.WriteLine("Trying artist/details without artistId parameter..."); var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Artist>.Get.Please()); Assert.That(apiXmlException.Error.Code, Is.EqualTo(1001)); Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("Missing parameter artistId.")); } [Test] public void Should_fail_correctly_if_non_xml_error_returned_eg_unauthorised() { // -- Deliberate unauthorized response Console.WriteLine("Trying user/locker without any credentials..."); var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Locker>.Get.Please()); Assert.That(apiXmlException.Error.Code, Is.EqualTo(9001)); Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("OAuth authentication error: Resource requires access token")); } } }
Add characterization tests for object members
namespace FakeItEasy.Specs { using FakeItEasy.Core; using FluentAssertions; using Xbehave; public static class ObjectMembersSpecs { [Scenario] public static void DefaultEqualsWithSelf(IFoo fake, bool equals) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "When Equals is called on the fake with the fake as the argument" .x(() => equals = fake.Equals(fake)); "Then it returns true" .x(() => equals.Should().BeTrue()); } [Scenario] public static void DefaultEqualsWithOtherFake(IFoo fake, IFoo otherFake, bool equals) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And another fake of the same type" .x(() => otherFake = A.Fake<IFoo>()); "When Equals is called on the first fake with the other fake as the argument" .x(() => equals = fake.Equals(otherFake)); "Then it returns false" .x(() => equals.Should().BeFalse()); } [Scenario] public static void DefaultGetHashCode(IFoo fake, FakeManager manager, int fakeHashCode) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And its manager" .x(() => manager = Fake.GetFakeManager(fake)); "When GetHashCode is called on the fake" .x(() => fakeHashCode = fake.GetHashCode()); "Then it returns the manager's hash code" .x(() => fakeHashCode.Should().Be(manager.GetHashCode())); } [Scenario] public static void DefaultToString(IFoo fake, string? stringRepresentation) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "When ToString is called on the fake" .x(() => stringRepresentation = fake.ToString()); "Then it should return a string representation of the fake" .x(() => stringRepresentation.Should().Be("Faked FakeItEasy.Specs.ObjectMembersSpecs+IFoo")); } public interface IFoo { void Bar(); } } }
Add ResourceFinder as an option that can be set.
namespace ZocMonLib.Web { public class WebSettingsExtensionOptions { public ISerializer Serializer { get; set; } public IRuntime Runtime { get; set; } public IStorageFactory StorageFactory { get; set; } public ISystemLoggerProvider LoggerProvider { get; set; } public IConfigProvider ConfigProvider { get; set; } } }
namespace ZocMonLib.Web { public class WebSettingsExtensionOptions { public IResourceFinder ResourceFinder { get; set; } public ISerializer Serializer { get; set; } public IRuntime Runtime { get; set; } public IStorageFactory StorageFactory { get; set; } public ISystemLoggerProvider LoggerProvider { get; set; } public IConfigProvider ConfigProvider { get; set; } } }
Support convert to or from struct type
// Copyright (c) kuicker.org. All rights reserved. // Modified By YYYY-MM-DD // kevinjong 2016-03-04 - Creation using System; namespace IsTo.Tests { public struct TestStruct { public int Property11; public int Property12; public int Property13; } }
Move sample to correct namespace
using BenchmarkDotNet.Tasks; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BenchmarkDotNet.Samples.Other { [BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)] public class Cpu_Atomics { private int a; private object syncRoot = new object(); [Benchmark] [OperationsPerInvoke(4)] public void Lock() { lock (syncRoot) a++; lock (syncRoot) a++; lock (syncRoot) a++; lock (syncRoot) a++; } [Benchmark] [OperationsPerInvoke(4)] public void Interlocked() { System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); } [Benchmark] [OperationsPerInvoke(4)] public void NoLock() { a++; a++; a++; a++; } } }
using BenchmarkDotNet.Tasks; namespace BenchmarkDotNet.Samples.CPU { [BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)] public class Cpu_Atomics { private int a; private object syncRoot = new object(); [Benchmark] [OperationsPerInvoke(4)] public void Lock() { lock (syncRoot) a++; lock (syncRoot) a++; lock (syncRoot) a++; lock (syncRoot) a++; } [Benchmark] [OperationsPerInvoke(4)] public void Interlocked() { System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); System.Threading.Interlocked.Increment(ref a); } [Benchmark] [OperationsPerInvoke(4)] public void NoLock() { a++; a++; a++; a++; } } }
Add test scene for `MultiplayerPlayer`
// 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.Testing; using osu.Game.Rulesets.Osu; using osu.Game.Screens.OnlinePlay.Multiplayer; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerPlayer : MultiplayerTestScene { private MultiplayerPlayer player; [SetUpSteps] public override void SetUpSteps() { base.SetUpSteps(); AddStep("set beatmap", () => { Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo); }); AddStep("initialise gameplay", () => { Stack.Push(player = new MultiplayerPlayer(Client.CurrentMatchPlayingItem.Value, Client.Room?.Users.ToArray())); }); } [Test] public void TestGameplay() { AddUntilStep("wait for gameplay start", () => player.LocalUserPlaying.Value); } } }
Add a method for getting settings UI components automatically from a target class
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Overlays.Settings; namespace osu.Game.Configuration { /// <summary> /// An attribute to mark a bindable as being exposed to the user via settings controls. /// Can be used in conjunction with <see cref="SettingSourceExtensions.CreateSettingsControls"/> to automatically create UI controls. /// </summary> [MeansImplicitUse] [AttributeUsage(AttributeTargets.Property)] public class SettingSourceAttribute : Attribute { public string Label { get; } public string Description { get; } public SettingSourceAttribute(string label, string description = null) { Label = label ?? string.Empty; Description = description ?? string.Empty; } } public static class SettingSourceExtensions { public static IEnumerable<Drawable> CreateSettingsControls(this object obj) { var configProperties = obj.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SettingSourceAttribute>(true) != null); foreach (var property in configProperties) { var attr = property.GetCustomAttribute<SettingSourceAttribute>(true); switch (property.GetValue(obj)) { case BindableNumber<float> bNumber: yield return new SettingsSlider<float> { LabelText = attr.Label, Bindable = bNumber }; break; case BindableNumber<double> bNumber: yield return new SettingsSlider<double> { LabelText = attr.Label, Bindable = bNumber }; break; case BindableNumber<int> bNumber: yield return new SettingsSlider<int> { LabelText = attr.Label, Bindable = bNumber }; break; case Bindable<bool> bBool: yield return new SettingsCheckbox { LabelText = attr.Label, Bindable = bBool }; break; } } } } }
Add possibility to mock ConfigurationManager
using System; using System.Configuration; using System.Linq; using System.Reflection; namespace UnitTests.Helpers { // the default app.config is used. /// <summary> /// Allow to override default configuration file access via ConfigurationService for piece of code /// Main purpose: unit tests /// Do not use it in production code /// </summary> /// <example> /// // the default app.config is used. /// using(AppConfig.Change(tempFileName)) /// { /// // the app.config in tempFileName is used /// } /// </example> public abstract class AppConfig : IDisposable { public abstract void Dispose(); public static AppConfig Change(string path) { return new ChangeAppConfig(path); } private class ChangeAppConfig : AppConfig { private readonly string oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); private bool disposedValue; public ChangeAppConfig(string path) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfigMechanism(); } public override void Dispose() { if (!disposedValue) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig); ResetConfigMechanism(); disposedValue = true; } GC.SuppressFinalize(this); } private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); } } } }
Add ApplicationUser class for Identity and DbContext
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace Gnx.Models { public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } //public System.Data.Entity.DbSet<Portal.Models.ModuleModels> ModuleModels { get; set; } } }
Create read-only dictionary for .NET version 2.0
#if PS20 using System; using System.Collections.Generic; namespace WpfCLR { public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { public const string ReadOnlyErrorMessage = "Dictionary is read-only"; private IDictionary<TKey, TValue> _innerDictionary; protected IDictionary<TKey, TValue> InnerDictionary { get { return _innerDictionary; } } public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _innerDictionary = dictionary; } #region IDictionary<TKey, TValue> members public TValue this[TKey key] { get { return _innerDictionary[key]; } } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return _innerDictionary[key]; } set { throw new NotSupportedException(ReadOnlyErrorMessage); } } public ICollection<TKey> Keys { get { return _innerDictionary.Keys; } } public ICollection<TValue> Values { get { return _innerDictionary.Values; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(ReadOnlyErrorMessage); } public bool ContainsKey(TKey key) { return _innerDictionary.ContainsKey(key); } bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(ReadOnlyErrorMessage); } public bool TryGetValue(TKey key, out TValue value) { return _innerDictionary.TryGetValue(key, out value); } #endregion #region ICollection<KeyValuePair<TKey, TValue>> members public int Count { get { return _innerDictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(ReadOnlyErrorMessage); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(ReadOnlyErrorMessage); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _innerDictionary.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _innerDictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(ReadOnlyErrorMessage); } #endregion #region IEnumerable members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _innerDictionary.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (_innerDictionary as System.Collections.IEnumerable).GetEnumerator(); } #endregion } } #endif
Sort chars by freq - monad
// https://leetcode.com/problems/sort-characters-by-frequency/ // https://leetcode.com/submissions/detail/83684155/ // // Submission Details // 34 / 34 test cases passed. // Status: Accepted // Runtime: 188 ms // Submitted: 0 minutes ago public class Solution { public string FrequencySort(string s) { return s.Aggregate(new Dictionary<char, int>(), (acc, x) => { if (!acc.ContainsKey(x)) { acc[x] = 0; } acc[x]++; return acc; }) .OrderByDescending(x => x.Value) .Aggregate(new StringBuilder(), (acc, x) => { acc.Append(new String(x.Key, x.Value)); return acc; }) .ToString(); } }
Fix inverted documentation between two methods
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.ComponentModel { /// <summary> /// Provides functionality to commit or rollback changes to an object that is used as a data source. /// </summary> public interface IEditableObject { /// <summary> /// Begins an edit on an object. /// </summary> void BeginEdit(); /// <summary> /// Discards changes since the last BeginEdit call. /// </summary> void EndEdit(); /// <summary> /// Pushes changes since the last BeginEdit into the underlying object. /// </summary> void CancelEdit(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.ComponentModel { /// <summary> /// Provides functionality to commit or rollback changes to an object that is used as a data source. /// </summary> public interface IEditableObject { /// <summary> /// Begins an edit on an object. /// </summary> void BeginEdit(); /// <summary> /// Pushes changes since the last BeginEdit into the underlying object. /// </summary> void EndEdit(); /// <summary> /// Discards changes since the last BeginEdit call. /// </summary> void CancelEdit(); } }
Check if an array is preorder
// http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/ // // Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, // else return false. Expected time complexity is O(n). // using System; using System.Collections.Generic; static class Program { static bool IsTraversal(this int[] a) { var stack = new Stack<int>(); var root = int.MinValue; foreach (var node in a) { if (node < root) { return false; } while (stack.Count != 0 && stack.Peek() < node) { root = stack.Pop(); } stack.Push(node); } return true; } static void Main() { if (!new [] {2, 4, 3}.IsTraversal()) { throw new Exception("You are weak, expected true"); } if (!new [] {40, 30, 35, 80, 100}.IsTraversal()) { throw new Exception("You are weak, expected true"); } if (new [] {2, 4, 1}.IsTraversal()) { throw new Exception("You are weak, expected false"); } if (new [] {40, 30, 35, 20, 80, 100}.IsTraversal()) { throw new Exception("You are weak, expected false"); } Console.WriteLine("All appears to be well"); } }
Revert "remove old assemblyinfo (wasn't included in the solution)"
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("IniFileParserTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IniFileParserTests")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("b45d3f26-a017-43e3-8f76-2516ad4ec9b2")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Add type to request comment help
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { class CommentHelpRequest { public static readonly RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object> Type = RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object>.Create("powershell/getCommentHelp"); } public class CommentHelpRequestResult { public string[] content; } public class CommentHelpRequestParams { public string DocumentUri { get; set; } public Position TriggerPosition { get; set; } } }
Introduce exponential backoff for executors
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Gremlin.Net.Driver.Exceptions; namespace ExRam.Gremlinq.Core { public static class GremlinQueryExecutorExtensions { private sealed class ExponentialBackoffExecutor : IGremlinQueryExecutor { [ThreadStatic] private static Random? _rnd; private const int MaxTries = 32; private readonly IGremlinQueryExecutor _baseExecutor; private readonly Func<int, ResponseException, bool> _shouldRetry; public ExponentialBackoffExecutor(IGremlinQueryExecutor baseExecutor, Func<int, ResponseException, bool> shouldRetry) { _baseExecutor = baseExecutor; _shouldRetry = shouldRetry; } public IAsyncEnumerable<object> Execute(object serializedQuery, IGremlinQueryEnvironment environment) { return AsyncEnumerable.Create(Core); async IAsyncEnumerator<object> Core(CancellationToken ct) { var hasSeenFirst = false; for (var i = 0; i < MaxTries; i++) { await using (var enumerator = _baseExecutor.Execute(serializedQuery, environment).GetAsyncEnumerator(ct)) { while (true) { try { if (!await enumerator.MoveNextAsync()) yield break; hasSeenFirst = true; } catch (ResponseException ex) { if (hasSeenFirst) throw; if (!_shouldRetry(i, ex)) throw; await Task.Delay((_rnd ??= new Random()).Next(i + 2) * 16, ct); break; } yield return enumerator.Current; } } } } } } public static IGremlinQueryExecutor RetryWithExponentialBackoff(this IGremlinQueryExecutor executor, Func<int, ResponseException, bool> shouldRetry) { return new ExponentialBackoffExecutor(executor, shouldRetry); } } }
Cover DelegateInvokingLoadBalancerCreator by unit tests.
using System; using System.Threading.Tasks; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.LoadBalancer { public class DelegateInvokingLoadBalancerCreatorTests { private readonly DelegateInvokingLoadBalancerCreator<FakeLoadBalancer> _creator; private readonly Func<DownstreamReRoute, IServiceDiscoveryProvider, ILoadBalancer> _creatorFunc; private readonly Mock<IServiceDiscoveryProvider> _serviceProvider; private DownstreamReRoute _reRoute; private ILoadBalancer _loadBalancer; private string _typeName; public DelegateInvokingLoadBalancerCreatorTests() { _creatorFunc = (reRoute, serviceDiscoveryProvider) => new FakeLoadBalancer(reRoute, serviceDiscoveryProvider); _creator = new DelegateInvokingLoadBalancerCreator<FakeLoadBalancer>(_creatorFunc); _serviceProvider = new Mock<IServiceDiscoveryProvider>(); } [Fact] public void should_return_expected_name() { this.When(x => x.WhenIGetTheLoadBalancerTypeName()) .Then(x => x.ThenTheLoadBalancerTypeIs("FakeLoadBalancer")) .BDDfy(); } [Fact] public void should_return_result_of_specified_creator_func() { var reRoute = new DownstreamReRouteBuilder() .Build(); this.Given(x => x.GivenAReRoute(reRoute)) .When(x => x.WhenIGetTheLoadBalancer()) .Then(x => x.ThenTheLoadBalancerIsReturned<FakeLoadBalancer>()) .BDDfy(); } private void GivenAReRoute(DownstreamReRoute reRoute) { _reRoute = reRoute; } private void WhenIGetTheLoadBalancer() { _loadBalancer = _creator.Create(_reRoute, _serviceProvider.Object); } private void WhenIGetTheLoadBalancerTypeName() { _typeName = _creator.Type; } private void ThenTheLoadBalancerIsReturned<T>() where T : ILoadBalancer { _loadBalancer.ShouldBeOfType<T>(); } private void ThenTheLoadBalancerTypeIs(string type) { _typeName.ShouldBe(type); } private class FakeLoadBalancer : ILoadBalancer { public FakeLoadBalancer(DownstreamReRoute reRoute, IServiceDiscoveryProvider serviceDiscoveryProvider) { ReRoute = reRoute; ServiceDiscoveryProvider = serviceDiscoveryProvider; } public DownstreamReRoute ReRoute { get; } public IServiceDiscoveryProvider ServiceDiscoveryProvider { get; } public Task<Response<ServiceHostAndPort>> Lease(DownstreamContext context) { throw new NotImplementedException(); } public void Release(ServiceHostAndPort hostAndPort) { throw new NotImplementedException(); } } } }
Add http request reason provider for Abp.Web
using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using System.Web; namespace Abp.Web.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason { get { if (OverridedValue != null) { return OverridedValue.Reason; } return HttpContext.Current?.Request.Url.AbsoluteUri; } } public HttpRequestEntityChangeSetReasonProvider( IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { } } }
Add usability overload for IMockFactory
using System; using System.ComponentModel; using System.Reflection; namespace Moq.Sdk { /// <summary> /// Usability functions for <see cref="IMockFactory"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static class MockFactoryExtensions { /// <summary> /// Creates a mock with the given parameters. /// </summary> /// <param name="mocksAssembly">Assembly where compile-time generated mocks exist.</param> /// <param name="baseType">The base type (or main interface) of the mock.</param> /// <returns>A mock that implements <see cref="IMocked"/> in addition to the specified interfaces (if any).</returns> public static T CreateMock<T>(this IMockFactory factory, Assembly mocksAssembly) => (T)factory.CreateMock(mocksAssembly, typeof(T), new Type[0], new object[0]); } }
Test to verify that minimal message body can be redelivered via the delayed transport (serialization issue)
namespace MassTransit.Tests { using System; using System.Linq; using System.Threading.Tasks; using MassTransit.Serialization; using NUnit.Framework; using TestFramework; using TestFramework.Messages; [TestFixture] public class When_consuming_a_minimal_message_body : InMemoryTestFixture { [Test] public async Task Should_use_the_correct_intervals_for_each_redelivery() { await InputQueueSendEndpoint.Send(new PingMessage(), x => x.Serializer = new CopyBodySerializer(SystemTextJsonMessageSerializer.JsonContentType, new StringMessageBody(@" { ""message"": { ""CorrelationId"": ""9BBCF5F0-596E-4E90-B3C5-1B27358C5AEB"" }, ""messageType"": [ ""urn:message:MassTransit.TestFramework.Messages:PingMessage"" ] } "))); await Task.WhenAll(_received.Select(x => x.Task)); Assert.That(_timestamps[1] - _timestamps[0], Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(0.9))); TestContext.Out.WriteLine("Interval: {0}", _timestamps[1] - _timestamps[0]); } TaskCompletionSource<ConsumeContext<PingMessage>>[] _received; int _count; DateTime[] _timestamps; protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _count = 0; _received = new[] { GetTask<ConsumeContext<PingMessage>>(), GetTask<ConsumeContext<PingMessage>>() }; _timestamps = new DateTime[2]; configurator.UseDelayedRedelivery(r => r.Intervals(1000)); configurator.Handler<PingMessage>(async context => { _received[_count].TrySetResult(context); _timestamps[_count] = DateTime.Now; _count++; throw new IntentionalTestException("I'm so not ready for this jelly."); }); } } }
Remove dupes from list II
// https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ // Given a sorted linked list, delete all nodes that have duplicate numbers, // leaving only distinct numbers from the original list. // https://leetcode.com/submissions/detail/58844735/ // // Submission Details // 166 / 166 test cases passed. // Status: Accepted // Runtime: 152 ms // // Submitted: 0 minutes ago // You are here! // Your runtime beats 95.74% of csharpsubmissions. public class Solution { public ListNode DeleteDuplicates(ListNode head) { var dummy = new ListNode(-1) { next = head }; var last = dummy; var it = head; while (it != null) { while (it.next != null && it.val == it.next.val) { it = it.next; } if (last.next == it) { last = last.next; } else { last.next = it.next; } it = it.next; } return dummy.next; } }
Add tests for converting RGB with HSV
namespace BigEgg.Tools.PowerMode.Tests.Utils { using System.Drawing; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using BigEgg.Tools.PowerMode.Utils; public class ColorExtensionTest { [TestClass] public class HSVConvert { [TestMethod] public void ConvertTest() { var colorProperties = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public); var colors = colorProperties.ToDictionary(p => p.Name, p => (Color)p.GetValue(null, null)); foreach (var color in colors) { color.Value.ColorToHSV(out double hue, out double saturation, out double value); var newColor = ColorExtensions.ColorFromHSV(hue, saturation, value); Assert.AreEqual(color.Value.R, newColor.R); Assert.AreEqual(color.Value.G, newColor.G); Assert.AreEqual(color.Value.B, newColor.B); } } } } }
Copy Text objects to other layer and delete surce
//Synchronous template //----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 30.03.2017 // Autor Guenther.Schindler // // Empty template to fill for synchronous script. //----------------------------------------------------------------------------------- // GUID newScript_636264684078812126 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; using System.Collections; // example line to import dll DLLImport C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\searchedDLL.dll; //this line includes a custom dll, e.g. your own dll or other microsoft dlls namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { IFilter filter = new IFilter(parent); //your code here foreach (ILayer layer in parent.GetCurrentStep().GetActiveLayerList()) { List<IODBObject> objectsToMove = new List<IODBObject>(); foreach (IODBObject obj in layer.GetAllLayerObjects()) { foreach (DictionaryEntry entry in obj.GetAttributes()) { if (entry.Key.ToString() == "_string") { objectsToMove.Add((IODBObject)obj); } } } IODBLayer newLayer = filter.CreateEmptyODBLayer(layer.GetLayerName() + "_1", parent.GetCurrentStep().Name); filter.InsertElementsToLayer(0, newLayer, objectsToMove, new PointD(0, 0), false, false, 0); foreach (IODBObject mo in objectsToMove) { ((IODBLayer)layer).RemoveObject(mo); } } parent.UpdateControlsAndResetView(); } } }
Implement betting and getting popular keywords
using System; using StackExchange.Redis; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace CollapsedToto { [Prefix("/round")] public class RoundModule : BaseModule { private static ConnectionMultiplexer redis = null; private static IDatabase Database { get { if (redis == null) { redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,resolveDns=True"); } return redis.GetDatabase(); } } private string CurrentRoundKey = "CurrentRound"; public RoundModule() { } [Get("/popular")] public async Task<dynamic> PopularKeyword(dynamic param, CancellationToken ct) { SortedSetEntry[] values = await Database.SortedSetRangeByRankWithScoresAsync(CurrentRoundKey, 0, 30); return JsonConvert.SerializeObject(values); } [Post("/bet")] public async Task<dynamic> BettingKeyword(dynamic param, CancellationToken ct) { bool result = false; dynamic data = Request.Form; if (data.Count == 0) { data = Request.Query; } string keyword = (data["keyword"].ToString()).Trim(); int point = int.Parse(data["point"].ToString()); await Database.SortedSetIncrementAsync(CurrentRoundKey, keyword, 1.0); // TODO: subtract user point result = true; return JsonConvert.SerializeObject(result); } } }
Add benchmark for dependency injection.
/* using BenchmarkDotNet.Attributes; using Robust.Shared.IoC; namespace Content.Benchmarks { // To actually run this benchmark you'll have to make DependencyCollection public so it's accessible. public class DependencyInjectBenchmark { [Params(InjectMode.Reflection, InjectMode.DynamicMethod)] public InjectMode Mode { get; set; } private DependencyCollection _dependencyCollection; [GlobalSetup] public void Setup() { _dependencyCollection = new DependencyCollection(); _dependencyCollection.Register<X1, X1>(); _dependencyCollection.Register<X2, X2>(); _dependencyCollection.Register<X3, X3>(); _dependencyCollection.Register<X4, X4>(); _dependencyCollection.Register<X5, X5>(); _dependencyCollection.BuildGraph(); switch (Mode) { case InjectMode.Reflection: break; case InjectMode.DynamicMethod: // Running this without oneOff will cause DependencyCollection to cache the DynamicMethod injector. // So future injections (even with oneOff) will keep using the DynamicMethod. // AKA, be fast. _dependencyCollection.InjectDependencies(new TestDummy()); break; } } [Benchmark] public void Inject() { _dependencyCollection.InjectDependencies(new TestDummy(), true); } public enum InjectMode { Reflection, DynamicMethod } private sealed class X1 { } private sealed class X2 { } private sealed class X3 { } private sealed class X4 { } private sealed class X5 { } private sealed class TestDummy { [Dependency] private readonly X1 _x1; [Dependency] private readonly X2 _x2; [Dependency] private readonly X3 _x3; [Dependency] private readonly X4 _x4; [Dependency] private readonly X5 _x5; } } } */
Add texture cropping test case
// 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.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Testing; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTextureCropping : GridTestScene { public TestSceneTextureCropping() : base(3, 3) { } protected override void LoadComplete() { base.LoadComplete(); for (int i = 0; i < Rows; ++i) { for (int j = 0; j < Cols; ++j) { RectangleF cropRectangle = new RectangleF(i / 3f, j / 3f, 1 / 3f, 1 / 3f); Cell(i, j).AddRange(new Drawable[] { new SpriteText { Text = $"{cropRectangle}", Font = new FontUsage(size: 14), }, new Container { RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Anchor = Anchor.Centre, Origin = Anchor.Centre, Masking = true, Children = new Drawable[] { new Sprite { RelativeSizeAxes = Axes.Both, Texture = texture.Crop(cropRectangle, relativeSizeAxes: Axes.Both), Anchor = Anchor.Centre, Origin = Anchor.Centre, } } } }); } } } private Texture texture; [BackgroundDependencyLoader] private void load(TextureStore store) { texture = store.Get(@"sample-texture"); } } }
Add comment for OSX specific FileSystem test
// 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.Diagnostics; using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase { [Fact] public void Null_Path_Throws_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null)); } [Fact] public void Empty_Path_Throws_ArgumentException() { Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty)); } [Fact] public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath())); } [Fact] public void SetToValidOtherDirectory() { RemoteInvoke(() => { Directory.SetCurrentDirectory(TestDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase { [Fact] public void Null_Path_Throws_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null)); } [Fact] public void Empty_Path_Throws_ArgumentException() { Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty)); } [Fact] public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath())); } [Fact] public void SetToValidOtherDirectory() { RemoteInvoke(() => { Directory.SetCurrentDirectory(TestDirectory); // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } } }
Add unit tests for the SqlServerStorageEngine class
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Openchain.Sqlite.Tests { public class SqlServerStorageEngineTests : BaseStorageEngineTests { private readonly int instanceId; public SqlServerStorageEngineTests() { Random rnd = new Random(); this.instanceId = rnd.Next(0, int.MaxValue); this.Store = CreateNewEngine(); } protected override IStorageEngine CreateNewEngine() { SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", this.instanceId, TimeSpan.FromSeconds(10)); engine.OpenConnection().Wait(); return engine; } } }
Change console URL for 1 code sample
// Download the twilio-csharp library from twilio.com/docs/csharp/install using System; using Twilio.Lookups; class Example { static void Main(string[] args) { // Find your Account Sid and Auth Token at twilio.com/user/account const string accountSid = "{{ account_sid }}"; const string authToken = "{{ auth_token }}"; var lookupsClient = new LookupsClient(accountSid, authToken); // Look up a phone number in E.164 format var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true); Console.WriteLine(phoneNumber.Carrier.Type); Console.WriteLine(phoneNumber.Carrier.Name); } }
// Download the twilio-csharp library from twilio.com/docs/csharp/install using System; using Twilio.Lookups; class Example { static void Main(string[] args) { // Find your Account Sid and Auth Token at twilio.com/console const string accountSid = "{{ account_sid }}"; const string authToken = "{{ auth_token }}"; var lookupsClient = new LookupsClient(accountSid, authToken); // Look up a phone number in E.164 format var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true); Console.WriteLine(phoneNumber.Carrier.Type); Console.WriteLine(phoneNumber.Carrier.Name); } }
Add order item delete support
@model Orders.com.Web.MVC.ViewModels.OrderItemViewModel @{ ViewBag.Title = "Delete"; } <h2>Delete Item</h2> <h3>Are you sure you want to delete this?</h3> <div class="form-horizontal"> <div class="form-group"> <label class="control-label col-md-1">Category</label> <div class="col-md-10"> @Html.DisplayFor(model => model.AssociatedCategory.Name) </div> </div> <div class="form-group"> <label class="control-label col-md-1">Product</label> <div class="col-md-10"> @Html.DisplayFor(model => model.AssociatedProduct.Name) </div> </div> <div class="form-group"> <label class="control-label col-md-1">Price</label> <div class="col-md-10"> @Html.DisplayFor(model => model.Price) </div> </div> <div class="form-group"> <label class="control-label col-md-1">Quantity</label> <div class="col-md-10"> @Html.DisplayFor(model => model.Quantity) </div> </div> <div class="form-group"> <label class="control-label col-md-1">Amount</label> <div class="col-md-10"> @Html.DisplayFor(model => model.Amount) </div> </div> <div class="form-group"> <label class="control-label col-md-1">Status</label> <div class="col-md-10"> @Html.DisplayFor(model => model.Status) </div> </div> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-actions no-color"> <input type="submit" value="Delete" class="btn btn-default" /> | @Html.ActionLink("Back to List", "Edit", "Orders", new { id = Model.OrderID }, null) </div> } </div>
Create a class that acts as a configuration node for cache providers
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Configuration; using Nohros.Resources; namespace Nohros.Configuration { /// <summary> /// Contains configuration informations for cache providers. /// </summary> public class CacheProviderNode : ProviderNode { /// <summary> /// Initializes a new instance of the <see cref="CacheProviderNode"/> class by using the specified /// provider name and type. /// </summary> /// <param name="name">The name of the provider.</param> /// <param name="type">The assembly-qualified name of the provider type.</param> public CacheProviderNode(string name, string type) : base(name, type) { } /// <summary> /// Parses a XML node that contains information about the provider. /// </summary> /// <param name="node">The XML node to parse.</param> /// <param name="config">A <see cref="NohrosConfiguration"/> object containing the provider configuration /// informations.</param> /// <exception cref="System.Configuration.ConfigurationErrorsException">The <paramref name="node"/> is not a /// valid representation of a messenger provider.</exception> public override void Parse(XmlNode node, NohrosConfiguration config) { InternalParse(node, config); } } }
Add a more specific GenericListModel to reduce the amount of code
using System.Collections; using System.Collections.Generic; using Xe.Tools.Wpf.Models; namespace OpenKh.Tools.Common.Models { public class MyGenericListModel<T> : GenericListModel<T>, IEnumerable<T> { public MyGenericListModel(IEnumerable<T> list) : base(list) { } public IEnumerator<T> GetEnumerator() => Items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator(); protected override T OnNewItem() => throw new System.NotImplementedException(); } }
Add realtime multiplayer test scene
// 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.Screens.Multi.Components; namespace osu.Game.Tests.Visual.RealtimeMultiplayer { public class TestSceneRealtimeMultiplayer : RealtimeMultiplayerTestScene { public TestSceneRealtimeMultiplayer() { var multi = new TestRealtimeMultiplayer(); AddStep("show", () => LoadScreen(multi)); AddUntilStep("wait for loaded", () => multi.IsLoaded); } private class TestRealtimeMultiplayer : Screens.Multi.RealtimeMultiplayer.RealtimeMultiplayer { protected override RoomManager CreateRoomManager() => new TestRealtimeRoomManager(); } } }
Add tests for Get & AddToPayload
using Bugsnag.Payload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Bugsnag.Tests { public class PayloadExtensionsTests { [Theory] [MemberData(nameof(PayloadTestData))] public void AddToPayloadTests(Dictionary<string, object> dictionary, string key, object value, object expectedValue) { dictionary.AddToPayload(key, value); if (expectedValue == null) { Assert.DoesNotContain(key, dictionary.Keys); } else { Assert.Equal(expectedValue, dictionary[key]); } } public static IEnumerable<object[]> PayloadTestData() { yield return new object[] { new Dictionary<string, object>(), "key", 1, 1 }; yield return new object[] { new Dictionary<string, object>(), "key", null, null }; yield return new object[] { new Dictionary<string, object>(), "key", "", null }; yield return new object[] { new Dictionary<string, object>(), "key", "value", "value" }; yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", null, null }; yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", "", null }; } [Fact] public void GetExistingKey() { var dictionary = new Dictionary<string, object> { { "key", "value" } }; Assert.Equal("value", dictionary.Get("key")); } [Fact] public void GetNonExistentKeyReturnsNull() { var dictionary = new Dictionary<string, object>(); Assert.Null(dictionary.Get("key")); } } }
Add test case for TypeRegistry
using Htc.Vita.Core.Util; using Xunit; namespace Htc.Vita.Core.Tests { public class TypeRegistryTest { [Fact] public static void Default_0_RegisterDefault() { TypeRegistry.RegisterDefault<BaseClass, SubClass1>(); } [Fact] public static void Default_1_Register() { TypeRegistry.RegisterDefault<BaseClass, SubClass1>(); TypeRegistry.Register<BaseClass, SubClass2>(); } [Fact] public static void Default_2_GetInstance() { TypeRegistry.RegisterDefault<BaseClass, SubClass1>(); TypeRegistry.Register<BaseClass, SubClass2>(); var obj = TypeRegistry.GetInstance<BaseClass>(); Assert.False(obj is SubClass1); Assert.True(obj is SubClass2); } } public abstract class BaseClass { } public class SubClass1 : BaseClass { } public class SubClass2 : BaseClass { } }
Create Global Supressions for CA warnings on THNETII.CommandLine.Hosting
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Reliability", "CA2007: Consider calling ConfigureAwait on the awaited task")] [assembly: SuppressMessage("Design", "CA1062: Validate arguments of public methods")] [assembly: SuppressMessage("Globalization", "CA1303: Do not pass literals as localized parameters")]
Add test coverage of login dialog
// 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.Testing; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Login; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneLoginPanel : OsuManualInputManagerTestScene { private LoginPanel loginPanel; [SetUpSteps] public void SetUpSteps() { AddStep("create login dialog", () => { Add(loginPanel = new LoginPanel { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 0.5f, }); }); } [Test] public void TestBasicLogin() { AddStep("logout", () => API.Logout()); AddStep("enter password", () => loginPanel.ChildrenOfType<OsuPasswordTextBox>().First().Text = "password"); AddStep("submit", () => loginPanel.ChildrenOfType<OsuButton>().First(b => b.Text.ToString() == "Sign in").TriggerClick()); } } }
Add .net 4.5 compatibility shim classes
// ---------------------------------------------------- // THIS WHOLE File CAN GO AWAY WHEN WE TARGET 4.5 ONLY // ---------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Octokit { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>> { bool ContainsKey(TKey key); bool TryGetValue(TKey key, out TValue value); TValue this[TKey key] { get; } IEnumerable<TKey> Keys { get; } IEnumerable<TValue> Values { get; } } public interface IReadOnlyCollection<out T> : IEnumerable<T> { int Count { get; } } public class ReadOnlyCollection<TItem> : IReadOnlyCollection<TItem> { readonly List<TItem> _source; public ReadOnlyCollection(IEnumerable<TItem> source) { _source = new List<TItem>(source); } public IEnumerator<TItem> GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return _source.Count; } } } [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public class ReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { readonly IDictionary<TKey, TValue> _source; public ReadOnlyDictionary(IDictionary<TKey, TValue> source) { _source = new Dictionary<TKey, TValue>(source); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return _source.Count; } } public bool ContainsKey(TKey key) { return _source.ContainsKey(key); } public bool TryGetValue(TKey key, out TValue value) { return _source.TryGetValue(key, out value); } public TValue this[TKey key] { get { return _source[key]; } } public IEnumerable<TKey> Keys { get { return _source.Keys; } } public IEnumerable<TValue> Values { get { return _source.Values; } } } }
Add view model factory interface
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhotoLife.Factories { interface IViewModelFactory { } }
Add an expression interpretation bug test
using System; using System.Linq.Expressions; using Xunit; namespace ExpressionToCodeTest { public class ExpressionInterpretationBug { struct AStruct { public int AValue; } class SomethingMutable { public AStruct AStructField; } static Expression<Func<T>> Expr<T>(Expression<Func<T>> e) => e; [Fact] public void DotNetCoreIsNotBuggy() { var expr_compiled = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(false)(); Assert.Equal(2, expr_compiled.AStructField.AValue); var expr_interpreted = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(true)(); Assert.Equal(2, expr_interpreted.AStructField.AValue); } } }
Add benchmarks for bindable binding
// 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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { private Bindable<int> bindable; [GlobalSetup] public void GlobalSetup() => bindable = new Bindable<int>(); /// <summary> /// Creates an instance of the bindable directly by construction. /// </summary> [Benchmark(Baseline = true)] public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>(); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>. /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>. /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true); } }
Replace missing file lost during merge
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Orchard.Alias.Implementation.Holder; using Orchard.Alias.Implementation.Storage; namespace Orchard.Alias.Implementation.Updater { public interface IAliasHolderUpdater : IDependency { void Refresh(); } public class AliasHolderUpdater : IAliasHolderUpdater { private readonly IAliasHolder _aliasHolder; private readonly IAliasStorage _storage; private readonly IAliasUpdateCursor _cursor; public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage, IAliasUpdateCursor cursor) { _aliasHolder = aliasHolder; _storage = storage; _cursor = cursor; } public void Refresh() { // only retreive aliases which have not been processed yet var aliases = _storage.List(x => x.Id > _cursor.Cursor).ToArray(); // update the last processed id if (aliases.Any()) { _cursor.Cursor = aliases.Last().Item5; _aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 })); } } } }
Add a static resources library
// Resources.cs // <copyright file="Resources.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EnigmaUtilities { /// <summary> /// A static class with commonly used functions throughout multiple classes. /// </summary> public static class Resources { /// <summary> /// Gets the alphabet as a string. /// </summary> public static string Alphabet { get { return "abcdefghijkmnopqrstuvwxyz"; } } /// <summary> /// Performs modulus operations on an integer. /// </summary> /// <param name="i"> The integer to modulus. </param> /// <param name="j"> The integer to modulus by. </param> /// <returns> The integer after modulus operations. </returns> /// <remarks> Performs negative modulus python style. </remarks> public static int Mod(int i, int j) { return ((i % j) + j) % j; } /// <summary> /// Gets the character value of an integer. /// </summary> /// <param name="i"> The integer to convert to a character. </param> /// <returns> The character value of the integer. </returns> public static char ToChar(this int i) { return Alphabet[Mod(i, 26)]; } /// <summary> /// Gets the index in the alphabet of a character. /// </summary> /// <param name="c"> The character to convert to an integer. </param> /// <returns> The integer value of the character. </returns> /// <remarks> Will return -1 if not in the alphabet. </remarks> public static int ToInt(this char c) { return Alphabet.Contains(c) ? Alphabet.IndexOf(c) : -1; } } }
Add namespace & type for experimental work
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2018 Atif Aziz. 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. #endregion namespace MoreLinq.Experimental { using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. THE METHODS ARE EXPERIMENTAL. /// THEY MAY BE UNSTABLE AND UNTESTED. THEY MAY BE REMOVED FROM A FUTURE /// MAJOR OR MINOR RELEASE AND POSSIBLY WITHOUT NOTICE. USE THEM AT YOUR /// OWN RISK. THE METHODS ARE PUBLISHED FOR FIELD EXPERIMENTATION TO /// SOLICIT FEEDBACK ON THEIR UTILITY AND DESIGN/IMPLEMENTATION DEFECTS. /// </summary> public static partial class ExperimentalEnumerable { } }
Add failing test for compiled queries with Includes
using Marten.Linq; using Marten.Services; using Marten.Services.Includes; using Marten.Testing.Documents; using Shouldly; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; namespace Marten.Testing.Bugs { public class compiled_query_problem_with_includes_and_ICompiledQuery_reuse : DocumentSessionFixture<IdentityMap> { public class IssueWithUsers : ICompiledListQuery<Issue> { public List<User> Users { get; set; } // Can also work like that: //public List<User> Users => new List<User>(); public Expression<Func<IQueryable<Issue>, IEnumerable<Issue>>> QueryIs() { return query => query.Include<Issue, IssueWithUsers>(x => x.AssigneeId, x => x.Users, JoinType.Inner); } } [Fact] public void can_get_includes_with_compiled_queries() { var user1 = new User(); var user2 = new User(); var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted" }; var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" }; var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" }; theSession.Store(user1, user2); theSession.Store(issue1, issue2, issue3); theSession.SaveChanges(); // Issue first query using (var session = theStore.QuerySession()) { var query = new IssueWithUsers(); var issues = session.Query(query).ToArray(); query.Users.Count.ShouldBe(2); issues.Count().ShouldBe(3); query.Users.Any(x => x.Id == user1.Id); query.Users.Any(x => x.Id == user2.Id); } // Issue second query using (var session = theStore.QuerySession()) { var query = new IssueWithUsers(); var issues = session.Query(query).ToArray(); // Should populate this instance of IssueWithUsers query.Users.ShouldNotBeNull(); // Should not re-use a previous instance of IssueWithUsers, which would make the count 4 query.Users.Count.ShouldBe(2); issues.Count().ShouldBe(3); query.Users.Any(x => x.Id == user1.Id); query.Users.Any(x => x.Id == user2.Id); } } } }
Set up timer so that it can't start reducing while previous reduction is still in progress.
using System; namespace ZocMonLib.Service.Reduce { public class ReduceServiceRunner { private readonly ISystemLogger _logger; private System.Timers.Timer _timer; private readonly ISettings _settings; public ReduceServiceRunner(ISettings settings) { _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner)); _settings = settings; } public void Start() { Log("ReduceServiceRunner - Starting"); if (_settings.Enabled) { Log("ReduceServiceRunner - Timing setup"); _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => { Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _settings.RecordReduce.ReduceAll(false); Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); }; _timer.Start(); } } public void Stop() { Log("ReduceServiceRunner - Finished"); if (_timer != null) _timer.Stop(); } private void Log(string info) { _logger.Info(info); Console.WriteLine(info); } } }
using System; namespace ZocMonLib.Service.Reduce { public class ReduceServiceRunner { private readonly ISystemLogger _logger; private System.Timers.Timer _timer; private readonly ISettings _settings; public ReduceServiceRunner(ISettings settings) { _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner)); _settings = settings; } public void Start() { Log("ReduceServiceRunner - Starting"); if (_settings.Enabled) { Log("ReduceServiceRunner - Timing setup"); _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = false }; _timer.Elapsed += (sender, eventArgs) => { Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _settings.RecordReduce.ReduceAll(false); Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _timer.Start(); }; _timer.Start(); } } public void Stop() { Log("ReduceServiceRunner - Finished"); if (_timer != null) _timer.Stop(); } private void Log(string info) { _logger.Info(info); Console.WriteLine(info); } } }
Add test to cover `RegisterBlockHelper` readme example
using System.Collections.Generic; using Xunit; namespace HandlebarsDotNet.Test { public class ReadmeTests { [Fact] public void RegisterBlockHelper() { var handlebars = Handlebars.Create(); handlebars.RegisterHelper("StringEqualityBlockHelper", (output, options, context, arguments) => { if (arguments.Length != 2) { throw new HandlebarsException("{{#StringEqualityBlockHelper}} helper must have exactly two arguments"); } var left = arguments.At<string>(0); var right = arguments[1] as string; if (left == right) options.Template(output, context); else options.Inverse(output, context); }); var animals = new Dictionary<string, string> { {"Fluffy", "cat" }, {"Fido", "dog" }, {"Chewy", "hamster" } }; var template = "{{#each this}}The animal, {{@key}}, {{#StringEqualityBlockHelper @value 'dog'}}is a dog{{else}}is not a dog{{/StringEqualityBlockHelper}}.\r\n{{/each}}"; var compiledTemplate = handlebars.Compile(template); string templateOutput = compiledTemplate(animals); Assert.Equal( "The animal, Fluffy, is not a dog.\r\n" + "The animal, Fido, is a dog.\r\n" + "The animal, Chewy, is not a dog.\r\n", templateOutput ); } } }
Add usage examples for double-checking doc examples.
using System; using System.Collections.Generic; using System.Text; using Xunit; using static Nito.ConnectedProperties.ConnectedProperty; namespace UnitTests { class UsageExamples { [Fact] public void SimpleUsage() { var obj = new object(); var nameProperty = GetConnectedProperty(obj, "Name"); nameProperty.Set("Bob"); Assert.Equal("Bob", ReadName(obj)); } private static string ReadName(object obj) { var nameProperty = GetConnectedProperty(obj, "Name"); return nameProperty.Get(); } } }
Add path.cs to source control
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chutes.Optimization.Entities { public class Path { LinkedList<Gamespace> _path = new LinkedList<Gamespace>(); public Path() { _path.Clear(); } public Gamespace Add(Gamespace space) { if (_path.Any()) _path.AddAfter(_path.Last, space); else _path.AddFirst(space); return space; } public int Length { get { return _path.Count; } } public int RollCount { get { return _path.Where(s => !s.PathTo.HasValue).Count(); } } public override string ToString() { var sb = new StringBuilder(); foreach (var item in _path) sb.Append(item.Index.ToString("00") + " "); return sb.ToString(); } public IEnumerable<Gamespace> Reverse() { throw new NotImplementedException(); } } }
Add coin flipping command. Sometimes lands on it's side. No idea why!
using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 1) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } }
Add suport of nullable reference type attributes for lower TFM
#if !NETSTANDARD2_1 namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } #endif
Add the builder of DateRange
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace NBi.Core.Members.Ranges { internal class DateRangeBuilder : BaseBuilder { protected new DateRange Range { get { return (DateRange)base.Range; } } protected override void InternalBuild() { if (string.IsNullOrEmpty(Range.Format)) Result = Build(Range.Start, Range.End, Range.Culture, ToShortDatePattern); else Result = Build(Range.Start, Range.End, Range.Culture, Range.Format); } public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, Func<CultureInfo, DateTime, string> dateFormatter) { var list = new List<string>(); var date= start; while (date <= end) { var dateString = dateFormatter(culture, date); list.Add(dateString); date = date.AddDays(1); } return list; } public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, string format) { var list = new List<string>(); var date = start; while (date <= end) { var dateString = date.ToString(format, culture.DateTimeFormat); list.Add(dateString); date = date.AddDays(1); } return list; } protected string ToLongDatePattern(CultureInfo culture, DateTime value) { return value.ToString(culture.DateTimeFormat.LongDatePattern); } protected string ToShortDatePattern(CultureInfo culture, DateTime value) { return value.ToString(culture.DateTimeFormat.ShortDatePattern); } } }
Fix incorrect copying of blending values.
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK.Graphics.ES30; namespace osu.Framework.Graphics { public struct BlendingInfo { public BlendingFactorSrc Source; public BlendingFactorDest Destination; public BlendingFactorSrc SourceAlpha; public BlendingFactorDest DestinationAlpha; public BlendingInfo(bool additive) { Source = BlendingFactorSrc.SrcAlpha; Destination = BlendingFactorDest.OneMinusSrcAlpha; SourceAlpha = BlendingFactorSrc.One; DestinationAlpha = BlendingFactorDest.One; Additive = additive; } public bool Additive { set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; } } /// <summary> /// Copies the current BlendingInfo into target. /// </summary> /// <param name="target">The BlendingInfo to be filled with the copy.</param> public void Copy(ref BlendingInfo target) { target.Source = Source; target.Destination = Destination; target.SourceAlpha = Source; target.DestinationAlpha = Destination; } public bool Equals(BlendingInfo other) { return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha; } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK.Graphics.ES30; namespace osu.Framework.Graphics { public struct BlendingInfo { public BlendingFactorSrc Source; public BlendingFactorDest Destination; public BlendingFactorSrc SourceAlpha; public BlendingFactorDest DestinationAlpha; public BlendingInfo(bool additive) { Source = BlendingFactorSrc.SrcAlpha; Destination = BlendingFactorDest.OneMinusSrcAlpha; SourceAlpha = BlendingFactorSrc.One; DestinationAlpha = BlendingFactorDest.One; Additive = additive; } public bool Additive { set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; } } /// <summary> /// Copies the current BlendingInfo into target. /// </summary> /// <param name="target">The BlendingInfo to be filled with the copy.</param> public void Copy(ref BlendingInfo target) { target.Source = Source; target.Destination = Destination; target.SourceAlpha = SourceAlpha; target.DestinationAlpha = DestinationAlpha; } public bool Equals(BlendingInfo other) { return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha; } } }
Add tests for the BarLineGenerator
// 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.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.Timing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneBarLineGeneration : OsuTestScene { [Test] public void TestCloseBarLineGeneration() { const double start_time = 1000; var beatmap = new Beatmap<TaikoHitObject> { HitObjects = { new Hit { Type = HitType.Centre, StartTime = start_time } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new TaikoRuleset().RulesetInfo }, }; beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint()); beatmap.ControlPointInfo.Add(start_time + 1, new TimingControlPoint()); var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines; AddAssert("first barline generated", () => barlines.Any(b => b.StartTime == start_time)); AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + 1)); } [Test] public void TestOmitBarLineEffectPoint() { const double start_time = 1000; const double beat_length = 500; const int time_signature_numerator = 4; var beatmap = new Beatmap<TaikoHitObject> { HitObjects = { new Hit { Type = HitType.Centre, StartTime = start_time } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new TaikoRuleset().RulesetInfo }, }; beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint { BeatLength = beat_length, TimeSignature = new TimeSignature(time_signature_numerator) }); beatmap.ControlPointInfo.Add(start_time, new EffectControlPoint { OmitFirstBarLine = true }); var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines; AddAssert("first barline ommited", () => !barlines.Any(b => b.StartTime == start_time)); AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + (beat_length * time_signature_numerator))); } } }
Create a supplier that supply elements continually(Stream).
using System; namespace Nohros { /// <summary> /// A implementation of the <see cref="ISupplier{T}"/> class that supply /// elements of type <typeparamref name="T"/> in a sequence. /// </summary> /// <typeparam name="T"> /// The type of objects supplied. /// </typeparam> public interface ISupplierStream<T> : ISupplier<T> { /// <summary> /// Gets a value indicating if an item available is available from the /// supplier. /// </summary> /// <value> /// <c>true</c> if an item is available from the supplier(that is, if /// <see cref="ISupplier{T}.Supply"/> method wolud return a value); /// otherwise <c>false</c>. /// </value> bool Available { get; } } }
Add test scene for drawings screen
// 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.IO; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Graphics.Cursor; using osu.Game.Tournament.Screens.Drawings; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneDrawingsScreen : TournamentTestScene { [BackgroundDependencyLoader] private void load(Storage storage) { using (var stream = storage.GetStream("drawings.txt", FileAccess.Write)) using (var writer = new StreamWriter(stream)) { writer.WriteLine("KR : South Korea : KOR"); writer.WriteLine("US : United States : USA"); writer.WriteLine("PH : Philippines : PHL"); writer.WriteLine("BR : Brazil : BRA"); writer.WriteLine("JP : Japan : JPN"); } Add(new OsuContextMenuContainer { RelativeSizeAxes = Axes.Both, Child = new DrawingsScreen() }); } } }