Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Change test method to async
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PublicHolidays.Test { [TestClass] public class PublicHolidaysApiTest { [TestMethod] public void TestGet() { var holidays = JpPublicHolidays.PublicHolidays.Get().Result; Assert.IsTrue(holidays.Length >= 20); var day = holidays.FirstOrDefault(x => x.Date == new DateTime(DateTime.Now.Year, 1, 1)); Assert.IsNotNull(day); Assert.AreEqual(day.Name, "元日"); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PublicHolidays.Test { [TestClass] public class PublicHolidaysApiTest { [TestMethod] public async Task TestGet() { var holidays = await JpPublicHolidays.PublicHolidays.Get(); Assert.IsTrue(holidays.Length >= 20); var day = holidays.FirstOrDefault(x => x.Date == new DateTime(DateTime.Now.Year, 1, 1)); Assert.IsNotNull(day); Assert.AreEqual(day.Name, "元日"); } } }
Rework the way DB access is done
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using PKMDS_CS; namespace PKMDS_Save_Editor { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void loadSaveToolStripMenuItem_Click(object sender, EventArgs e) { // Test to make sure the dependencies are working correctly //this.Text = PKMDS.GetPKMName(4, 9, "F:\\Dropbox\\PKMDS Databases\\veekun-pokedex.sqlite"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using PKMDS_CS; namespace PKMDS_Save_Editor { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void loadSaveToolStripMenuItem_Click(object sender, EventArgs e) { // Test to make sure the dependencies are working correctly PKMDS.OpenDB("F:\\Dropbox\\PKMDS Databases\\veekun-pokedex.sqlite"); this.Text = PKMDS.GetPKMName(4, 9); PKMDS.CloseDB(); } } }
Create server side API for single multiple answer question
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } /// <summary> /// Adding single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SaveChanges(); } } }
Use dot instead of dash to separate build metadata
public class BuildVersion { public GitVersion GitVersion { get; private set; } public string Version { get; private set; } public string Milestone { get; private set; } public string SemVersion { get; private set; } public string GemVersion { get; private set; } public string VsixVersion { get; private set; } public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion) { var version = gitVersion.MajorMinorPatch; var semVersion = gitVersion.LegacySemVer; var vsixVersion = gitVersion.MajorMinorPatch; if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) { semVersion += "-" + gitVersion.BuildMetaData; vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH"); } return new BuildVersion { GitVersion = gitVersion, Milestone = version, Version = version, SemVersion = semVersion, GemVersion = semVersion.Replace("-", "."), VsixVersion = vsixVersion, }; } }
public class BuildVersion { public GitVersion GitVersion { get; private set; } public string Version { get; private set; } public string Milestone { get; private set; } public string SemVersion { get; private set; } public string GemVersion { get; private set; } public string VsixVersion { get; private set; } public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion) { var version = gitVersion.MajorMinorPatch; var semVersion = gitVersion.LegacySemVer; var vsixVersion = gitVersion.MajorMinorPatch; if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) { semVersion += "." + gitVersion.BuildMetaData; vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH"); } return new BuildVersion { GitVersion = gitVersion, Milestone = version, Version = version, SemVersion = semVersion, GemVersion = semVersion.Replace("-", "."), VsixVersion = vsixVersion, }; } }
Hide results until results are available
@model string <div class="container"> <form action="/" method="POST"> <div class="control-group"> <div class="controls controls-row"> <div class="input-prepend"> <span class="add-on">Ask me</span> <input id="query" name="query" class="input-xlarge" placeholder="What is the meaing of life?" type="text"> </div> </div> </div> <button id="submit" type="submit" class="btn btn-inverse btn-large">Ask the psychic dangerzone</button> </form> <div id="results-wrapper"> <div id="results-header"> <h2>Welcome to the dangerzone</h2> </div> <div id="results"> <p>@Model</p> </div> </div> </div>
@model string <div class="container"> <form action="/" method="POST"> <div class="control-group"> <div class="controls controls-row"> <div class="input-prepend"> <span class="add-on">Ask me</span> <input id="query" name="query" class="input-xlarge" placeholder="What is the meaing of life?" type="text"> </div> </div> </div> <button id="submit" type="submit" class="btn btn-danger btn-large">Ask the psychic dangerzone</button> </form> @if (!string.IsNullOrEmpty(Model)) { <center> <div id="results-wrapper"> <div id="results-header"> <h2>Welcome to the dangerzone</h2> </div> <div id="results"> <p>@Model</p> </div> </div> </center> } </div>
Fix parameter order in ArgumentException constructor
using System; namespace WpfMath.Utils { internal static class Result { public static Result<TValue> Ok<TValue>(TValue value) => new Result<TValue>(value, null); public static Result<TValue> Error<TValue>(Exception error) => new Result<TValue>(default, error); } internal readonly struct Result<TValue> { private readonly TValue value; public TValue Value => this.Error == null ? this.value : throw this.Error; public Exception Error { get; } public bool IsSuccess => this.Error == null; public Result(TValue value, Exception error) { if (!Equals(value, default) && error != null) { throw new ArgumentException(nameof(error), $"Invalid {nameof(Result)} constructor call"); } this.value = value; this.Error = error; } public Result<TProduct> Map<TProduct>(Func<TValue, TProduct> mapper) => this.IsSuccess ? Result.Ok(mapper(this.Value)) : Result.Error<TProduct>(this.Error); } }
using System; namespace WpfMath.Utils { internal static class Result { public static Result<TValue> Ok<TValue>(TValue value) => new Result<TValue>(value, null); public static Result<TValue> Error<TValue>(Exception error) => new Result<TValue>(default, error); } internal readonly struct Result<TValue> { private readonly TValue value; public TValue Value => this.Error == null ? this.value : throw this.Error; public Exception Error { get; } public bool IsSuccess => this.Error == null; public Result(TValue value, Exception error) { if (!Equals(value, default) && error != null) { throw new ArgumentException($"Invalid {nameof(Result)} constructor call", nameof(error)); } this.value = value; this.Error = error; } public Result<TProduct> Map<TProduct>(Func<TValue, TProduct> mapper) => this.IsSuccess ? Result.Ok(mapper(this.Value)) : Result.Error<TProduct>(this.Error); } }
Fix not being able to drag non-snaked sliders
// 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.Graphics; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osuTK; namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders { public class SliderSelectionBlueprint : OsuSelectionBlueprint<Slider> { protected readonly SliderBodyPiece BodyPiece; protected readonly SliderCircleSelectionBlueprint HeadBlueprint; protected readonly SliderCircleSelectionBlueprint TailBlueprint; public SliderSelectionBlueprint(DrawableSlider slider) : base(slider) { var sliderObject = (Slider)slider.HitObject; InternalChildren = new Drawable[] { BodyPiece = new SliderBodyPiece(), HeadBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.Start), TailBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.End), new PathControlPointVisualiser(sliderObject), }; } protected override void Update() { base.Update(); BodyPiece.UpdateFrom(HitObject); } public override Vector2 SelectionPoint => HeadBlueprint.SelectionPoint; protected virtual SliderCircleSelectionBlueprint CreateCircleSelectionBlueprint(DrawableSlider slider, SliderPosition position) => new SliderCircleSelectionBlueprint(slider, position); } }
// 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.Graphics; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osuTK; namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders { public class SliderSelectionBlueprint : OsuSelectionBlueprint<Slider> { protected readonly SliderBodyPiece BodyPiece; protected readonly SliderCircleSelectionBlueprint HeadBlueprint; protected readonly SliderCircleSelectionBlueprint TailBlueprint; public SliderSelectionBlueprint(DrawableSlider slider) : base(slider) { var sliderObject = (Slider)slider.HitObject; InternalChildren = new Drawable[] { BodyPiece = new SliderBodyPiece(), HeadBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.Start), TailBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.End), new PathControlPointVisualiser(sliderObject), }; } protected override void Update() { base.Update(); BodyPiece.UpdateFrom(HitObject); } public override Vector2 SelectionPoint => HeadBlueprint.SelectionPoint; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => BodyPiece.ReceivePositionalInputAt(screenSpacePos); protected virtual SliderCircleSelectionBlueprint CreateCircleSelectionBlueprint(DrawableSlider slider, SliderPosition position) => new SliderCircleSelectionBlueprint(slider, position); } }
Use discards to fix CI complaints
// 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 disable using System; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Tests.Visual; namespace osu.Framework.Tests.Containers { public class TestSceneEnumeratorVersion : FrameworkTestScene { private Container parent; [SetUp] public void SetUp() => Schedule(() => { Child = parent = new Container { Child = new Container() }; }); [Test] public void TestEnumeratingNormally() { AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() => { foreach (var child in parent) { } })); } [Test] public void TestAddChildDuringEnumerationFails() { AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Add(new Container()); } })); } [Test] public void TestRemoveChildDuringEnumerationFails() { AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Remove(child, true); } })); } [Test] public void TestClearDuringEnumerationFails() { AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Clear(); } })); } } }
// 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 disable using System; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Tests.Visual; namespace osu.Framework.Tests.Containers { public class TestSceneEnumeratorVersion : FrameworkTestScene { private Container parent; [SetUp] public void SetUp() => Schedule(() => { Child = parent = new Container { Child = new Container() }; }); [Test] public void TestEnumeratingNormally() { AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() => { foreach (var _ in parent) { } })); } [Test] public void TestAddChildDuringEnumerationFails() { AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var _ in parent) { parent.Add(new Container()); } })); } [Test] public void TestRemoveChildDuringEnumerationFails() { AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var child in parent) { parent.Remove(child, true); } })); } [Test] public void TestClearDuringEnumerationFails() { AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() => { foreach (var _ in parent) { parent.Clear(); } })); } } }
Add SignPath to known words
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE namespace Nuke.Common.Utilities { public static partial class StringExtensions { private static readonly string[] KnownWords = { "DotNet", "GitHub", "GitVersion", "MSBuild", "NuGet", "ReSharper", "AppVeyor", "TeamCity", "GitLab" }; } }
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE namespace Nuke.Common.Utilities { public static partial class StringExtensions { private static readonly string[] KnownWords = { "DotNet", "GitHub", "GitVersion", "MSBuild", "NuGet", "ReSharper", "AppVeyor", "TeamCity", "GitLab", "SignPath" }; } }
Apply angular velocity to asteroids
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 7f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); } protected override void OnCollision(GameObject other, Vector2 normal, float penetration) { base.OnCollision(other, normal, penetration); // asteroids shouldn't move so much if ships bump into them, because // they should look heavy and sluggish if (other.type == ObjectType.AIShip || other.type == ObjectType.PlayerShip) this.velocity *= 0.8f; } public override bool IsTerrain() { return true; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { private float angularVelocity; public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 7f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); facing += angularVelocity * deltaTime; angularVelocity *= (float)Math.Pow(0.8f, deltaTime); } protected override void OnCollision(GameObject other, Vector2 normal, float penetration) { base.OnCollision(other, normal, penetration); // spin around! angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0); // asteroids shouldn't move so much if ships bump into them, because // they should look heavy and sluggish if (other.type == ObjectType.AIShip || other.type == ObjectType.PlayerShip) this.velocity *= 0.8f; } public override bool IsTerrain() { return true; } } }
Use body length for Service Bus binary messages.
using System; using System.IO; using System.Text; using Microsoft.Azure.Jobs.Host.Bindings; using Microsoft.ServiceBus.Messaging; namespace Microsoft.Azure.Jobs.ServiceBus.Triggers { internal class BrokeredMessageValueProvider : IValueProvider { private readonly object _value; private readonly Type _valueType; private readonly string _invokeString; public BrokeredMessageValueProvider(BrokeredMessage clone, object value, Type valueType) { if (value != null && !valueType.IsAssignableFrom(value.GetType())) { throw new InvalidOperationException("value is not of the correct type."); } _value = value; _valueType = valueType; _invokeString = CreateInvokeString(clone); } public Type Type { get { return _valueType; } } public object GetValue() { return _value; } public string ToInvokeString() { return _invokeString; } private static string CreateInvokeString(BrokeredMessage message) { using (MemoryStream outputStream = new MemoryStream()) { using (Stream inputStream = message.GetBody<Stream>()) { if (inputStream == null) { return null; } inputStream.CopyTo(outputStream); try { return StrictEncodings.Utf8.GetString(outputStream.ToArray()); } catch (DecoderFallbackException) { return "byte[" + message.Size + "]"; } } } } } }
using System; using System.IO; using System.Text; using Microsoft.Azure.Jobs.Host.Bindings; using Microsoft.ServiceBus.Messaging; namespace Microsoft.Azure.Jobs.ServiceBus.Triggers { internal class BrokeredMessageValueProvider : IValueProvider { private readonly object _value; private readonly Type _valueType; private readonly string _invokeString; public BrokeredMessageValueProvider(BrokeredMessage clone, object value, Type valueType) { if (value != null && !valueType.IsAssignableFrom(value.GetType())) { throw new InvalidOperationException("value is not of the correct type."); } _value = value; _valueType = valueType; _invokeString = CreateInvokeString(clone); } public Type Type { get { return _valueType; } } public object GetValue() { return _value; } public string ToInvokeString() { return _invokeString; } private static string CreateInvokeString(BrokeredMessage message) { using (MemoryStream outputStream = new MemoryStream()) { using (Stream inputStream = message.GetBody<Stream>()) { if (inputStream == null) { return null; } inputStream.CopyTo(outputStream); byte[] bytes = outputStream.ToArray(); try { return StrictEncodings.Utf8.GetString(bytes); } catch (DecoderFallbackException) { return "byte[" + bytes.Length + "]"; } } } } } }
Update existing documentation for show images.
namespace TraktApiSharp.Objects.Get.Shows { using Basic; using Newtonsoft.Json; /// <summary> /// A collection of images for a Trakt show. /// </summary> public class TraktShowImages { /// <summary> /// A fanart image set for various sizes. /// </summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } /// <summary> /// A poster image set for various sizes. /// </summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary> /// A logo image. /// </summary> [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } /// <summary> /// A clearart image. /// </summary> [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } /// <summary> /// A banner image. /// </summary> [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } /// <summary> /// A thumbnail image. /// </summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
namespace TraktApiSharp.Objects.Get.Shows { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt show.</summary> public class TraktShowImages { /// <summary>Gets or sets the fan art image set.</summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } /// <summary>Gets or sets the poster image set.</summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary>Gets or sets the loge image.</summary> [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } /// <summary>Gets or sets the clear art image.</summary> [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } /// <summary>Gets or sets the banner image.</summary> [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } /// <summary>Gets or sets the thumb image.</summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
Include the Table namespace into Hangman
using System; public class Hangman { public static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine("You entered the following {0} command line arguments:", args.Length ); for (int i=0; i < args.Length; i++) { Console.WriteLine("{0}", args[i]); } } }
using System; using Table; public class Hangman { public static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine("You entered the following {0} command line arguments:", args.Length ); for (int i=0; i < args.Length; i++) { Console.WriteLine("{0}", args[i]); } } }
Add vote method to voting service
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhotoLife.Services { class VotingService { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhotoLife.Data.Contracts; using PhotoLife.Factories; using PhotoLife.Models; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class VotingService { private readonly IRepository<Vote> voteRepository; private readonly IUnitOfWork unitOfWork; private readonly IVoteFactory voteFactory; private readonly IPostService postService; public VotingService(IRepository<Vote> voteRepository, IUnitOfWork unitOfWork, IVoteFactory voteFactory, IPostService postService) { if (voteRepository == null) { throw new ArgumentNullException(nameof(voteRepository)); } if (unitOfWork == null) { throw new ArgumentNullException(nameof(unitOfWork)); } if (postService == null) { throw new ArgumentNullException(nameof(postService)); } if (voteFactory == null) { throw new ArgumentNullException(nameof(voteFactory)); } this.voteRepository = voteRepository; this.unitOfWork = unitOfWork; this.postService = postService; this.voteFactory = voteFactory; } public int Vote(int postId, string userId) { var userVoteOnLog = this.voteRepository .GetAll .FirstOrDefault(v => v.PostId.Equals(postId) && v.UserId.Equals(userId)); var notVoted = (userVoteOnLog == null); if (notVoted) { var log = this.postService.GetPostById(postId); if (log != null) { var vote = this.voteFactory.CreateVote(postId, userId); this.voteRepository.Add(vote); this.unitOfWork.Commit(); return log.Votes.Count; } } return -1; } } }
Increment version 0.1.3 -> 0.1.4
using System.Reflection; 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("PogoLocationFeeder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PogoLocationFeeder")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.3.0")] [assembly: AssemblyFileVersion("0.1.3.0")]
using System.Reflection; 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("PogoLocationFeeder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PogoLocationFeeder")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.4.0")] [assembly: AssemblyFileVersion("0.1.4.0")]
Test version of binary dependency
using System; using System.Linq; using Microsoft.Build.Evaluation; using NuGet.Extensions.MSBuild; using NuGet.Extensions.Tests.TestData; using NUnit.Framework; namespace NuGet.Extensions.Tests.MSBuild { [TestFixture] public class ProjectAdapterTests { [Test] public void ProjectWithDependenciesAssemblyNameIsProjectWithDependencies() { var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies); Assert.That(projectAdapter.AssemblyName, Is.EqualTo("ProjectWithDependencies")); } [Test] public void ProjectWithDependenciesDependsOnNewtonsoftJson() { var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies); var binaryReferences = projectAdapter.GetBinaryReferences(); var binaryReferenceIncludeNames = binaryReferences.Select(r => r.IncludeName).ToList(); Assert.That(binaryReferenceIncludeNames, Contains.Item("Newtonsoft.Json")); } private static ProjectAdapter CreateProjectAdapter(string projectWithDependencies) { var msBuildProject = new Project(projectWithDependencies, null, null); var projectAdapter = new ProjectAdapter(msBuildProject, "packages.config"); return projectAdapter; } } }
using System; using System.Linq; using Microsoft.Build.Evaluation; using NuGet.Extensions.MSBuild; using NuGet.Extensions.Tests.TestData; using NUnit.Framework; namespace NuGet.Extensions.Tests.MSBuild { [TestFixture] public class ProjectAdapterTests { private const string _expectedBinaryDependencyAssemblyName = "Newtonsoft.Json"; private const string _expectedBinaryDependencyVersion = "6.0.0.0"; [Test] public void ProjectWithDependenciesAssemblyNameIsProjectWithDependencies() { var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies); Assert.That(projectAdapter.AssemblyName, Is.EqualTo("ProjectWithDependencies")); } [Test] public void ProjectWithDependenciesDependsOnNewtonsoftJson() { var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies); var binaryReferences = projectAdapter.GetBinaryReferences(); var binaryReferenceIncludeNames = binaryReferences.Select(r => r.IncludeName).ToList(); Assert.That(binaryReferenceIncludeNames, Contains.Item(_expectedBinaryDependencyAssemblyName)); } [Test] public void ProjectWithDependenciesDependsOnNewtonsoftJson6000() { var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies); var binaryReferences = projectAdapter.GetBinaryReferences(); var newtonsoft = binaryReferences.Single(r => r.IncludeName == _expectedBinaryDependencyAssemblyName); Assert.That(newtonsoft.IncludeVersion, Is.EqualTo(_expectedBinaryDependencyVersion)); } private static ProjectAdapter CreateProjectAdapter(string projectWithDependencies) { var msBuildProject = new Project(projectWithDependencies, null, null); var projectAdapter = new ProjectAdapter(msBuildProject, "packages.config"); return projectAdapter; } } }
Fix ButtonMadness application closes when Close button is clicked.
using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; namespace SamplesButtonMadness { public partial class AppDelegate : NSApplicationDelegate { TestWindowController mainWindowController; public AppDelegate () { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new TestWindowController (); mainWindowController.Window.MakeKeyAndOrderFront (this); } } }
using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; namespace SamplesButtonMadness { public partial class AppDelegate : NSApplicationDelegate { TestWindowController mainWindowController; public AppDelegate () { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new TestWindowController (); mainWindowController.Window.MakeKeyAndOrderFront (this); } public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender) { return true; } } }
Make the Loading html page look better.
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace BabbyJotz { public partial class WebViewPage : ContentPage { public WebViewPage(string title, Func<Task<string>> htmlFunc) { InitializeComponent(); Title = title; ((HtmlWebViewSource)webview.Source).Html = "<html><body>Loading...</body></html>"; doFunc(htmlFunc); } private async void doFunc(Func<Task<string>> htmlFunc) { ((HtmlWebViewSource)webview.Source).Html = await htmlFunc(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace BabbyJotz { public partial class WebViewPage : ContentPage { public WebViewPage(string title, Func<Task<string>> htmlFunc) { InitializeComponent(); Title = title; ((HtmlWebViewSource)webview.Source).Html = @" <html> <head> <style> body { padding: 0px; margin: 8px; font-family: Helvetica; background-color: #333333; color: #ffffff; } </style> </head> <body> Loading... </body> </html>"; doFunc(htmlFunc); } private async void doFunc(Func<Task<string>> htmlFunc) { ((HtmlWebViewSource)webview.Source).Html = await htmlFunc(); } } }
Include interface to make IoC easier
using System.Collections.Generic; using System.Xml.Serialization; namespace XeroApi.Model { public abstract class EndpointModelBase : ModelBase { } public abstract class ModelBase { [XmlAttribute("status")] public ValidationStatus ValidationStatus { get; set; } public List<ValidationError> ValidationErrors { get; set; } public List<Warning> Warnings { get; set; } } public enum ValidationStatus { OK, WARNING, ERROR } public struct Warning { public string Message; } public struct ValidationError { public string Message; } }
using System.Collections.Generic; using System.Xml.Serialization; namespace XeroApi.Model { public abstract class EndpointModelBase : ModelBase { } public abstract class ModelBase : IModelBase { [XmlAttribute("status")] public ValidationStatus ValidationStatus { get; set; } public List<ValidationError> ValidationErrors { get; set; } public List<Warning> Warnings { get; set; } } public interface IModelBase { } public enum ValidationStatus { OK, WARNING, ERROR } public struct Warning { public string Message; } public struct ValidationError { public string Message; } }
Fix unit test that was failing after moving from yepnope to LazyLoad.js
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Newtonsoft.Json.Linq; using Umbraco.Core.Manifest; using Umbraco.Web.UI.JavaScript; namespace Umbraco.Tests.AngularIntegration { [TestFixture] public class JsInitializationTests { [Test] public void Get_Default_Init() { var init = JsInitialization.GetDefaultInitialization(); Assert.IsTrue(init.Any()); } [Test] public void Parse_Main() { var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" }); Assert.AreEqual(@" yepnope({ load: [ 'lib/jquery/jquery-2.0.3.min.js', 'lib/angular/1.1.5/angular.min.js', 'lib/underscore/underscore.js', ], complete: function () { yepnope({ load: [World], complete: function () { //we need to set the legacy UmbClientMgr path UmbClientMgr.setUmbracoPath('Hello'); jQuery(document).ready(function () { angular.bootstrap(document, ['umbraco']); }); } }); } });", result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Newtonsoft.Json.Linq; using Umbraco.Core.Manifest; using Umbraco.Web.UI.JavaScript; namespace Umbraco.Tests.AngularIntegration { [TestFixture] public class JsInitializationTests { [Test] public void Get_Default_Init() { var init = JsInitialization.GetDefaultInitialization(); Assert.IsTrue(init.Any()); } [Test] public void Parse_Main() { var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" }); Assert.AreEqual(@"LazyLoad.js([World], function () { //we need to set the legacy UmbClientMgr path UmbClientMgr.setUmbracoPath('Hello'); jQuery(document).ready(function () { angular.bootstrap(document, ['umbraco']); }); });", result); } } }
Fix rare crash when deleting airlock while the deny animation is playing
using Robust.Client.GameObjects; using Robust.Client.Interfaces.GameObjects.Components; using static Content.Shared.GameObjects.Components.SharedWiresComponent; namespace Content.Client.GameObjects.Components.Wires { public class WiresVisualizer : AppearanceVisualizer { public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); var sprite = component.Owner.GetComponent<ISpriteComponent>(); if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state)) { sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state); } } public enum WiresVisualLayers { MaintenancePanel, } } }
using Robust.Client.GameObjects; using Robust.Client.Interfaces.GameObjects.Components; using static Content.Shared.GameObjects.Components.SharedWiresComponent; namespace Content.Client.GameObjects.Components.Wires { public class WiresVisualizer : AppearanceVisualizer { public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); if (component.Owner.Deleted) return; var sprite = component.Owner.GetComponent<ISpriteComponent>(); if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state)) { sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state); } } public enum WiresVisualLayers { MaintenancePanel, } } }
Change Steam switch timeout and check time
#region using System.Diagnostics; using System.IO; using System.Threading; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { internal class SteamClient { public static void LogIn(Account account) { Process.Start(Settings.Default.SteamPath, $"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\""); } public static void LogOut() { Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument); } public static bool LogOutAuto() { var timeout = 0; const int maxtimeout = 5000; const int waitstep = 500; if (IsSteamOpen()) { LogOut(); while (IsSteamOpen()) { if (timeout >= maxtimeout) { Popup.Show("Logout operation has timed out. Please force close steam and try again."); return false; } Thread.Sleep(waitstep); timeout += waitstep; } } return true; } public static string ResolvePath() { if (File.Exists(Resources.SteamPath32)) return Resources.SteamPath32; if (File.Exists(Resources.SteamPath64)) return Resources.SteamPath64; Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location."); var dia = new SteamPath(); dia.ShowDialog(); return dia.Path; } public static bool IsSteamOpen() { return (Process.GetProcessesByName(Resources.Steam).Length > 0); } } }
#region using System.Diagnostics; using System.IO; using System.Threading; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { internal class SteamClient { public static void LogIn(Account account) { Process.Start(Settings.Default.SteamPath, $"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\""); } public static void LogOut() { Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument); } public static bool LogOutAuto() { var timeout = 0; const int maxtimeout = 10000; const int waitstep = 100; if (IsSteamOpen()) { LogOut(); while (IsSteamOpen()) { if (timeout >= maxtimeout) { Popup.Show("Logout operation has timed out. Please force close steam and try again."); return false; } Thread.Sleep(waitstep); timeout += waitstep; } } return true; } public static string ResolvePath() { if (File.Exists(Resources.SteamPath32)) return Resources.SteamPath32; if (File.Exists(Resources.SteamPath64)) return Resources.SteamPath64; Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location."); var dia = new SteamPath(); dia.ShowDialog(); return dia.Path; } public static bool IsSteamOpen() { return (Process.GetProcessesByName(Resources.Steam).Length > 0); } } }
Load from embedded resources on GTK too.
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using Perspex.Platform; namespace Perspex.Gtk { /// <summary> /// Loads assets compiled into the application binary. /// </summary> public class AssetLoader : IAssetLoader { /// <summary> /// Opens the resource with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <returns>A stream containing the resource contents.</returns> /// <exception cref="FileNotFoundException"> /// The resource was not found. /// </exception> public Stream Open(Uri uri) { var assembly = Assembly.GetEntryAssembly(); var resourceName = assembly.GetName().Name + ".g"; var manager = new ResourceManager(resourceName, assembly); using (var resourceSet = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { var stream = (Stream)resourceSet.GetObject(uri.ToString(), true); if (stream == null) { throw new FileNotFoundException($"The requested asset could not be found: {uri}"); } return stream; } } } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using Perspex.Platform; namespace Perspex.Gtk { /// <summary> /// Loads assets compiled into the application binary. /// </summary> public class AssetLoader : IAssetLoader { /// <summary> /// Opens the resource with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <returns>A stream containing the resource contents.</returns> /// <exception cref="FileNotFoundException"> /// The resource was not found. /// </exception> public Stream Open(Uri uri) { var assembly = Assembly.GetEntryAssembly(); return assembly.GetManifestResourceStream(uri.ToString()); } } }
Remove sticky note 'Patron's Trophy'
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content yellow"> <h1> Patron's Trophy </h1> <p> Entries for Parton's Trophy close Thursday, 2nd June 2016. <a href="/tournaments">Learn more</a> or <a href="/tournaments/2016/ac/patrons-trophy">enter now!</a> </p> </div> </div> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> Recent Updates </h1> <ul> <li>Link to Association Croquet World Rankings added to <a href="/disciplines/association-croquet/resources">resources</a>.</li> <li>Link to Golf Croquet World Rankings added to <a href="/disciplines/golf-croquet/resources">resources</a>.</li> </ul> </div> </div> </div>
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> Recent Updates </h1> <ul> <li>Link to Association Croquet World Rankings added to <a href="/disciplines/association-croquet/resources">resources</a>.</li> <li>Link to Golf Croquet World Rankings added to <a href="/disciplines/golf-croquet/resources">resources</a>.</li> </ul> </div> </div> </div>
Build the builder in order to create the receiver
using Microsoft.Extensions.Configuration; using RockLib.Messaging; namespace RockLib.Configuration.MessagingProvider { public static class RockLibMessagingProviderExtensions { public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) => builder.AddRockLibMessagingProvider(MessagingScenarioFactory.CreateReceiver(scenarioName)); public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) => builder.Add(new MessagingConfigurationSource(receiver)); } }
using Microsoft.Extensions.Configuration; using RockLib.Messaging; namespace RockLib.Configuration.MessagingProvider { public static class RockLibMessagingProviderExtensions { public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) => builder.AddRockLibMessagingProvider(builder.Build().GetSection("RockLib.Messaging").CreateReceiver(scenarioName)); public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) => builder.Add(new MessagingConfigurationSource(receiver)); } }
Revert "unit test bug fix"
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode 2018. All rights reserved. // </copyright> // <auto-generated> // Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source. // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.Serialization.Test { using FakeItEasy; using OBeautifulCode.AutoFakeItEasy; using OBeautifulCode.Serialization; /// <summary> /// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>. /// </summary> #if !OBeautifulCodeSerializationSolution [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")] internal #else public #endif class SerializationDummyFactory : DefaultSerializationDummyFactory { public SerializationDummyFactory() { AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary); AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null); #if OBeautifulCodeSerializationSolution AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>(); AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>(); #endif AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent1(A.Dummy<short>(), A.Dummy<UtcDateTime>())); AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent2(A.Dummy<short>(), A.Dummy<UtcDateTime>())); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode 2018. All rights reserved. // </copyright> // <auto-generated> // Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source. // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.Serialization.Test { using OBeautifulCode.AutoFakeItEasy; using OBeautifulCode.Serialization; /// <summary> /// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>. /// </summary> #if !OBeautifulCodeSerializationSolution [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")] internal #else public #endif class SerializationDummyFactory : DefaultSerializationDummyFactory { public SerializationDummyFactory() { AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary); AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null); #if OBeautifulCodeSerializationSolution AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>(); AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>(); #endif } } }
Add empty constructor for files that don't have a comment yet.
using NUnit.Framework; namespace TagLib.Tests.Images.Validators { /// <summary> /// This class tests the modification of the Comment field, /// regardless of which metadata format is used. /// </summary> public class CommentModificationValidator : IMetadataModificationValidator { string orig_comment; readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ "; public CommentModificationValidator (string orig_comment) { this.orig_comment = orig_comment; } /// <summary> /// Check if the original comment is found. /// </summary> public virtual void ValidatePreModification (Image.File file) { Assert.AreEqual (orig_comment, GetTag (file).Comment); } /// <summary> /// Changes the comment. /// </summary> public virtual void ModifyMetadata (Image.File file) { GetTag (file).Comment = test_comment; } /// <summary> /// Validates if changes survived a write. /// </summary> public void ValidatePostModification (Image.File file) { Assert.AreEqual (test_comment, GetTag (file).Comment); } /// <summary> /// Returns the tag that should be tested. Default /// behavior is no specific tag. /// </summary> public virtual Image.ImageTag GetTag (Image.File file) { return file.ImageTag; } } }
using System; using NUnit.Framework; namespace TagLib.Tests.Images.Validators { /// <summary> /// This class tests the modification of the Comment field, /// regardless of which metadata format is used. /// </summary> public class CommentModificationValidator : IMetadataModificationValidator { string orig_comment; readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ "; public CommentModificationValidator () : this (String.Empty) { } public CommentModificationValidator (string orig_comment) { this.orig_comment = orig_comment; } /// <summary> /// Check if the original comment is found. /// </summary> public virtual void ValidatePreModification (Image.File file) { Assert.AreEqual (orig_comment, GetTag (file).Comment); } /// <summary> /// Changes the comment. /// </summary> public virtual void ModifyMetadata (Image.File file) { GetTag (file).Comment = test_comment; } /// <summary> /// Validates if changes survived a write. /// </summary> public void ValidatePostModification (Image.File file) { Assert.AreEqual (test_comment, GetTag (file).Comment); } /// <summary> /// Returns the tag that should be tested. Default /// behavior is no specific tag. /// </summary> public virtual Image.ImageTag GetTag (Image.File file) { return file.ImageTag; } } }
Make wait service not timeout without yelling, and making the timeout longer
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace RazorWebSite { public class WaitService { private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(10); private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim(); private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim(); public void NotifyClient() { _clientResetEvent.Set(); } public void WaitForClient() { _clientResetEvent.Set(); _serverResetEvent.Wait(_waitTime); _serverResetEvent.Reset(); } public void WaitForServer() { _serverResetEvent.Set(); _clientResetEvent.Wait(_waitTime); _clientResetEvent.Reset(); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace RazorWebSite { public class WaitService { private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(60); private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim(); private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim(); public void NotifyClient() { _clientResetEvent.Set(); } public void WaitForClient() { _clientResetEvent.Set(); if (!_serverResetEvent.Wait(_waitTime)) { throw new InvalidOperationException("Timeout exceeded"); } _serverResetEvent.Reset(); } public void WaitForServer() { _serverResetEvent.Set(); if (!_clientResetEvent.Wait(_waitTime)) { throw new InvalidOperationException("Timeout exceeded"); } _clientResetEvent.Reset(); } } }
Fix caption of Python Environments window.
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Runtime.InteropServices; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Shell; namespace Microsoft.PythonTools.InterpreterList { [Guid(PythonConstants.InterpreterListToolWindowGuid)] class InterpreterListToolWindow : ToolWindowPane { const string Title = "Python Interpreters"; public InterpreterListToolWindow() { Caption = Title; Content = new InterpreterList( PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(), PythonToolsPackage.Instance); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Runtime.InteropServices; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.Shell; namespace Microsoft.PythonTools.InterpreterList { [Guid(PythonConstants.InterpreterListToolWindowGuid)] class InterpreterListToolWindow : ToolWindowPane { public InterpreterListToolWindow() { Caption = SR.GetString(SR.Interpreters); Content = new InterpreterList( PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(), PythonToolsPackage.Instance); } } }
Unwind some Linq in a relatively hot path
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SymbolInfoExtensions { public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info) { return info.Symbol == null && info.CandidateSymbols.Length == 0 ? SpecializedCollections.EmptyEnumerable<ISymbol>() : GetAllSymbolsWorker(info).Distinct(); } private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info) { if (info.Symbol != null) { yield return info.Symbol; } foreach (var symbol in info.CandidateSymbols) { yield return symbol; } } public static ISymbol GetAnySymbol(this SymbolInfo info) { return info.GetAllSymbols().FirstOrDefault(); } public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info) { if (info.Symbol != null) { return SpecializedCollections.SingletonEnumerable(info.Symbol); } else if (info.CandidateSymbols.Length > 0) { return info.CandidateSymbols; } return SpecializedCollections.EmptyEnumerable<ISymbol>(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SymbolInfoExtensions { public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info) { return info.Symbol == null && info.CandidateSymbols.Length == 0 ? SpecializedCollections.EmptyEnumerable<ISymbol>() : GetAllSymbolsWorker(info).Distinct(); } private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info) { if (info.Symbol != null) { yield return info.Symbol; } foreach (var symbol in info.CandidateSymbols) { yield return symbol; } } public static ISymbol GetAnySymbol(this SymbolInfo info) { return info.Symbol != null ? info.Symbol : info.CandidateSymbols.FirstOrDefault(); } public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info) { if (info.Symbol != null) { return SpecializedCollections.SingletonEnumerable(info.Symbol); } else if (info.CandidateSymbols.Length > 0) { return info.CandidateSymbols; } return SpecializedCollections.EmptyEnumerable<ISymbol>(); } } }
Use GetFileFromApplicationUriAsync to convert from a Uri to a system file path.
using FBCore.Concurrency; using ImagePipeline.Image; using ImagePipeline.Memory; using ImagePipeline.Request; using System.IO; using System.Threading.Tasks; namespace ImagePipeline.Producers { /// <summary> /// Represents a local file fetch producer. /// </summary> public class LocalFileFetchProducer : LocalFetchProducer { internal const string PRODUCER_NAME = "LocalFileFetchProducer"; /// <summary> /// Instantiates the <see cref="LocalFileFetchProducer"/>. /// </summary> public LocalFileFetchProducer( IExecutorService executor, IPooledByteBufferFactory pooledByteBufferFactory) : base( executor, pooledByteBufferFactory) { } /// <summary> /// Gets the encoded image. /// </summary> protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest) { FileInfo file = (FileInfo)imageRequest.SourceFile; return Task.FromResult(GetEncodedImage(file.OpenRead(), (int)(file.Length))); } /// <summary> /// The name of the Producer. /// </summary> protected override string ProducerName { get { return PRODUCER_NAME; } } } }
using FBCore.Concurrency; using ImagePipeline.Image; using ImagePipeline.Memory; using ImagePipeline.Request; using System; using System.IO; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage; namespace ImagePipeline.Producers { /// <summary> /// Represents a local file fetch producer. /// </summary> public class LocalFileFetchProducer : LocalFetchProducer { internal const string PRODUCER_NAME = "LocalFileFetchProducer"; /// <summary> /// Instantiates the <see cref="LocalFileFetchProducer"/>. /// </summary> public LocalFileFetchProducer( IExecutorService executor, IPooledByteBufferFactory pooledByteBufferFactory) : base( executor, pooledByteBufferFactory) { } /// <summary> /// Gets the encoded image. /// </summary> protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest) { Task<StorageFile> uriToFilePathTask = StorageFile.GetFileFromApplicationUriAsync(imageRequest.SourceUri).AsTask(); return uriToFilePathTask.ContinueWith<EncodedImage>((filepathTask) => { FileInfo file = new FileInfo(filepathTask.Result.Path); return GetEncodedImage(file.OpenRead(), (int)(file.Length)); }); } /// <summary> /// The name of the Producer. /// </summary> protected override string ProducerName { get { return PRODUCER_NAME; } } } }
Use RunClassConstructor to initialize templates
using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; using Fluid.Ast; namespace Fluid { public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new() { static BaseFluidTemplate() { // Necessary to force the custom template class static constructor // c.f. https://github.com/sebastienros/fluid/issues/19 new T(); } public static FluidParserFactory Factory { get; } = new FluidParserFactory(); public IList<Statement> Statements { get; set; } = new List<Statement>(); public static bool TryParse(string template, out T result, out IEnumerable<string> errors) { if (Factory.CreateParser().TryParse(template, out var statements, out errors)) { result = new T(); result.Statements = statements; return true; } else { result = default(T); return false; } } public static bool TryParse(string template, out T result) { return TryParse(template, out result, out var errors); } public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context) { foreach (var statement in Statements) { await statement.WriteToAsync(writer, encoder, context); } } } }
using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; using Fluid.Ast; namespace Fluid { public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new() { static BaseFluidTemplate() { // Necessary to force the custom template class static constructor // as the only member accessed is defined on this class System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); } public static FluidParserFactory Factory { get; } = new FluidParserFactory(); public IList<Statement> Statements { get; set; } = new List<Statement>(); public static bool TryParse(string template, out T result, out IEnumerable<string> errors) { if (Factory.CreateParser().TryParse(template, out var statements, out errors)) { result = new T(); result.Statements = statements; return true; } else { result = default(T); return false; } } public static bool TryParse(string template, out T result) { return TryParse(template, out result, out var errors); } public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context) { foreach (var statement in Statements) { await statement.WriteToAsync(writer, encoder, context); } } } }
Add optimizations to problem 10
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.PythagoreanNumbers { class PythagoreanNumbers { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = int.Parse(Console.ReadLine()); } Array.Sort(nums); bool any = false; for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) { for (int c = 0; c < n; c++) { if (a < b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c])) { Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]); any = true; } } } } if (!any) { Console.WriteLine("No"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.PythagoreanNumbers { class PythagoreanNumbers { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = int.Parse(Console.ReadLine()); } Array.Sort(nums); bool any = false; for (int a = 0; a < n; a++) { for (int b = a; b < n; b++) { for (int c = b; c < n; c++) { if (a <= b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c])) { Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]); any = true; } } } } if (!any) { Console.WriteLine("No"); } } } }
Add missed paren in comment.
using System; using System.Threading; namespace ProcessTest_ConsoleApp { class Program { static int Main(string[] args) { try { if (args.Length > 0) { if (args[0].Equals("infinite")) { // To avoid potential issues with orphaned processes (say, the test exits before // exiting the process, we'll say "infinite" is actually 30 seconds. Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop"); Thread.Sleep(30 * 1000); } if (args[0].Equals("error")) { Exception ex = new Exception("Intentional Exception thrown"); throw ex; } if (args[0].Equals("input")) { string str = Console.ReadLine(); } } else { Console.WriteLine("ProcessTest_ConsoleApp.exe started"); Console.WriteLine("ProcessTest_ConsoleApp.exe closed"); } return 100; } catch (Exception toLog) { // We're testing STDERR streams, not the JIT debugger. // This makes the process behave just like a crashing .NET app, but without the WER invocation // nor the blocking dialog that comes with it, or the need to suppress that. Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString())); return 1; } } } }
using System; using System.Threading; namespace ProcessTest_ConsoleApp { class Program { static int Main(string[] args) { try { if (args.Length > 0) { if (args[0].Equals("infinite")) { // To avoid potential issues with orphaned processes (say, the test exits before // exiting the process), we'll say "infinite" is actually 30 seconds. Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop"); Thread.Sleep(30 * 1000); } if (args[0].Equals("error")) { Exception ex = new Exception("Intentional Exception thrown"); throw ex; } if (args[0].Equals("input")) { string str = Console.ReadLine(); } } else { Console.WriteLine("ProcessTest_ConsoleApp.exe started"); Console.WriteLine("ProcessTest_ConsoleApp.exe closed"); } return 100; } catch (Exception toLog) { // We're testing STDERR streams, not the JIT debugger. // This makes the process behave just like a crashing .NET app, but without the WER invocation // nor the blocking dialog that comes with it, or the need to suppress that. Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString())); return 1; } } } }
Add SetMethod & GetMethod Property
using System; using System.Reflection; using System.Reflection.Emit; namespace AspectCore.Lite.Abstractions.Generator { public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder> { public abstract string PropertyName { get; } public abstract PropertyAttributes PropertyAttributes { get; } public abstract CallingConventions CallingConventions { get; } public abstract Type ReturnType { get; } public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public virtual Type[] ParameterTypes { get { return Type.EmptyTypes; } } public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember) { } protected override PropertyBuilder ExecuteBuild() { var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes); if (CanRead) { var readMethodGenerator = GetReadMethodGenerator(DeclaringMember); propertyBuilder.SetGetMethod(readMethodGenerator.Build()); } if (CanWrite) { var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember); propertyBuilder.SetSetMethod(writeMethodGenerator.Build()); } return propertyBuilder; } protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType); protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType); } }
using System; using System.Reflection; using System.Reflection.Emit; namespace AspectCore.Lite.Abstractions.Generator { public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder> { public abstract string PropertyName { get; } public abstract PropertyAttributes PropertyAttributes { get; } public abstract CallingConventions CallingConventions { get; } public abstract Type ReturnType { get; } public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public abstract MethodInfo GetMethod { get; } public abstract MethodInfo SetMethod { get; } public virtual Type[] ParameterTypes { get { return Type.EmptyTypes; } } public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember) { } protected override PropertyBuilder ExecuteBuild() { var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes); if (CanRead) { var readMethodGenerator = GetReadMethodGenerator(DeclaringMember); propertyBuilder.SetGetMethod(readMethodGenerator.Build()); } if (CanWrite) { var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember); propertyBuilder.SetSetMethod(writeMethodGenerator.Build()); } return propertyBuilder; } protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType); protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType); } }
Add PKIX key blob formats
namespace NSec.Cryptography { public enum KeyBlobFormat { None = 0, // --- Secret Key Formats --- RawSymmetricKey = -1, RawPrivateKey = -2, NSecSymmetricKey = -101, NSecPrivateKey = -102, // --- Public Key Formats --- RawPublicKey = 1, NSecPublicKey = 101, } }
namespace NSec.Cryptography { public enum KeyBlobFormat { None = 0, // --- Secret Key Formats --- RawSymmetricKey = -1, RawPrivateKey = -2, NSecSymmetricKey = -101, NSecPrivateKey = -102, PkixPrivateKey = -202, PkixPrivateKeyText = -203, // --- Public Key Formats --- RawPublicKey = 1, NSecPublicKey = 101, PkixPublicKey = 201, PkixPublicKeyText = 202, } }
Fix for randomBase64, it was filling a full internal array unnecessarily.
using System; using System.Collections.Generic; using System.Security.Cryptography; namespace LanguageExt { public static partial class Prelude { readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider(); readonly static byte[] target = new byte[4096]; /// <summary> /// Thread-safe cryptographically strong random number generator /// </summary> /// <param name="max">Maximum value to return + 1</param> /// <returns>A non-negative random number, less than the value specified.</returns> public static int random(int max) { lock (rnd) { rnd.GetBytes(target); return Math.Abs(BitConverter.ToInt32(target, 0)) % max; } } /// <summary> /// Thread-safe cryptographically strong random base-64 string generator /// </summary> /// <param name="count">bytesCount - number of bytes generated that are then /// returned Base64 encoded</param> /// <returns>Base64 encoded random string</returns> public static string randomBase64(int bytesCount) { if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1"); if (bytesCount > 4096) throw new ArgumentException($"The maximum value for {nameof(bytesCount)} is 4096"); lock (rnd) { rnd.GetBytes(target); return Convert.ToBase64String(target); } } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; namespace LanguageExt { public static partial class Prelude { readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider(); readonly static byte[] inttarget = new byte[4]; /// <summary> /// Thread-safe cryptographically strong random number generator /// </summary> /// <param name="max">Maximum value to return + 1</param> /// <returns>A non-negative random number, less than the value specified.</returns> public static int random(int max) { lock (rnd) { rnd.GetBytes(inttarget); return Math.Abs(BitConverter.ToInt32(inttarget, 0)) % max; } } /// <summary> /// Thread-safe cryptographically strong random base-64 string generator /// </summary> /// <param name="count">bytesCount - number of bytes generated that are then /// returned Base64 encoded</param> /// <returns>Base64 encoded random string</returns> public static string randomBase64(int bytesCount) { if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1"); var bytes = new byte[bytesCount]; rnd.GetBytes(bytes); return Convert.ToBase64String(bytes); } } }
Make tests of converters possible
using System.Reflection; 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: AssemblyConfiguration("")] // 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")]
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: AssemblyConfiguration("")] // 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")] [assembly: InternalsVisibleTo("TMDbLibTests")]
Add a way to measure how long it took to read a binlog file.
namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.SourceArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); eventSource.Replay(filePath); var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; build.SourceFilesArchive = sourceArchive; return build; } } }
using System.Diagnostics; namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.SourceArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); var sw = Stopwatch.StartNew(); eventSource.Replay(filePath); var elapsed = sw.Elapsed; var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; build.SourceFilesArchive = sourceArchive; // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() }); return build; } } }
Use ICustomAttributeProvider.IsDefined in `HasAttribute` to avoid allocations.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace IntelliTect.Coalesce.TypeDefinition { public static class ReflectionExtensions { /// <summary> /// Returns the attributed requested if it exists or null if it does not. /// </summary> /// <typeparam name="TAttribute"></typeparam> /// <returns></returns> public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute { var attributes = member.GetCustomAttributes(typeof(TAttribute), true); return attributes.FirstOrDefault() as TAttribute; } /// <summary> /// Returns true if the attribute exists. /// </summary> /// <typeparam name="TAttribute"></typeparam> /// <returns></returns> public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute { return member.GetAttribute<TAttribute>() != null; } public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute { var attr = member.GetAttribute<TAttribute>(); if (attr != null) { var property = attr.GetType().GetProperty(valueName); if (property == null) return null; // TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why. try { return property.GetValue(attr, null); } catch (Exception) { return null; } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace IntelliTect.Coalesce.TypeDefinition { public static class ReflectionExtensions { /// <summary> /// Returns the attributed requested if it exists or null if it does not. /// </summary> /// <typeparam name="TAttribute"></typeparam> /// <returns></returns> public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute { var attributes = member.GetCustomAttributes(typeof(TAttribute), true); return attributes.FirstOrDefault() as TAttribute; } /// <summary> /// Returns true if the attribute exists. /// </summary> /// <typeparam name="TAttribute"></typeparam> /// <returns></returns> public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute { return member.IsDefined(typeof(TAttribute), true); } public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute { var attr = member.GetAttribute<TAttribute>(); if (attr != null) { var property = attr.GetType().GetProperty(valueName); if (property == null) return null; // TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why. try { return property.GetValue(attr, null); } catch (Exception) { return null; } } return null; } } }
Add test case for 69c97371
namespace Nine.Storage { using System; using System.Collections.Generic; using Xunit; public class PersistedStorageTest : StorageSpec<PersistedStorageTest> { public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData() { return new[] { new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())), }; } } }
namespace Nine.Storage { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; public class PersistedStorageTest : StorageSpec<PersistedStorageTest> { public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData() { return new[] { new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())), }; } [Fact] public async Task persisted_storage_put_and_get() { var storage = new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString()); await storage.Put(new TestStorageObject("a")); Assert.NotNull(await storage.Get("a")); var gets = new ConcurrentBag<TestStorageObject>(); Parallel.For(0, 100, i => { if (i % 2 == 0) { storage.Put(new TestStorageObject("a")).Wait(); } else { gets.Add(storage.Get("a").Result); } }); Assert.All(gets, got => Assert.NotNull(got)); } } }
Stop loading dynamic modules from disk
using System; using System.Reflection; using slang.Compiler.Clr.Compilation.Definitions; namespace slang.Tests.IL { static class AssemblyDefinitionExtensions { public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition) { return assemblyDefinition.LoadAssembly ().GetTypes (); } public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition) { return AppDomain.CurrentDomain.Load (new AssemblyName (assemblyDefinition.Name)); } } }
using System; using System.Reflection; using slang.Compiler.Clr.Compilation.Definitions; namespace slang.Tests.IL { static class AssemblyDefinitionExtensions { public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition) { return assemblyDefinition.LoadAssembly ().GetTypes (); } public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition) { throw new InvalidOperationException("We will no longer be loading dynamic assemblies for disk so this operation is no longer possible."); } } }
Update detection sample web app
@model Wangkanai.Detection.Services.IDetectionService @{ ViewData["Title"] = "Detection"; } <h3>UserAgent</h3> <code>@Model.UserAgent</code> <h3>Results</h3> <table> <thead> <tr> <th>Resolver</th> <th>Type</th> <th>Version</th> </tr> </thead> <tbody> <tr> <th>Device</th> <td>@Model.Device?.Type</td> <td></td> </tr> <tr> <th>Platform</th> <td>@Model.Platform?.OperatingSystem</td> <td>@Model.Platform?.Processor</td> </tr> <tr> <th>Engine</th> <td>@Model.Engine?.Type</td> <td></td> </tr> <tr> <th>Browser</th> <td>@Model.Browser?.Type</td> <td></td> </tr> <tr> <th>Crawler</th> <td>@Model.Crawler?.Type.ToString()</td> <td>@Model.Crawler?.Version</td> </tr> </tbody> </table>
@model Wangkanai.Detection.Services.IDetectionService @{ ViewData["Title"] = "Detection"; } <h3>UserAgent</h3> <code>@Model.UserAgent</code> <h3>Results</h3> <table> <thead> <tr> <th>Resolver</th> <th>Type</th> <th>Version</th> </tr> </thead> <tbody> <tr> <th>Device</th> <td>@Model.Device?.Type</td> <td></td> </tr> <tr> <th>Platform</th> <td>@Model.Platform?.OperatingSystem</td> <td>@Model.Platform?.Processor</td> </tr> <tr> <th>Engine</th> <td>@Model.Engine?.Type</td> <td></td> </tr> <tr> <th>Browser</th> <td>@Model.Browser?.Type</td> <td></td> </tr> <tr> <th>Crawler</th> <td>@Model.Crawler?.Type</td> <td>@Model.Crawler?.Version</td> </tr> </tbody> </table>
Add drop-down menu for concerts.
@functions { private string GetCssClass(string actionName, string controllerName) { var currentControllerName = ViewContext.RouteData.Values["controller"].ToString(); var isCurrentController = currentControllerName == controllerName; if (currentControllerName == "Home") { return GetHomeControllerLinksCssClass(actionName, isCurrentController); } return isCurrentController ? "active" : string.Empty; } private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController) { if (!isCurrentController) { return string.Empty; } var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName; return isCurrentAction ? "active" : string.Empty; } } @helper GetMenuBarLink(string linkText, string actionName, string controllerName) { <li class="@GetCssClass(actionName, controllerName)">@Html.ActionLink(linkText, actionName, controllerName)</li> } <ul class="nav"> @GetMenuBarLink("Home", "Index", "Home") @GetMenuBarLink("Concerts", "Index", "Concerts") @GetMenuBarLink("Rehearsals", "Index", "Rehearsals") @GetMenuBarLink("About", "About", "Home") @GetMenuBarLink("Contact", "Contact", "Home") </ul>
@functions { private string GetCssClass(string actionName, string controllerName) { var currentControllerName = ViewContext.RouteData.Values["controller"].ToString(); var isCurrentController = currentControllerName == controllerName; if (currentControllerName == "Home") { return GetHomeControllerLinksCssClass(actionName, isCurrentController); } return isCurrentController ? "active" : string.Empty; } private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController) { if (!isCurrentController) { return string.Empty; } var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName; return isCurrentAction ? "active" : string.Empty; } } @helper GetMenuBarLink(string linkText, string actionName, string controllerName) { <li class="dropdown @GetCssClass(actionName, controllerName)"> @if (controllerName == "Concerts" && Request.IsAuthenticated) { <a href="@Url.Action(actionName, controllerName)" class="dropdown-toggle" data-toggle="dropdown"> @linkText <b class="caret"></b> </a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Administer Concerts", "List", "Concerts")</li> </ul> } else { @Html.ActionLink(linkText, actionName, controllerName) } </li> } <ul class="nav"> @GetMenuBarLink("Home", "Index", "Home") @GetMenuBarLink("Concerts", "Index", "Concerts") @GetMenuBarLink("Rehearsals", "Index", "Rehearsals") @GetMenuBarLink("About", "About", "Home") @GetMenuBarLink("Contact", "Contact", "Home") </ul>
Refactor - Move Skip, Take duplicate code
using System.Collections.Generic; using System.Linq.Expressions; using Jokenizer.Net; namespace System.Linq.Dynamic { public static partial class DynamicQueryable { public static IQueryable<T> As<T>(this IQueryable source) { return (IQueryable<T>)source; } public static IQueryable Take(this IQueryable source, int count) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Provider.CreateQuery( Expression.Call( typeof(Queryable), "Take", new[] { source.ElementType }, source.Expression, Expression.Constant(count)) ); } public static IQueryable Skip(this IQueryable source, int count) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Provider.CreateQuery( Expression.Call( typeof(Queryable), "Skip", new[] { source.ElementType }, source.Expression, Expression.Constant(count) ) ); } } }
using System.Collections.Generic; using System.Linq.Expressions; using Jokenizer.Net; namespace System.Linq.Dynamic { public static partial class DynamicQueryable { public static IQueryable<T> As<T>(this IQueryable source) { return (IQueryable<T>)source; } public static IQueryable Take(this IQueryable source, int count) { return HandleConstant(source, "Take", count); } public static IQueryable Skip(this IQueryable source, int count) { return HandleConstant(source, "Skip", count); } public static IQueryable HandleConstant(this IQueryable source, string method, int count) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Provider.CreateQuery( Expression.Call( typeof(Queryable), method, new[] { source.ElementType }, source.Expression, Expression.Constant(count) ) ); } } }
Set disable registration as default true.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; namespace BTCPayServer.Services { public class PoliciesSettings { [Display(Name = "Requires a confirmation mail for registering")] public bool RequiresConfirmedEmail { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] [Display(Name = "Disable registration")] public bool LockSubscription { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; namespace BTCPayServer.Services { public class PoliciesSettings { [Display(Name = "Requires a confirmation mail for registering")] public bool RequiresConfirmedEmail { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] [Display(Name = "Disable registration")] public bool LockSubscription { get; set; } = true; } }
Make paths of text files to write verbatim, so that slashes are not misinterpreted under Windows as escape characters
// <copyright file="TextToPythonScript.cs" company="Mark Final"> // Opus package // </copyright> // <summary>XmlUtilities package</summary> // <author>Mark Final</author> namespace XmlUtilities { public static class TextToPythonScript { public static void Write( System.Text.StringBuilder content, string pythonScriptPath, string pathToGeneratedFile) { using (var writer = new System.IO.StreamWriter(pythonScriptPath)) { writer.WriteLine("#!usr/bin/python"); writer.WriteLine(System.String.Format("with open('{0}', 'wt') as script:", pathToGeneratedFile)); foreach (var line in content.ToString().Split('\n')) { writer.WriteLine("\tscript.write('{0}\\n')", line); } } } } }
// <copyright file="TextToPythonScript.cs" company="Mark Final"> // Opus package // </copyright> // <summary>XmlUtilities package</summary> // <author>Mark Final</author> namespace XmlUtilities { public static class TextToPythonScript { public static void Write( System.Text.StringBuilder content, string pythonScriptPath, string pathToGeneratedFile) { using (var writer = new System.IO.StreamWriter(pythonScriptPath)) { writer.WriteLine("#!usr/bin/python"); writer.WriteLine(System.String.Format("with open(r'{0}', 'wt') as script:", pathToGeneratedFile)); foreach (var line in content.ToString().Split('\n')) { writer.WriteLine("\tscript.write('{0}\\n')", line); } } } } }
Update TFM to include netcoreapp3.0
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Server.IntegrationTesting { public static class Tfm { public const string Net461 = "net461"; public const string NetCoreApp20 = "netcoreapp2.0"; public const string NetCoreApp21 = "netcoreapp2.1"; public const string NetCoreApp22 = "netcoreapp2.2"; public static bool Matches(string tfm1, string tfm2) { return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Server.IntegrationTesting { public static class Tfm { public const string Net461 = "net461"; public const string NetCoreApp20 = "netcoreapp2.0"; public const string NetCoreApp21 = "netcoreapp2.1"; public const string NetCoreApp22 = "netcoreapp2.2"; public const string NetCoreApp30 = "netcoreapp3.0"; public static bool Matches(string tfm1, string tfm2) { return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase); } } }
Put explicit blit in its own Execute func, added inspector button
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class ShaderBlit : MonoBehaviour { public bool Dirty = true; public bool AlwaysDirtyInEditor = true; public Texture Input; public Shader BlitShader; public Material BlitMaterial; public RenderTexture Output; public UnityEngine.Events.UnityEvent OnClean; public void SetDirty() { Dirty = true; } void Update () { if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor ) Dirty = true; if ( !Dirty ) return; if ( Input == null ) return; if (BlitShader != null) { if ( BlitMaterial == null ) BlitMaterial = new Material( BlitShader ); } if ( BlitMaterial == null ) return; Graphics.Blit( Input, Output, BlitMaterial ); Dirty = false; if ( OnClean != null ) OnClean.Invoke(); } }
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class ShaderBlit : MonoBehaviour { [InspectorButton("Execute")] public bool Dirty = true; public bool AlwaysDirtyInEditor = true; public Texture Input; public Shader BlitShader; public Material BlitMaterial; public RenderTexture Output; public UnityEngine.Events.UnityEvent OnClean; public void SetDirty() { Dirty = true; } public void Execute() { if (BlitShader != null) { if ( BlitMaterial == null ) BlitMaterial = new Material( BlitShader ); } if ( BlitMaterial == null ) return; Graphics.Blit( Input, Output, BlitMaterial ); } void Update () { if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor ) Dirty = true; if ( !Dirty ) return; if ( Input == null ) return; Execute(); Dirty = false; if ( OnClean != null ) OnClean.Invoke(); } }
Use Instrument.Preset to detect preset instruments rather than a null InstrumentGroup
// Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Google.Protobuf; using VDrumExplorer.Model; namespace VDrumExplorer.Proto { internal partial class InstrumentAudio { internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema) { var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments; var instrument = bank[InstrumentId]; return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray()); } internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) => new InstrumentAudio { AudioData = ByteString.CopyFrom(audio.Audio), InstrumentId = audio.Instrument.Id, Preset = audio.Instrument.Group != null }; } }
// Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Google.Protobuf; using VDrumExplorer.Model; namespace VDrumExplorer.Proto { internal partial class InstrumentAudio { internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema) { var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments; var instrument = bank[InstrumentId]; return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray()); } internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) => new InstrumentAudio { AudioData = ByteString.CopyFrom(audio.Audio), InstrumentId = audio.Instrument.Id, Preset = audio.Instrument.Group.Preset }; } }
Add test case for gift insertion
using Common; using NUnit.Framework; namespace Tests.Common { [TestFixture] public class TourTest { private Tour testee; [SetUp] public void Init() { testee = new Tour(); testee.AddGift(new Gift(1, 500, 0, 0)); testee.AddGift(new Gift(2, 500, 4, 2)); } [Test] public void TestValidTourWeight() { Assert.IsTrue(testee.IsValid()); } [Test] public void TestInvalidTourWeight() { testee.AddGift(new Gift(3, 0.001, 5, 5)); Assert.IsFalse(testee.IsValid()); } } }
using Common; using NUnit.Framework; namespace Tests.Common { [TestFixture] public class TourTest { private Tour testee; [SetUp] public void Init() { testee = new Tour(); testee.AddGift(new Gift(1, 500, 0, 0)); testee.AddGift(new Gift(2, 500, 4, 2)); } [Test] public void TestValidTourWeight() { Assert.IsTrue(testee.IsValid()); } [Test] public void TestInvalidTourWeight() { testee.AddGift(new Gift(3, 0.001, 5, 5)); Assert.IsFalse(testee.IsValid()); } [Test] public void TestAddGift() { int oldCount = testee.Gifts.Count; testee.AddGift(new Gift(3, 0.001, 5, 5)); Assert.AreEqual(oldCount + 1, testee.Gifts.Count); } } }
Use proper path for settings file
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DataMigrationAppSettings.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; namespace Microsoft.Azure.Commands.DataMigration.Test { public class DataMigrationAppSettings { private static volatile DataMigrationAppSettings instance; private string configFileName = "appsettings.json"; private static object lockObj = new Object(); private JObject config; private DataMigrationAppSettings() { } public static DataMigrationAppSettings Instance { get { if (instance == null) { lock (lockObj) { if (instance == null) { instance = new DataMigrationAppSettings(); instance.LoadConfigFile(); } } } return instance; } } private void LoadConfigFile() { string path = Directory.GetCurrentDirectory(); string fullFilePath = Path.Combine(path, configFileName); if (!File.Exists(fullFilePath)) { // Because of File.Delete doesn't throw any exception in case file not found throw new FileNotFoundException("appsettings.json File Not Found"); } config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath)); } public string GetValue(string configName) { string value = (string) config[configName]; if (string.IsNullOrEmpty(value)) { string message = "Cannot not find config : " + configName; throw new ArgumentException(message); } return value; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DataMigrationAppSettings.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; namespace Microsoft.Azure.Commands.DataMigration.Test { public class DataMigrationAppSettings { private static volatile DataMigrationAppSettings instance; private string configFileName = "appsettings.json"; private static object lockObj = new Object(); private JObject config; private DataMigrationAppSettings() { } public static DataMigrationAppSettings Instance { get { if (instance == null) { lock (lockObj) { if (instance == null) { instance = new DataMigrationAppSettings(); instance.LoadConfigFile(); } } } return instance; } } private void LoadConfigFile() { string fullFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFileName); if (!File.Exists(fullFilePath)) { instance = null; throw new FileNotFoundException("appsettings.json File Not Found"); } config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath)); } public string GetValue(string configName) { string value = (string) config[configName]; if (string.IsNullOrEmpty(value)) { string message = "Cannot not find config : " + configName; throw new ArgumentException(message); } return value; } } }
Fix DataCenter enum in tests project
namespace NFig.Tests.Common { public enum Tier { Any = 0, Local = 1, Dev = 2, Prod = 3, } public enum DataCenter { Any = 0, Local = 1, Dev = 2, Prod = 3, } }
namespace NFig.Tests.Common { public enum Tier { Any = 0, Local = 1, Dev = 2, Prod = 3, } public enum DataCenter { Any = 0, Local = 1, East = 2, West = 3, } }
Add badge for unknown key request count.
@{ Layout = "_Layout"; ViewData["Title"] = "Analysen"; } <div class="row"> <nav class="col-md-3 col-xl-2"> <ul class="nav"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="Analysis" asp-controller="UnknownKeyRequests" asp-action="Index">Unbekannte Translationkeys</a> </li> </ul> </nav> <div class="col-md-9 col-xl-10 py-md-3 pl-md-5"> @RenderBody() </div> </div>
@using System.Linq @inject MitternachtWeb.Areas.Analysis.Services.UnknownKeyRequestsService UnknownKeyRequestsService @{ Layout = "_Layout"; ViewData["Title"] = "Analysen"; } <div class="row"> <nav class="col-md-3 col-xl-2"> <ul class="nav"> <li class="nav-item"> <a class="nav-link text-dark d-flex justify-content-between align-items-center" asp-area="Analysis" asp-controller="UnknownKeyRequests" asp-action="Index"> Unbekannte Translationkeys <span class="badge badge-danger badge-pill">@UnknownKeyRequestsService.UnknownKeyRequests.Values.Aggregate(0ul, (r, i) => r+i)</span> </a> </li> </ul> </nav> <div class="col-md-9 col-xl-10 py-md-3 pl-md-5"> @RenderBody() </div> </div>
Add EtherType enumeration for some types (not all)
using System; namespace TAPCfg { public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } }
using System; namespace TAPCfg { public enum EtherType : int { InterNetwork = 0x0800, ARP = 0x0806, RARP = 0x8035, AppleTalk = 0x809b, AARP = 0x80f3, InterNetworkV6 = 0x86dd, CobraNet = 0x8819, } public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } }
Add some spacing to interface 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 osu.Framework.Bindables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects.Drawables { /// <summary> /// Provides a visual state of a <see cref="PalpableCatchHitObject"/>. /// </summary> public interface IHasCatchObjectState { PalpableCatchHitObject HitObject { get; } Bindable<Color4> AccentColour { get; } Bindable<bool> HyperDash { get; } Vector2 DisplaySize { get; } float DisplayRotation { get; } } }
// 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.Bindables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects.Drawables { /// <summary> /// Provides a visual state of a <see cref="PalpableCatchHitObject"/>. /// </summary> public interface IHasCatchObjectState { PalpableCatchHitObject HitObject { get; } Bindable<Color4> AccentColour { get; } Bindable<bool> HyperDash { get; } Vector2 DisplaySize { get; } float DisplayRotation { get; } } }
Revert "use WebHost.CreateDefaultBuilder in IdentitySample.Mvc"
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace IdentitySample { public static class Program { public static void Main(string[] args) => BuildWebHost(args).Run(); public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
using System.IO; using Microsoft.AspNetCore.Hosting; namespace IdentitySample { public static class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
Update assembly file version for next release
//------------------------------------------------------------------------------ // <copyright // file="CommonAssemblyInfo.cs" // company="enckse"> // Copyright (c) All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyFileVersion("1.3.0.0")]
//------------------------------------------------------------------------------ // <copyright // file="CommonAssemblyInfo.cs" // company="enckse"> // Copyright (c) All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyFileVersion("1.3.1.0")]
Add workaround required after MapODataServiceRoute
using System; using Abp.AspNetCore.Configuration; using Abp.Configuration.Startup; using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Extensions; namespace Abp.AspNetCore.OData.Configuration { internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration { public ODataConventionModelBuilder ODataModelBuilder { get; set; } public Action<IAbpStartupConfiguration> MapAction { get; set; } public AbpAspNetCoreODataModuleConfiguration() { MapAction = configuration => { configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: "odata", model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel() ); }; } } }
using System; using Abp.AspNetCore.Configuration; using Abp.Configuration.Startup; using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Extensions; namespace Abp.AspNetCore.OData.Configuration { internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration { public ODataConventionModelBuilder ODataModelBuilder { get; set; } public Action<IAbpStartupConfiguration> MapAction { get; set; } public AbpAspNetCoreODataModuleConfiguration() { MapAction = configuration => { configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: "odata", model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel() ); // Workaround: https://github.com/OData/WebApi/issues/1175 configuration.Modules.AbpAspNetCore().RouteBuilder.EnableDependencyInjection(); }; } } }
Add path for local vs code install
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Assent.Reporters.DiffPrograms { public abstract class DiffProgramBase : IDiffProgram { protected static IReadOnlyList<string> WindowsProgramFilePaths => new[] { Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramFiles(x86)"), Environment.GetEnvironmentVariable("ProgramW6432") } .Where(p => !string.IsNullOrWhiteSpace(p)) .Distinct() .ToArray(); public IReadOnlyList<string> SearchPaths { get; } protected DiffProgramBase(IReadOnlyList<string> searchPaths) { SearchPaths = searchPaths; } protected virtual string CreateProcessStartArgs( string receivedFile, string approvedFile) { return $"\"{receivedFile}\" \"{approvedFile}\""; } public virtual bool Launch(string receivedFile, string approvedFile) { var path = SearchPaths.FirstOrDefault(File.Exists); if (path == null) return false; var process = Process.Start(new ProcessStartInfo( path, CreateProcessStartArgs(receivedFile, approvedFile))); process.WaitForExit(); return true; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Assent.Reporters.DiffPrograms { public abstract class DiffProgramBase : IDiffProgram { protected static IReadOnlyList<string> WindowsProgramFilePaths => new[] { Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramFiles(x86)"), Environment.GetEnvironmentVariable("ProgramW6432"), Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Programs") } .Where(p => !string.IsNullOrWhiteSpace(p)) .Distinct() .ToArray(); public IReadOnlyList<string> SearchPaths { get; } protected DiffProgramBase(IReadOnlyList<string> searchPaths) { SearchPaths = searchPaths; } protected virtual string CreateProcessStartArgs( string receivedFile, string approvedFile) { return $"\"{receivedFile}\" \"{approvedFile}\""; } public virtual bool Launch(string receivedFile, string approvedFile) { var path = SearchPaths.FirstOrDefault(File.Exists); if (path == null) return false; var process = Process.Start(new ProcessStartInfo( path, CreateProcessStartArgs(receivedFile, approvedFile))); process.WaitForExit(); return true; } } }
Modify main program to work with port again
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost(args).Run(); Console.ResetColor(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost().Run(); Console.ResetColor(); } public static IWebHost BuildWebHost() => WebHost.CreateDefaultBuilder() .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
Use IOwinContext in to pass Request.CallCancelled to repository
using Bit.Signalr; using Bit.Signalr.Implementations; using BitChangeSetManager.DataAccess; using BitChangeSetManager.Model; using System; using System.Threading; using System.Threading.Tasks; using Bit.Data.Contracts; using BitChangeSetManager.DataAccess.Contracts; namespace BitChangeSetManager.Api.Implementations { public class BitChangeSetManagerAppMessageHubEvents : DefaultMessageHubEvents { public virtual IBitChangeSetManagerRepository<User> UsersRepository { get; set; } public override async Task OnConnected(MessagesHub hub) { User user = await UsersRepository.GetByIdAsync(CancellationToken.None, Guid.Parse(UserInformationProvider.GetCurrentUserId())); await hub.Groups.Add(hub.Context.ConnectionId, user.Culture.ToString()); await base.OnConnected(hub); } } }
using Bit.Signalr; using Bit.Signalr.Implementations; using BitChangeSetManager.DataAccess.Contracts; using BitChangeSetManager.Model; using Microsoft.Owin; using System; using System.Threading.Tasks; namespace BitChangeSetManager.Api.Implementations { public class BitChangeSetManagerAppMessageHubEvents : DefaultMessageHubEvents { public virtual IBitChangeSetManagerRepository<User> UsersRepository { get; set; } public virtual IOwinContext OwinContext { get; set; } public override async Task OnConnected(MessagesHub hub) { User user = await UsersRepository.GetByIdAsync(OwinContext.Request.CallCancelled, Guid.Parse(UserInformationProvider.GetCurrentUserId())); await hub.Groups.Add(hub.Context.ConnectionId, user.Culture.ToString()); await base.OnConnected(hub); } } }
Fix removal of code block space indent for pre with parent div
using System; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Div : ConverterBase { public Div(Converter converter) : base(converter) { Converter.Register("div", this); } public override string Convert(HtmlNode node) { return $"{(Td.FirstNodeWithinCell(node) ? "" : Environment.NewLine)}{TreatChildren(node).Trim()}{(Td.LastNodeWithinCell(node) ? "" : Environment.NewLine)}"; } } }
using System; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Div : ConverterBase { public Div(Converter converter) : base(converter) { Converter.Register("div", this); } public override string Convert(HtmlNode node) { var content = TreatChildren(node).Trim(); // if child is a pre tag then Trim in the above step removes the 4 spaces for code block if (node.ChildNodes.Count > 0 && node.FirstChild.Name == "pre" && !Converter.Config.GithubFlavored) { content = $" {content}"; } return $"{(Td.FirstNodeWithinCell(node) ? "" : Environment.NewLine)}{content}{(Td.LastNodeWithinCell(node) ? "" : Environment.NewLine)}"; } } }
Add Position and Size properties to Rectanclei
using System; using System.Numerics; namespace CSGL.Math { public struct Rectanglei { public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int Height { get; set; } public Rectanglei(int x, int y, int width, int height) { X = x; Y = y; Width = width; Height = height; } public Rectanglei(Rectangle rect) { X = (int)rect.X; Y = (int)rect.Y; Width = (int)rect.Width; Height = (int)rect.Height; } //public Vector2i public float Top { get { return Y; } } public float Bottom { get { return Y + Height; } } public float Left { get { return X; } } public float Right { get { return X + Width; } } public bool Intersects(Rectanglei other) { return (X < other.X + other.Width) && (X + Width > other.X) && (Y < other.Y + other.Height) && (Y + Height > other.Y); } public bool Intersects(Rectangle other) { var thisf = new Rectangle(this); return thisf.Intersects(other); } } }
using System; using System.Numerics; namespace CSGL.Math { public struct Rectanglei { public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int Height { get; set; } public Rectanglei(int x, int y, int width, int height) { X = x; Y = y; Width = width; Height = height; } public Rectanglei(Rectangle rect) { X = (int)rect.X; Y = (int)rect.Y; Width = (int)rect.Width; Height = (int)rect.Height; } public Vector2i Position { get { return new Vector2i(X, Y); } set { X = value.X; Y = value.Y; } } public Vector2i Size { get { return new Vector2i(Width, Height); } set { Width = value.X; Height = value.Y; } } public float Top { get { return Y; } } public float Bottom { get { return Y + Height; } } public float Left { get { return X; } } public float Right { get { return X + Width; } } public bool Intersects(Rectanglei other) { return (X < other.X + other.Width) && (X + Width > other.X) && (Y < other.Y + other.Height) && (Y + Height > other.Y); } public bool Intersects(Rectangle other) { var thisf = new Rectangle(this); return thisf.Intersects(other); } } }
Move some common test setup code into the test class constructor
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace DirectoryHash.Tests { public class RecomputeTests { [Fact] public void RecomputeOnEmptyDirectory() { using (var temporaryDirectory = new TemporaryDirectory()) { temporaryDirectory.Run("recompute"); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); Assert.Empty(hashes.HashedDirectory.Directories); Assert.Empty(hashes.HashedDirectory.Files); } } [Fact] public void RecomputeUpdatesTimeStamp() { using (var temporaryDirectory = new TemporaryDirectory()) { var timeRange = DateTimeRange.CreateSurrounding( () => temporaryDirectory.Run("recompute")); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); timeRange.AssertContains(hashes.UpdateTime); } } [Fact] public void RecomputeWithFile() { using (var temporaryDirectory = new TemporaryDirectory()) { var file = temporaryDirectory.CreateFileWithContent("Fox", Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog.")); temporaryDirectory.Run("recompute"); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); var rehashedFile = HashedFile.FromFile(file); Assert.Equal(rehashedFile, hashes.HashedDirectory.Files["Fox"]); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace DirectoryHash.Tests { public class RecomputeTests : IDisposable { private readonly TemporaryDirectory temporaryDirectory = new TemporaryDirectory(); void IDisposable.Dispose() { temporaryDirectory.Dispose(); } [Fact] public void RecomputeOnEmptyDirectory() { temporaryDirectory.Run("recompute"); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); Assert.Empty(hashes.HashedDirectory.Directories); Assert.Empty(hashes.HashedDirectory.Files); } [Fact] public void RecomputeUpdatesTimeStamp() { var timeRange = DateTimeRange.CreateSurrounding( () => temporaryDirectory.Run("recompute")); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); timeRange.AssertContains(hashes.UpdateTime); } [Fact] public void RecomputeWithFile() { var file = temporaryDirectory.CreateFileWithContent("Fox", Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog.")); temporaryDirectory.Run("recompute"); var hashes = HashesXmlFile.ReadFrom(temporaryDirectory.Directory); var rehashedFile = HashedFile.FromFile(file); Assert.Equal(rehashedFile, hashes.HashedDirectory.Files["Fox"]); } } }
Test we can commit gain
using Kata.GildedRose.CSharp.Domain; namespace Kata.GildedRose.CSharp.Unit.Tests.Factories.UpdateStockItemStrategy { public class UpdateItemStrategyFactory : IUpdateItemStrategyFactory { public IStockItemUpdateStrategy Create(Item stockItem) { return new AgedBrieUpdateStrategy(); } } }
using Kata.GildedRose.CSharp.Domain; namespace Kata.GildedRose.CSharp.Unit.Tests.Factories.UpdateStockItemStrategy { public class UpdateItemStrategyFactory : IUpdateItemStrategyFactory { public IStockItemUpdateStrategy Create(Item stockItem) { switch (item.Name) { case "Aged Brie": _updateStrategy = new AgedBrieUpdateStrategy(); break; case "Backstage passes to a TAFKAL80ETC concert": _updateStrategy = new BackStagePassesUpdateStrategy(); break; case "Sulfuras, Hand of Ragnaros": _updateStrategy = new LegendaryItemsUpdateStratgey(); break; default: _updateStrategy = new StandardItemsUpdateStrategy(); break; } } } }
Revert "Included call to base.WarmUp()."
using System.Threading; using System.Threading.Tasks; using Nimbus.ConcurrentCollections; using Nimbus.Configuration.Settings; using Nimbus.Infrastructure; using Nimbus.Infrastructure.MessageSendersAndReceivers; using Nimbus.Transports.InProcess.QueueManagement; namespace Nimbus.Transports.InProcess.MessageSendersAndReceivers { internal class InProcessQueueReceiver : ThrottlingMessageReceiver { private readonly string _queuePath; private readonly InProcessMessageStore _messageStore; private readonly ThreadSafeLazy<AsyncBlockingCollection<NimbusMessage>> _messageQueue; public InProcessQueueReceiver(string queuePath, ConcurrentHandlerLimitSetting concurrentHandlerLimit, InProcessMessageStore messageStore, IGlobalHandlerThrottle globalHandlerThrottle, ILogger logger) : base(concurrentHandlerLimit, globalHandlerThrottle, logger) { _queuePath = queuePath; _messageStore = messageStore; _messageQueue = new ThreadSafeLazy<AsyncBlockingCollection<NimbusMessage>>(() => _messageStore.GetOrCreateMessageQueue(_queuePath)); } public override string ToString() { return _queuePath; } protected override Task WarmUp() { _messageQueue.EnsureValueCreated(); return base.WarmUp(); } protected override async Task<NimbusMessage> Fetch(CancellationToken cancellationToken) { var nimbusMessage = await _messageQueue.Value.Take(cancellationToken); return nimbusMessage; } } }
using System.Threading; using System.Threading.Tasks; using Nimbus.ConcurrentCollections; using Nimbus.Configuration.Settings; using Nimbus.Infrastructure; using Nimbus.Infrastructure.MessageSendersAndReceivers; using Nimbus.Transports.InProcess.QueueManagement; namespace Nimbus.Transports.InProcess.MessageSendersAndReceivers { internal class InProcessQueueReceiver : ThrottlingMessageReceiver { private readonly string _queuePath; private readonly InProcessMessageStore _messageStore; private readonly ThreadSafeLazy<AsyncBlockingCollection<NimbusMessage>> _messageQueue; public InProcessQueueReceiver(string queuePath, ConcurrentHandlerLimitSetting concurrentHandlerLimit, InProcessMessageStore messageStore, IGlobalHandlerThrottle globalHandlerThrottle, ILogger logger) : base(concurrentHandlerLimit, globalHandlerThrottle, logger) { _queuePath = queuePath; _messageStore = messageStore; _messageQueue = new ThreadSafeLazy<AsyncBlockingCollection<NimbusMessage>>(() => _messageStore.GetOrCreateMessageQueue(_queuePath)); } public override string ToString() { return _queuePath; } protected override Task WarmUp() { return Task.Run(() => _messageQueue.EnsureValueCreated()); } protected override async Task<NimbusMessage> Fetch(CancellationToken cancellationToken) { var nimbusMessage = await _messageQueue.Value.Take(cancellationToken); return nimbusMessage; } } }
Fix WinUI demo null ref exception after cancelling file picker.
using System; using System.Threading.Tasks; using Microsoft.UI.Xaml; using Windows.Storage.Pickers; namespace ModelViewer.Services; public sealed class FilePickerService { public async Task<string> StartFilePicker(string filters) { var tokens = filters.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); return await StartFilePicker(tokens); } public async Task<string> StartFilePicker(string[] filters) { var picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; // Pass in the current WinUI window and get its handle var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.GetService<Window>()); WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd); foreach (var filter in filters) { if (filter == ".mesh.xml") { continue; } picker.FileTypeFilter.Add(filter); } return await picker.PickSingleFileAsync().AsTask().ContinueWith((result) => { return result is null ? string.Empty : result.Result.Path; }); } }
using System; using System.Threading.Tasks; using Microsoft.UI.Xaml; using Windows.Storage.Pickers; namespace ModelViewer.Services; public sealed class FilePickerService { public async Task<string> StartFilePicker(string filters) { var tokens = filters.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); return await StartFilePicker(tokens); } public async Task<string> StartFilePicker(string[] filters) { var picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; // Pass in the current WinUI window and get its handle var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.GetService<Window>()); WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd); foreach (var filter in filters) { if (filter == ".mesh.xml") { continue; } picker.FileTypeFilter.Add(filter); } return await picker.PickSingleFileAsync().AsTask().ContinueWith((result) => { return result is null || result.Result is null ? string.Empty : result.Result.Path; }); } }
Mask the osu! beatsnap grid
// 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.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Screens.Edit.Compose.Components; namespace osu.Game.Rulesets.Osu.Edit { public class OsuDistanceSnapGrid : CircularDistanceSnapGrid { public OsuDistanceSnapGrid(OsuHitObject hitObject) : base(hitObject, hitObject.StackedEndPosition) { } protected override float GetVelocity(double time, ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { TimingControlPoint timingPoint = controlPointInfo.TimingPointAt(time); DifficultyControlPoint difficultyPoint = controlPointInfo.DifficultyPointAt(time); double scoringDistance = OsuHitObject.BASE_SCORING_DISTANCE * difficulty.SliderMultiplier * difficultyPoint.SpeedMultiplier; return (float)(scoringDistance / timingPoint.BeatLength); } } }
// 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.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Screens.Edit.Compose.Components; namespace osu.Game.Rulesets.Osu.Edit { public class OsuDistanceSnapGrid : CircularDistanceSnapGrid { public OsuDistanceSnapGrid(OsuHitObject hitObject) : base(hitObject, hitObject.StackedEndPosition) { Masking = true; } protected override float GetVelocity(double time, ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { TimingControlPoint timingPoint = controlPointInfo.TimingPointAt(time); DifficultyControlPoint difficultyPoint = controlPointInfo.DifficultyPointAt(time); double scoringDistance = OsuHitObject.BASE_SCORING_DISTANCE * difficulty.SliderMultiplier * difficultyPoint.SpeedMultiplier; return (float)(scoringDistance / timingPoint.BeatLength); } } }
Add version and copyright info
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("SharpPhysFS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpPhysFS")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1e8d0656-fbd5-4f97-b634-584943b13af2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpPhysFS")] [assembly: AssemblyDescription("Managed wrapper around PhysFS")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Francesco Bertolaccini")] [assembly: AssemblyProduct("SharpPhysFS")] [assembly: AssemblyCopyright("Copyright © 2015 Francesco Bertolaccini")] [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("1e8d0656-fbd5-4f97-b634-584943b13af2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
Update mvx init for android
using System; using Cirrious.CrossCore; using Cirrious.CrossCore.Droid.Platform; using Cirrious.CrossCore.Plugins; using Acr.UserDialogs; namespace Acr.MvvmCross.Plugins.UserDialogs.Droid { public class Plugin : IMvxPlugin { public void Load() { Mvx.CallbackWhenRegistered<IMvxAndroidCurrentTopActivity>(x => { Acr.UserDialogs.UserDialogs.Instance = new AppCompatUserDialogsImpl(() => Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity); Mvx.RegisterSingleton(Acr.UserDialogs.UserDialogs.Instance); }); } } }
using System; using Cirrious.CrossCore; using Cirrious.CrossCore.Droid.Platform; using Cirrious.CrossCore.Plugins; using Acr.UserDialogs; namespace Acr.MvvmCross.Plugins.UserDialogs.Droid { public class Plugin : IMvxPlugin { public void Load() { Acr.UserDialogs.UserDialogs.Instance = new AppCompatUserDialogsImpl(() => Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity); Mvx.RegisterSingleton(Acr.UserDialogs.UserDialogs.Instance); } } }
Fix out of range bug in sequence task.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sequence : CompositeTask { private int taskIndex = 0; public Sequence(string name) : base(name) { } override public ReturnCode Update() { var returnCode = tasks[taskIndex].Update(); if (returnCode == ReturnCode.Succeed) { taskIndex++; if (taskIndex > tasks.Count) return ReturnCode.Succeed; else return ReturnCode.Running; } else { return returnCode; } } public override void Restart() { taskIndex = 0; base.Restart(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sequence : CompositeTask { private int taskIndex = 0; public Sequence(string name) : base(name) { } override public ReturnCode Update() { var returnCode = tasks[taskIndex].Update(); if (returnCode == ReturnCode.Succeed) { taskIndex++; if (taskIndex >= tasks.Count) return ReturnCode.Succeed; else return ReturnCode.Running; } else { return returnCode; } } public override void Restart() { taskIndex = 0; base.Restart(); } }
Fix zip file extension handling
using System.IO; using Ionic.Zip; namespace UnityBuildServer { public class ZipArchiveStep : ArchiveStep { ZipArchiveConfig config; public ZipArchiveStep(ZipArchiveConfig config) { this.config = config; } public override string TypeName { get { return "Zip File"; } } public override ArchiveInfo CreateArchive(BuildInfo buildInfo, Workspace workspace) { // Replace in-line variables string filename = workspace.Replacements.ReplaceVariablesInText(config.Filename); // Sanitize filename = filename.Replace(' ', '_'); string filepath = $"{workspace.ArchivesDirectory}/{filename}.zip"; // Remove old file if (File.Exists(filepath)) { File.Delete(filepath); } // Save zip file using (var zipFile = new ZipFile()) { zipFile.AddDirectory(workspace.WorkingDirectory); zipFile.Save(filepath); } var archiveInfo = new ArchiveInfo { ArchiveFileName = filename }; return archiveInfo; } } }
using System.IO; using Ionic.Zip; namespace UnityBuildServer { public class ZipArchiveStep : ArchiveStep { ZipArchiveConfig config; public ZipArchiveStep(ZipArchiveConfig config) { this.config = config; } public override string TypeName { get { return "Zip File"; } } public override ArchiveInfo CreateArchive(BuildInfo buildInfo, Workspace workspace) { // Remove file extension in case it was accidentally included in the config data string filename = Path.GetFileNameWithoutExtension(config.Filename); // Replace in-line variables filename = workspace.Replacements.ReplaceVariablesInText(config.Filename); // Sanitize filename = filename.Replace(' ', '_'); filename = filename + ".zip"; string filepath = $"{workspace.ArchivesDirectory}/{filename}"; // Remove old file if (File.Exists(filepath)) { File.Delete(filepath); } // Save zip file using (var zipFile = new ZipFile()) { zipFile.AddDirectory(workspace.WorkingDirectory); zipFile.Save(filepath); } var archiveInfo = new ArchiveInfo { ArchiveFileName = filename }; return archiveInfo; } } }
Fix 81 TIiles mod name
using ICities; using BuildingThemes.GUI; using UnityEngine; namespace BuildingThemes { public class BuildingThemesMod : IUserMod { // we'll use this variable to pass the building position to GetRandomBuildingInfo method. It's here to make possible 81 Tiles compatibility public static Vector3 position; public static readonly string EIGHTY_ONE_MOD = "81 Tiles(Fixed for C:S 1.2+)"; public string Name => "Building Themes"; public string Description => "Create building themes and apply them to cities and districts."; public void OnSettingsUI(UIHelperBase helper) { UIHelperBase group = helper.AddGroup("Building Themes"); group.AddCheckbox("Unlock Policies Panel From Start", PolicyPanelEnabler.Unlock, delegate (bool c) { PolicyPanelEnabler.Unlock = c; }); group.AddCheckbox("Enable Prefab Cloning (experimental, not stable!)", BuildingVariationManager.Enabled, delegate (bool c) { BuildingVariationManager.Enabled = c; }); group.AddGroup("Warning: When you disable this option, spawned clones will disappear!"); group.AddCheckbox("Warning message when selecting an invalid theme", UIThemePolicyItem.showWarning, delegate (bool c) { UIThemePolicyItem.showWarning = c; }); group.AddCheckbox("Generate Debug Output", Debugger.Enabled, delegate (bool c) { Debugger.Enabled = c; }); } } }
using ICities; using BuildingThemes.GUI; using UnityEngine; namespace BuildingThemes { public class BuildingThemesMod : IUserMod { // we'll use this variable to pass the building position to GetRandomBuildingInfo method. It's here to make possible 81 Tiles compatibility public static Vector3 position; public static readonly string EIGHTY_ONE_MOD = "81 Tiles (Fixed for C:S 1.2+)"; public string Name => "Building Themes"; public string Description => "Create building themes and apply them to cities and districts."; public void OnSettingsUI(UIHelperBase helper) { UIHelperBase group = helper.AddGroup("Building Themes"); group.AddCheckbox("Unlock Policies Panel From Start", PolicyPanelEnabler.Unlock, delegate (bool c) { PolicyPanelEnabler.Unlock = c; }); group.AddCheckbox("Enable Prefab Cloning (experimental, not stable!)", BuildingVariationManager.Enabled, delegate (bool c) { BuildingVariationManager.Enabled = c; }); group.AddGroup("Warning: When you disable this option, spawned clones will disappear!"); group.AddCheckbox("Warning message when selecting an invalid theme", UIThemePolicyItem.showWarning, delegate (bool c) { UIThemePolicyItem.showWarning = c; }); group.AddCheckbox("Generate Debug Output", Debugger.Enabled, delegate (bool c) { Debugger.Enabled = c; }); } } }
Add processed_at_min, processed_at_max and attribution_app_id
using Newtonsoft.Json; using ShopifySharp.Enums; namespace ShopifySharp.Filters { /// <summary> /// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and /// <see cref="OrderService.ListAsync(OrderFilter)"/> results. /// </summary> public class OrderFilter : ListFilter { /// <summary> /// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any". /// </summary> [JsonProperty("status")] public string Status { get; set; } /// <summary> /// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided". /// </summary> [JsonProperty("financial_status")] public string FinancialStatus { get; set; } /// <summary> /// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status. /// </summary> [JsonProperty("fulfillment_status")] public string FulfillmentStatus { get; set; } } }
using System; using Newtonsoft.Json; using ShopifySharp.Enums; namespace ShopifySharp.Filters { /// <summary> /// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and /// <see cref="OrderService.ListAsync(OrderFilter)"/> results. /// </summary> public class OrderFilter : ListFilter { /// <summary> /// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any". /// </summary> [JsonProperty("status")] public string Status { get; set; } /// <summary> /// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided". /// </summary> [JsonProperty("financial_status")] public string FinancialStatus { get; set; } /// <summary> /// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status. /// </summary> [JsonProperty("fulfillment_status")] public string FulfillmentStatus { get; set; } /// <summary> /// Show orders imported after date (format: 2014-04-25T16:15:47-04:00) /// </summary> [JsonProperty("processed_at_min")] public DateTime? ProcessedAtMin { get; set; } /// <summary> /// Show orders imported before date (format: 2014-04-25T16:15:47-04:00) /// </summary> [JsonProperty("processed_at_max")] public DateTime? ProcessedAtMax { get; set; } /// <summary> /// Show orders attributed to a specific app. Valid values are the app ID to filter on (eg. 123) or a value of "current" to only show orders for the app currently consuming the API. /// </summary> [JsonProperty("attribution_app_id")] public string AttributionAppId { get; set; } } }
Create success-only stubs for user validator
using System; using Xunit; using ISTS.Domain.Users; namespace ISTS.Domain.Tests.Users { public class UserTests { [Fact] public void Create_Returns_New_User() { var user = User.Create("myemail@company.com", "Person", "12345", "password1"); Assert.NotNull(user); Assert.Equal("myemail@company.com", user.Email); Assert.Equal("Person", user.DisplayName); Assert.Equal("12345", user.PostalCode); Assert.NotNull(user.PasswordHash); Assert.NotNull(user.PasswordSalt); } [Fact] public void Create_Throws_ArgumentNullException_When_Password_Is_Null() { var ex = Assert.Throws<ArgumentNullException>(() => User.Create("myemail@company.com", "Person", "12345", null)); Assert.NotNull(ex); } [Fact] public void Create_Throws_ArgumentException_When_Password_Is_WhiteSpace() { var ex = Assert.Throws<ArgumentException>(() => User.Create("myemail@company.com", "Person", "12345", " ")); Assert.NotNull(ex); } } }
using System; using Moq; using Xunit; using ISTS.Domain.Common; using ISTS.Domain.Users; namespace ISTS.Domain.Tests.Users { public class UserTests { private readonly Mock<IUserValidator> _userValidator; public UserTests() { _userValidator = new Mock<IUserValidator>(); } [Fact] public void Create_Returns_New_User() { var user = User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", "password1"); Assert.NotNull(user); Assert.Equal("myemail@company.com", user.Email); Assert.Equal("Person", user.DisplayName); Assert.Equal("12345", user.PostalCode); Assert.NotNull(user.PasswordHash); Assert.NotNull(user.PasswordSalt); } [Fact] public void Create_Throws_ArgumentNullException_When_Password_Is_Null() { var ex = Assert.Throws<ArgumentNullException>(() => User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", null)); Assert.NotNull(ex); } [Fact] public void Create_Throws_ArgumentException_When_Password_Is_WhiteSpace() { var ex = Assert.Throws<ArgumentException>(() => User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", " ")); Assert.NotNull(ex); } } }
Bring across Server Sent Events resource implementation
namespace Glimpse.Server.Web { public class MessageStreamResource : IResourceStartup { private readonly IServerBroker _serverBroker; public MessageStreamResource(IServerBroker serverBroker) { _serverBroker = serverBroker; } public void Configure(IResourceBuilder resourceBuilder) { // TODO: Need to get data to the client throw new System.NotImplementedException(); } } }
using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http; using System; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Glimpse.Server.Web { public class MessageStreamResource : IResourceStartup { private readonly IServerBroker _serverBroker; private readonly ISubject<string> _senderSubject; private readonly JsonSerializer _jsonSerializer; public MessageStreamResource(IServerBroker serverBroker, JsonSerializer jsonSerializer) { jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); _jsonSerializer = jsonSerializer; _serverBroker = serverBroker; _senderSubject = new Subject<string>(); // TODO: See if we can get Defered working there // lets subscribe, hope of the thread and then broadcast to all connections //_serverBroker.OffRecieverThread.ListenAll().Subscribe(message => Observable.Defer(() => Observable.Start(() => ProcessMessage(message), TaskPoolScheduler.Default))); _serverBroker.OffRecieverThread.ListenAll().Subscribe(message => Observable.Start(() => ProcessMessage(message), TaskPoolScheduler.Default)); } public void Configure(IResourceBuilder resourceBuilder) { resourceBuilder.Run("MessageStream", null, async (context, dictionary) => { var continueTask = new TaskCompletionSource<bool>(); // Disable request compression var buffering = context.Features.Get<IHttpBufferingFeature>(); if (buffering != null) { buffering.DisableRequestBuffering(); } context.Response.ContentType = "text/event-stream"; await context.Response.WriteAsync("retry: 5000\n\n"); await context.Response.WriteAsync("data: pong\n\n"); await context.Response.Body.FlushAsync(); var unSubscribe = _senderSubject.Subscribe(async t => { await context.Response.WriteAsync($"data: {t}\n\n"); await context.Response.Body.FlushAsync(); }); context.RequestAborted.Register(() => { continueTask.SetResult(true); unSubscribe.Dispose(); }); await continueTask.Task; }); } private void ProcessMessage(IMessage message) { var payload = _jsonSerializer.Serialize(message); _senderSubject.OnNext(payload); } } }
Remove Gender, Age in Model.
using System.Collections.ObjectModel; using System.ComponentModel; using App2Night.Model.Enum; namespace App2Night.Model.Model { public class User { public string Name { get; set; } public int Age { get; set; } public Gender Gender { get; set; } = Gender.Unkown; public string Email { get; set; } public ObservableCollection<Party> Events { get; set; } public Location Addresse { get; set; } public Location LastGpsLocation { get; set; } } }
using System.Collections.ObjectModel; using System.ComponentModel; using App2Night.Model.Enum; namespace App2Night.Model.Model { public class User { public string Name { get; set; } public string Email { get; set; } public ObservableCollection<Party> Events { get; set; } public Location Addresse { get; set; } public Location LastGpsLocation { get; set; } } }
Include original WebException when throwing new ApplicationException
using System; using System.Net; namespace DevDefined.OAuth.Consumer { public interface IConsumerRequestRunner { IConsumerResponse Run(IConsumerRequest consumerRequest); } public class DefaultConsumerRequestRunner : IConsumerRequestRunner { public IConsumerResponse Run(IConsumerRequest consumerRequest) { HttpWebRequest webRequest = consumerRequest.ToWebRequest(); IConsumerResponse consumerResponse = null; try { consumerResponse = new ConsumerResponse(webRequest.GetResponse() as HttpWebResponse); } catch (WebException webEx) { // I *think* it's safe to assume that the response will always be a HttpWebResponse... HttpWebResponse httpWebResponse = (HttpWebResponse)(webEx.Response); if (httpWebResponse == null) { throw new ApplicationException("An HttpWebResponse could not be obtained from the WebException. Status was " + webEx.Status.ToString()); } consumerResponse = new ConsumerResponse(httpWebResponse, webEx); } return consumerResponse; } } }
using System; using System.Net; namespace DevDefined.OAuth.Consumer { public interface IConsumerRequestRunner { IConsumerResponse Run(IConsumerRequest consumerRequest); } public class DefaultConsumerRequestRunner : IConsumerRequestRunner { public IConsumerResponse Run(IConsumerRequest consumerRequest) { HttpWebRequest webRequest = consumerRequest.ToWebRequest(); IConsumerResponse consumerResponse = null; try { consumerResponse = new ConsumerResponse(webRequest.GetResponse() as HttpWebResponse); } catch (WebException webEx) { // I *think* it's safe to assume that the response will always be a HttpWebResponse... HttpWebResponse httpWebResponse = (HttpWebResponse)(webEx.Response); if (httpWebResponse == null) { throw new ApplicationException("An HttpWebResponse could not be obtained from the WebException. Status was " + webEx.Status, webEx); } consumerResponse = new ConsumerResponse(httpWebResponse, webEx); } return consumerResponse; } } }
Use AssemblyHelper for MainWindow title version
using GalaSoft.MvvmLight.Messaging; using KAGTools.Helpers; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace KAGTools.Windows { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { if (double.IsNaN(Properties.Settings.Default.Left) || double.IsNaN(Properties.Settings.Default.Top)) { WindowStartupLocation = WindowStartupLocation.CenterScreen; } InitializeComponent(); Version version = Assembly.GetEntryAssembly().GetName().Version; Title += string.Format(" v{0}", version.ToString()); } private async void Window_Loaded(object sender, RoutedEventArgs e) { await UpdateHelper.UpdateApp(); } } }
using GalaSoft.MvvmLight.Messaging; using KAGTools.Helpers; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace KAGTools.Windows { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { if (double.IsNaN(Properties.Settings.Default.Left) || double.IsNaN(Properties.Settings.Default.Top)) { WindowStartupLocation = WindowStartupLocation.CenterScreen; } InitializeComponent(); Title += string.Format(" v{0}", AssemblyHelper.Version); } private async void Window_Loaded(object sender, RoutedEventArgs e) { await UpdateHelper.UpdateApp(); } } }
Add ProfileMatches to CustomerRegistration response
using System; using System.Collections.Generic; namespace GIDX.SDK.Models.CustomerIdentity { public class CustomerRegistrationResponse : ResponseBase, IReasonCodes { public string MerchantCustomerID { get; set; } public decimal IdentityConfidenceScore { get; set; } public decimal FraudConfidenceScore { get; set; } public List<string> ReasonCodes { get; set; } public LocationDetail LocationDetail { get; set; } public ProfileMatch ProfileMatch { get; set; } public List<WatchCheck> WatchChecks { get; set; } } }
using System; using System.Collections.Generic; namespace GIDX.SDK.Models.CustomerIdentity { public class CustomerRegistrationResponse : ResponseBase, IReasonCodes { public string MerchantCustomerID { get; set; } public decimal IdentityConfidenceScore { get; set; } public decimal FraudConfidenceScore { get; set; } public List<string> ReasonCodes { get; set; } public LocationDetail LocationDetail { get; set; } public ProfileMatch ProfileMatch { get; set; } public List<string> ProfileMatches { get; set; } public List<WatchCheck> WatchChecks { get; set; } } }
Add DoNotAwait for WinRT style tasks
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DigiTransit10.ExtensionMethods { public static class TaskExtensions { public static void DoNotAwait(this Task task) { } public static void DoNotAwait<T>(this Task<T> task) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; namespace DigiTransit10.ExtensionMethods { public static class TaskExtensions { public static void DoNotAwait(this Task task) { } public static void DoNotAwait<T>(this Task<T> task) { } public static void DoNotAwait(this IAsyncAction task) { } } }
Add test for non invariant default locale and test for locale with collation
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class Test { [Fact] public void TestCurrentCultures() { CultureInfo defaultCulture = CultureInfo.CurrentCulture; CultureInfo newCulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo defaultUICulture = CultureInfo.CurrentUICulture; CultureInfo newUICulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); CultureInfo.CurrentCulture = defaultCulture; Assert.Equal(CultureInfo.CurrentCulture, defaultCulture); CultureInfo.CurrentUICulture = defaultUICulture; Assert.Equal(CultureInfo.CurrentUICulture, defaultUICulture); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class Test { [Fact] public void TestCurrentCulture() { // run all tests in one method to avoid multi-threading issues CultureInfo defaultCulture = CultureInfo.CurrentCulture; Assert.NotEqual(CultureInfo.InvariantCulture, defaultCulture); CultureInfo newCulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); newCulture = new CultureInfo("de-DE_phoneb"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); Assert.Equal("de-DE_phoneb", newCulture.CompareInfo.Name); CultureInfo.CurrentCulture = defaultCulture; Assert.Equal(CultureInfo.CurrentCulture, defaultCulture); } [Fact] public void TestCurrentUICulture() { // run all tests in one method to avoid multi-threading issues CultureInfo defaultUICulture = CultureInfo.CurrentUICulture; Assert.NotEqual(CultureInfo.InvariantCulture, defaultUICulture); CultureInfo newUICulture = new CultureInfo(defaultUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); newUICulture = new CultureInfo("de-DE_phoneb"); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); Assert.Equal("de-DE_phoneb", newUICulture.CompareInfo.Name); CultureInfo.CurrentUICulture = defaultUICulture; Assert.Equal(CultureInfo.CurrentUICulture, defaultUICulture); } } }
Disable test parallelization due to shared state problems
using System; using System.Reflection; 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("StyleCop.Analyzers.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("StyleCop.Analyzers.Test")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // 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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0-dev")]
using System; using System.Reflection; using System.Runtime.InteropServices; using Xunit; // 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("StyleCop.Analyzers.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("StyleCop.Analyzers.Test")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // 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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0-dev")] [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)]
Disable test to get clean build
using JetBrains.ReSharper.FeaturesTestFramework.Completion; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.Feature.Services.CodeCompletion { // TODO: This doesn't test automatic completion // The AutomaticCodeCompletionTestBase class is not in the SDK [TestUnity] public class UnityEventFunctionCompletionListTest : CodeCompletionTestBase { protected override CodeCompletionTestType TestType => CodeCompletionTestType.List; protected override string RelativeTestDataPath => @"codeCompletion\List"; protected override bool CheckAutomaticCompletionDefault() => true; [Test] public void MonoBehaviour01() { DoNamedTest(); } [Test] public void MonoBehaviour02() { DoNamedTest(); } [Test] public void MonoBehaviour03() { DoNamedTest(); } [Test] public void MonoBehaviour04() { DoNamedTest(); } [Test] public void MonoBehaviour05() { DoNamedTest(); } [Test] public void MonoBehaviour06() { DoNamedTest(); } } }
using JetBrains.ReSharper.FeaturesTestFramework.Completion; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.Feature.Services.CodeCompletion { // TODO: This doesn't test automatic completion // The AutomaticCodeCompletionTestBase class is not in the SDK [TestUnity] public class UnityEventFunctionCompletionListTest : CodeCompletionTestBase { protected override CodeCompletionTestType TestType => CodeCompletionTestType.List; protected override string RelativeTestDataPath => @"codeCompletion\List"; protected override bool CheckAutomaticCompletionDefault() => true; //[Test] public void MonoBehaviour01() { DoNamedTest(); } [Test] public void MonoBehaviour02() { DoNamedTest(); } [Test] public void MonoBehaviour03() { DoNamedTest(); } [Test] public void MonoBehaviour04() { DoNamedTest(); } [Test] public void MonoBehaviour05() { DoNamedTest(); } [Test] public void MonoBehaviour06() { DoNamedTest(); } } }
Add quotes to paths for Windows
using System.Diagnostics; using System.IO; using System.Linq; namespace grr.Messages { [System.Diagnostics.DebuggerDisplay("{GetRemoteCommand()}")] public class OpenDirectoryMessage : DirectoryMessage { public OpenDirectoryMessage(RepositoryFilterOptions filter) : base(filter) { } protected override void ExecuteExistingDirectory(string directory) { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) directory = directory.Replace(@"\", "/"); Process.Start(new ProcessStartInfo($"\"{directory}\"") { UseShellExecute = true }); } } }
using System.Diagnostics; using System.IO; using System.Linq; namespace grr.Messages { [System.Diagnostics.DebuggerDisplay("{GetRemoteCommand()}")] public class OpenDirectoryMessage : DirectoryMessage { public OpenDirectoryMessage(RepositoryFilterOptions filter) : base(filter) { } protected override void ExecuteExistingDirectory(string directory) { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) directory = directory.Replace(@"\", "/"); if (Platform == "win") directory == $"\"{directory}\""; Process.Start(new ProcessStartInfo(directory) { UseShellExecute = true }); } } }
Implement "enable" event to reenable after "stop".
using UnityEngine; using SocketIOClient; public class ServoControllerClient : AbstractSocketioClient { private static readonly string SOCKETIO_SERVER = "http://192.168.1.51:5000"; private static readonly string SOCKETIO_NAMESPACE = "/servo"; public ServoControllerClient() : base(SOCKETIO_SERVER, SOCKETIO_NAMESPACE){} /* -------------------- */ /* - Eventemitter - */ /* -------------------- */ public void EventSetServoPosition(long position) { this.Emit("moveTo", position); } public void EventStop() { this.Emit("stop"); } public void PullToLeft() { this.Emit("pullToLeft"); } public void PullToRight() { this.Emit("pullToRight"); } }
using UnityEngine; using SocketIOClient; public class ServoControllerClient : AbstractSocketioClient { private static readonly string SOCKETIO_SERVER = "http://192.168.1.51:5000"; private static readonly string SOCKETIO_NAMESPACE = "/servo"; public ServoControllerClient() : base(SOCKETIO_SERVER, SOCKETIO_NAMESPACE){} /* -------------------- */ /* - Eventemitter - */ /* -------------------- */ public void EventSetServoPosition(long position) { Debug.LogWarning("Set servo to: " + position); this.Emit("moveTo", position); } public void EventStop() { this.Emit("stop"); } public void EventEnable() { this.Emit("enable"); } public void PullToLeft() { this.Emit("pullToLeft"); } public void PullToRight() { this.Emit("pullToRight"); } }
Include date in booked in fact
using System; using EventStore.ClientAPI; using System.Net; namespace EventStorePlayConsole { public class BookedInFact:Fact { public BookedInFact(string atValue, string someValue) { this.BookedInAtValue = atValue; this.PreviousBookingValue = someValue; } public string BookedInAtValue { get; private set; } public string PreviousBookingValue { get; private set; } public override string ToString() { return string.Format("[BookedInEvent: Id={0}, BookedInAtValue={1}, PreviousBookingValue={2}]", Id, BookedInAtValue, PreviousBookingValue); } } }
using System; using EventStore.ClientAPI; using System.Net; namespace EventStorePlayConsole { public class BookedInFact:Fact { public BookedInFact(string atValue, string someValue) { this.OccurredAt = DateTime.UtcNow; this.BookedInAtValue = atValue; this.PreviousBookingValue = someValue; } public DateTime OccurredAt { get; private set; } public string BookedInAtValue { get; private set; } public string PreviousBookingValue { get; private set; } public override string ToString() { return string.Format("[BookedInEvent: Id={0}, BookedInAtValue={1}, PreviousBookingValue={2}]", Id, BookedInAtValue, PreviousBookingValue); } } }
Make stats_only_admins a nullable bool, we're seeing this cause json deserialization exceptions when calling SlackClient.ConnectAsync()
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class TeamPreferences { public AuthMode auth_mode; public string[] default_channels; public bool display_real_names; public bool gateway_allow_irc_plain; public bool gateway_allow_irc_ssl; public bool gateway_allow_xmpp_ssl; public bool hide_referers; public int msg_edit_window_mins; public bool srvices_only_admins; public bool stats_only_admins; public enum AuthMode { normal, saml, google } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class TeamPreferences { public AuthMode auth_mode; public string[] default_channels; public bool display_real_names; public bool gateway_allow_irc_plain; public bool gateway_allow_irc_ssl; public bool gateway_allow_xmpp_ssl; public bool hide_referers; public int msg_edit_window_mins; public bool srvices_only_admins; public bool? stats_only_admins; public enum AuthMode { normal, saml, google } } }
Fix schedule stops not being ordered.
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.ViewModels.Wrappers; namespace TramlineFive.ViewModels { public class StopsViewModel { public IList<StopViewModel> LineStops { get; private set; } public StopsViewModel(ScheduleChooserViewModel scheduleChooser) { scheduleChooserViewModel = scheduleChooser; LineStops = new ObservableCollection<StopViewModel>(); } public async Task LoadStops() { await scheduleChooserViewModel.SelectedDay.LoadStops(); LineStops = scheduleChooserViewModel.SelectedDay.Stops.OrderBy(s => s.) foreach (StopViewModel stop in scheduleChooserViewModel.SelectedDay.Stops) LineStops.Add(stop); } public string Title { get { return $"{scheduleChooserViewModel.SelectedLine.ShortName} - {scheduleChooserViewModel.SelectedDirection.Name.ToUpper()}"; } } private ScheduleChooserViewModel scheduleChooserViewModel; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.ViewModels.Wrappers; namespace TramlineFive.ViewModels { public class StopsViewModel { public IList<StopViewModel> LineStops { get; private set; } public StopsViewModel(ScheduleChooserViewModel scheduleChooser) { scheduleChooserViewModel = scheduleChooser; LineStops = new ObservableCollection<StopViewModel>(); } public async Task LoadStops() { await scheduleChooserViewModel.SelectedDay.LoadStops(); LineStops = scheduleChooserViewModel.SelectedDay.Stops.OrderBy(s => s.Index).ToList(); } public string Title { get { return $"{scheduleChooserViewModel.SelectedLine.ShortName} - {scheduleChooserViewModel.SelectedDirection.Name.ToUpper()}"; } } private ScheduleChooserViewModel scheduleChooserViewModel; } }
Use CurrentUICulture for EditorConfig UI
// 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.Globalization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal class AnalyzerSetting { private readonly DiagnosticDescriptor _descriptor; private readonly AnalyzerSettingsUpdater _settingsUpdater; public AnalyzerSetting(DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, AnalyzerSettingsUpdater settingsUpdater, Language language) { _descriptor = descriptor; _settingsUpdater = settingsUpdater; DiagnosticSeverity severity = default; if (effectiveSeverity == ReportDiagnostic.Default) { severity = descriptor.DefaultSeverity; } else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1) { severity = severity1; } var enabled = effectiveSeverity != ReportDiagnostic.Suppress; IsEnabled = enabled; Severity = severity; Language = language; } public string Id => _descriptor.Id; public string Title => _descriptor.Title.ToString(CultureInfo.CurrentCulture); public string Description => _descriptor.Description.ToString(CultureInfo.CurrentCulture); public string Category => _descriptor.Category; public DiagnosticSeverity Severity { get; private set; } public bool IsEnabled { get; private set; } public Language Language { get; } internal void ChangeSeverity(DiagnosticSeverity severity) { if (severity == Severity) return; Severity = severity; _settingsUpdater.QueueUpdate(this, severity); } } }
// 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.Globalization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal class AnalyzerSetting { private readonly DiagnosticDescriptor _descriptor; private readonly AnalyzerSettingsUpdater _settingsUpdater; public AnalyzerSetting(DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, AnalyzerSettingsUpdater settingsUpdater, Language language) { _descriptor = descriptor; _settingsUpdater = settingsUpdater; DiagnosticSeverity severity = default; if (effectiveSeverity == ReportDiagnostic.Default) { severity = descriptor.DefaultSeverity; } else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1) { severity = severity1; } var enabled = effectiveSeverity != ReportDiagnostic.Suppress; IsEnabled = enabled; Severity = severity; Language = language; } public string Id => _descriptor.Id; public string Title => _descriptor.Title.ToString(CultureInfo.CurrentUICulture); public string Description => _descriptor.Description.ToString(CultureInfo.CurrentUICulture); public string Category => _descriptor.Category; public DiagnosticSeverity Severity { get; private set; } public bool IsEnabled { get; private set; } public Language Language { get; } internal void ChangeSeverity(DiagnosticSeverity severity) { if (severity == Severity) return; Severity = severity; _settingsUpdater.QueueUpdate(this, severity); } } }
Clean analyzer warnings on test projects
 // 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. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "We use lower-case BDD style naming for tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1024:Test methods cannot have overloads", Justification = "We re-declare the methods in the derived class to annotate with inline data/theory.")]
 // 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. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "We use lower-case BDD style naming for tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1024:Test methods cannot have overloads", Justification = "We re-declare the methods in the derived class to annotate with inline data/theory.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "For unit tests, no public API.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD012:Provide JoinableTaskFactory where allowed", Justification = "For unit tests, no public API.")]
Add more tests for puzzle 14
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using Xunit; /// <summary> /// A class containing tests for the <see cref="Puzzle014"/> class. This class cannot be inherited. /// </summary> public static class Puzzle014Tests { [Fact] public static void Puzzle014_Returns_Correct_Solution() { // Arrange object expected = 837799; // Act and Assert Puzzles.AssertSolution<Puzzle014>(expected); } [Fact] public static void Puzzle_014_GetCollatzSequence_Returns_Correct_Sequence() { // Arrange long start = 13; var expected = new long[] { 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 }; // Act var actual = Puzzle014.GetCollatzSequence(start); // Assert Assert.Equal(expected, actual); } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using Xunit; /// <summary> /// A class containing tests for the <see cref="Puzzle014"/> class. This class cannot be inherited. /// </summary> public static class Puzzle014Tests { [Fact] public static void Puzzle014_Returns_Correct_Solution() { // Arrange object expected = 837799; // Act and Assert Puzzles.AssertSolution<Puzzle014>(expected); } [Theory] [InlineData(1L, new long[] { 1 })] [InlineData(2L, new long[] { 2, 1 })] [InlineData(3L, new long[] { 3, 10, 5, 16, 8, 4, 2, 1 })] [InlineData(4L, new long[] { 4, 2, 1 })] [InlineData(13L, new long[] { 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 })] public static void Puzzle014_GetCollatzSequence_Returns_Correct_Sequence(long start, long[] expected) { // Act var actual = Puzzle014.GetCollatzSequence(start); // Assert Assert.Equal(expected, actual); } } }
Fix crashing due to missing history in LFR
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastFinishedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Finished Run"; public const string ShortComparisonName = "Last Run"; public string Name => ComparisonName; public LastFinishedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentFinished = null; foreach (var attempt in Run.AttemptHistory.Reverse()) { if (attempt.Time[method] != null) { mostRecentFinished = attempt; break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime; if (mostRecentFinished != null) segmentTime = Run[ind].SegmentHistory[mostRecentFinished.Value.Index][method]; else segmentTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastFinishedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Finished Run"; public const string ShortComparisonName = "Last Run"; public string Name => ComparisonName; public LastFinishedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentFinished = null; foreach (var attempt in Run.AttemptHistory.Reverse()) { if (attempt.Time[method] != null) { mostRecentFinished = attempt; break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime = null; if (mostRecentFinished != null && Run[ind].SegmentHistory.ContainsKey(mostRecentFinished.Value.Index)) segmentTime = Run[ind].SegmentHistory[mostRecentFinished.Value.Index][method]; else totalTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
Fix ghost orbit not syncing to other clients
using Robust.Shared.Animations; namespace Content.Shared.Follower.Components; [RegisterComponent] public sealed class OrbitVisualsComponent : Component { /// <summary> /// How long should the orbit animation last in seconds, before being randomized? /// </summary> public float OrbitLength = 2.0f; /// <summary> /// How far away from the entity should the orbit be, before being randomized? /// </summary> public float OrbitDistance = 1.0f; /// <summary> /// How long should the orbit stop animation last in seconds? /// </summary> public float OrbitStopLength = 1.0f; /// <summary> /// How far along in the orbit, from 0 to 1, is this entity? /// </summary> [Animatable] public float Orbit { get; set; } = 0.0f; }
using Robust.Shared.Animations; using Robust.Shared.GameStates; namespace Content.Shared.Follower.Components; [RegisterComponent] [NetworkedComponent] public sealed class OrbitVisualsComponent : Component { /// <summary> /// How long should the orbit animation last in seconds, before being randomized? /// </summary> public float OrbitLength = 2.0f; /// <summary> /// How far away from the entity should the orbit be, before being randomized? /// </summary> public float OrbitDistance = 1.0f; /// <summary> /// How long should the orbit stop animation last in seconds? /// </summary> public float OrbitStopLength = 1.0f; /// <summary> /// How far along in the orbit, from 0 to 1, is this entity? /// </summary> [Animatable] public float Orbit { get; set; } = 0.0f; }
Add PsiFeaturesImplZone for parent settings key.
using JetBrains.Application.BuildScript.Application.Zones; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity { [ZoneMarker] public class ZoneMarker { } }
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Resources.Shell; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity { [ZoneMarker] public class ZoneMarker : IRequire<PsiFeaturesImplZone> { } }
Replace Boolean with bool so we can remove System
using System; public class Year { public static Boolean IsLeap(int i) { if (i % 4 != 0) { return false; } if (i % 100 == 0) { if (i % 400 != 0) { return false; } } return true; } }
public class Year { public static bool IsLeap(int i) { if (i % 4 != 0) { return false; } if (i % 100 == 0) { if (i % 400 != 0) { return false; } } return true; } }
Remove unnecessary cache type specification
// 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 osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Timing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps { /// <summary> /// Provides various data sources which allow for synchronising visuals to a known beat. /// Primarily intended for use with <see cref="BeatSyncedContainer"/>. /// </summary> [Cached(typeof(IBeatSyncProvider))] public interface IBeatSyncProvider { ControlPointInfo? ControlPoints { get; } IClock? Clock { get; } ChannelAmplitudes? Amplitudes { get; } } }
// 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 osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Timing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps { /// <summary> /// Provides various data sources which allow for synchronising visuals to a known beat. /// Primarily intended for use with <see cref="BeatSyncedContainer"/>. /// </summary> [Cached] public interface IBeatSyncProvider { ControlPointInfo? ControlPoints { get; } IClock? Clock { get; } ChannelAmplitudes? Amplitudes { get; } } }
Include method in cache key
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.Linq; namespace HttpMock { public class RequestCacheKey { public string Scheme { get; private set; } public string Host { get; private set; } public int? Port { get; private set; } public string Path { get; private set; } public string Query { get; private set; } public KeyValuePair<string, StringValues>[] Headers { get; private set; } public RequestCacheKey(HttpRequest request, IEnumerable<string> headers) { Scheme = request.Scheme; Host = request.Host.Host; Port = request.Host.Port; Path = request.Path.Value; Query = request.QueryString.Value; Headers = request.Headers.Where(h => headers.Contains(h.Key)).ToArray(); } public override int GetHashCode() { var hash = new HashCode(); hash.Add(Scheme); hash.Add(Host); hash.Add(Port); hash.Add(Path); hash.Add(Query); foreach (var h in Headers) { hash.Add(h.Key); hash.Add(h.Value); } return hash.ToHashCode(); } public override bool Equals(object obj) { return obj is RequestCacheKey other && Scheme == other.Scheme && Host == other.Host && Port == other.Port && Path == other.Path && Query == other.Query && Headers.SequenceEqual(other.Headers); } } }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.Linq; namespace HttpMock { public class RequestCacheKey { public string Method { get; private set; } public string Scheme { get; private set; } public string Host { get; private set; } public int? Port { get; private set; } public string Path { get; private set; } public string Query { get; private set; } public KeyValuePair<string, StringValues>[] Headers { get; private set; } public RequestCacheKey(HttpRequest request, IEnumerable<string> headers) { Method = request.Method; Scheme = request.Scheme; Host = request.Host.Host; Port = request.Host.Port; Path = request.Path.Value; Query = request.QueryString.Value; Headers = request.Headers.Where(h => headers.Contains(h.Key)).ToArray(); } public override int GetHashCode() { var hash = new HashCode(); hash.Add(Method); hash.Add(Scheme); hash.Add(Host); hash.Add(Port); hash.Add(Path); hash.Add(Query); foreach (var h in Headers) { hash.Add(h.Key); hash.Add(h.Value); } return hash.ToHashCode(); } public override bool Equals(object obj) { return obj is RequestCacheKey other && Method == other.Method && Scheme == other.Scheme && Host == other.Host && Port == other.Port && Path == other.Path && Query == other.Query && Headers.SequenceEqual(other.Headers); } } }
Increase assembly version to 1.1.
// Copyright // ---------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable"> // MIT // </copyright> // <license> // This source code is subject to terms and conditions of The MIT License (MIT). // A copy of the license can be found in the License.txt file at the root of this distribution. // </license> // <summary> // Contains the attributes that provide information about the assembly. // </summary> // ---------------------------------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Dawn.SocketAwaitable")] [assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")] [assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")] [assembly: AssemblyProduct("Dawn Framework")] [assembly: AssemblyCopyright("MIT")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
// Copyright // ---------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable"> // MIT // </copyright> // <license> // This source code is subject to terms and conditions of The MIT License (MIT). // A copy of the license can be found in the License.txt file at the root of this distribution. // </license> // <summary> // Contains the attributes that provide information about the assembly. // </summary> // ---------------------------------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Dawn.SocketAwaitable")] [assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")] [assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")] [assembly: AssemblyProduct("Dawn Framework")] [assembly: AssemblyCopyright("MIT")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif