Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add missing project context handler for ts
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript; [ExportStatelessLspService(typeof(GetTextDocumentWithContextHandler), ProtocolConstants.TypeScriptLanguageContract), Shared] internal class VSTypeScriptProjectContextHandler : GetTextDocumentWithContextHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptProjectContextHandler() { } }
Add factory for analytics migrations
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Nether.Data.Sql.Common; using System; using System.Collections.Generic; using System.Text; namespace Nether.Data.Sql.Analytics { /// <summary> /// Class added to enable creating EF Migrations /// See https://docs.microsoft.com/en-us/ef/core/api/microsoft.entityframeworkcore.infrastructure.idbcontextfactory-1 /// </summary> public class SqlAnalyticsContextFactory : IDbContextFactory<SqlAnalyticsContext> { public SqlAnalyticsContext Create(DbContextFactoryOptions options) { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(); var logger = loggerFactory.CreateLogger<SqlAnalyticsContextFactory>(); var configuration = ConfigurationHelper.GetConfiguration(logger, options.ContentRootPath, options.EnvironmentName); var connectionString = configuration["Analytics:Store:properties:ConnectionString"]; logger.LogInformation("Using connection string: {0}", connectionString); return new SqlAnalyticsContext( loggerFactory, new SqlAnalyticsContextOptions { ConnectionString = connectionString }); } } }
Add order controller for authentified users
using System; using System.Collections.Generic; using System.Web.Http; namespace TokenAuthentification.Controllers { [RoutePrefix("api/orders")] public class OrdersController : ApiController { [Authorize] [Route("")] public IHttpActionResult Get() { return Ok(Order.CreateOrders()); } } #region Helpers public class Order { public int OrderID { get; set; } public string CustomerName { get; set; } public string ShipperCity { get; set; } public Boolean IsShipped { get; set; } public static List<Order> CreateOrders() { List<Order> OrderList = new List<Order> { new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true }, new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false}, new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false }, new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false}, new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true} }; return OrderList; } } #endregion }
Increment release number to 2.0.14
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following set of attributes. // Change these attribute values to modify the information associated with an assembly. [assembly: AssemblyTitle("Certify - SSL Certificate Manager")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Certify")] [assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible to COM components. If you // need to access a type in this assembly from COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")] // Version information for an assembly consists of the following four values: // // Major Version Minor Version Build Number Revision // // You can specify all the values or you can default the Build and Revision Numbers by using the '*' // as shown below: [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.13.*")] [assembly: AssemblyFileVersion("2.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following set of attributes. // Change these attribute values to modify the information associated with an assembly. [assembly: AssemblyTitle("Certify - SSL Certificate Manager")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Certify")] [assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible to COM components. If you // need to access a type in this assembly from COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")] // Version information for an assembly consists of the following four values: // // Major Version Minor Version Build Number Revision // // You can specify all the values or you can default the Build and Revision Numbers by using the '*' // as shown below: [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.14.*")] [assembly: AssemblyFileVersion("2.0.0")]
Add a failing test to check catch replay accuracy
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.UI; namespace osu.Game.Rulesets.Catch.Tests { public class TestSceneCatchReplay : TestSceneCatchPlayer { protected override bool Autoplay => true; private const int object_count = 10; [Test] public void TestReplayCatcherPositionIsFramePerfect() { AddUntilStep("caught all fruits", () => Player.ScoreProcessor.Combo.Value == object_count); } protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = new Beatmap { BeatmapInfo = { Ruleset = ruleset, } }; beatmap.ControlPointInfo.Add(0, new TimingControlPoint()); for (int i = 0; i < object_count / 2; i++) { beatmap.HitObjects.Add(new Fruit { StartTime = (i + 1) * 1000, X = 0 }); beatmap.HitObjects.Add(new Fruit { StartTime = (i + 1) * 1000 + 1, X = CatchPlayfield.WIDTH }); } return beatmap; } } }
Add user controller on API to check in/outs.
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using A2BBCommon.Models; using A2BBCommon; using A2BBAPI.Data; using IdentityModel.Client; using A2BBAPI.DTO; using Microsoft.Extensions.Logging; using A2BBAPI.Models; using System.Collections.Generic; using A2BBAPI.Utils; using static A2BBAPI.Utils.ClaimsUtils; using Microsoft.Extensions.Caching.Memory; namespace A2BBAPI.Controllers { /// <summary> /// Controller to manage user devices. /// </summary> [Produces("application/json")] [Route("api/me/inout")] [Authorize("User")] public class MeInOutController : Controller { #region Private fields /// <summary> /// The DB context. /// </summary> private readonly A2BBApiDbContext _dbContext; /// <summary> /// The logger. /// </summary> private readonly ILogger _logger; #endregion #region Public methods /// <summary> /// Create a new isntance of this class. /// </summary> /// <param name="dbContext">The DI DB context.</param> /// <param name="loggerFactory">The DI logger factory.</param> public MeInOutController(A2BBApiDbContext dbContext, ILoggerFactory loggerFactory) { _dbContext = dbContext; _logger = loggerFactory.CreateLogger<MeController>(); } [HttpGet] public ResponseWrapper<IEnumerable<InOut>> ListAll() { return new ResponseWrapper<IEnumerable<InOut>>(_dbContext.InOut.Where(io => io.Device.UserId == User.Claims.FirstOrDefault(c => c.Type == "sub").Value), Constants.RestReturn.OK); } [HttpGet] [Route("{deviceId}")] public ResponseWrapper<IEnumerable<InOut>> ListOfSpecificDevice([FromRoute] int deviceId) { return new ResponseWrapper<IEnumerable<InOut>>(_dbContext.InOut.Where(io => io.Device.UserId == User.Claims.FirstOrDefault(c => c.Type == "sub").Value && io.DeviceId == deviceId), Constants.RestReturn.OK); } #endregion } }
Add unit tests to verify that the amount parameters are added to the query string when they are added as parameter
using Mollie.Api.Client; using Mollie.Api.Models; using NUnit.Framework; using System.Net.Http; using System.Threading.Tasks; namespace Mollie.Tests.Unit.Client { [TestFixture] public class PaymentMethodClientTests : BaseClientTests { private const string defaultPaymentMethodJsonResponse = @"{ ""count"": 13, ""_embedded"": { ""methods"": [ { ""resource"": ""method"", ""id"": ""ideal"", ""description"": ""iDEAL"" } ] } }"; [Test] public async Task GetPaymentMethodListAsync_NoAmountParameter_QueryStringIsEmpty() { // Given: We make a request to retrieve a order without wanting any extra data var mockHttp = this.CreateMockHttpMessageHandler(HttpMethod.Get, $"{BaseMollieClient.ApiEndPoint}methods/all", defaultPaymentMethodJsonResponse); HttpClient httpClient = mockHttp.ToHttpClient(); PaymentMethodClient paymentMethodClient = new PaymentMethodClient("abcde", httpClient); // When: We send the request await paymentMethodClient.GetAllPaymentMethodListAsync(); // Then mockHttp.VerifyNoOutstandingExpectation(); } [Test] public async Task GetPaymentMethodListAsync_AmountParameterIsAdded_QueryStringContainsAmount() { // Given: We make a request to retrieve a order without wanting any extra data var mockHttp = this.CreateMockHttpMessageHandler(HttpMethod.Get, $"{BaseMollieClient.ApiEndPoint}methods/all?amount[value]=100.00&amount[currency]=EUR", defaultPaymentMethodJsonResponse); HttpClient httpClient = mockHttp.ToHttpClient(); PaymentMethodClient paymentMethodClient = new PaymentMethodClient("abcde", httpClient); // When: We send the request await paymentMethodClient.GetAllPaymentMethodListAsync(amount: new Amount("EUR", 100)); // Then mockHttp.VerifyNoOutstandingExpectation(); } } }
Add a new datatype for joints
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using System.IO; namespace MultipleKinectsPlatform.MultipleKinectsPlatform.Data { [DataContract(Name="Joint")] public class Joint { [DataMember] public float X; [DataMember] public float Y; [DataMember] public float Z; public Joint(float i_x, float i_y, float i_z) { X = i_x; Y = i_y; Z = i_z; } } }
Add shared helper to flatten response headers
using System.Collections.Generic; using System.Net.Http; namespace Amazon.S3 { internal static class HttpResponseMessageExtensions { public static Dictionary<string, string> GetProperties(this HttpResponseMessage response) { #if NET5_0 var result = new Dictionary<string, string>(16); foreach (var header in response.Headers) { result.Add(header.Key, string.Join(';', header.Value)); } foreach (var header in response.Content.Headers) { result.Add(header.Key, string.Join(';', header.Value)); } #else var baseHeaders = response.Headers.NonValidated; var contentHeaders = response.Content.Headers.NonValidated; var result = new Dictionary<string, string>(baseHeaders.Count + contentHeaders.Count); foreach (var header in baseHeaders) { result.Add(header.Key, header.Value.ToString()); } foreach (var header in contentHeaders) { result.Add(header.Key, header.Value.ToString()); } #endif return result; } } }
Add method to return Edge from IRefAxis
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using SolidworksAddinFramework.Geometry; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class RefAxisExtensions { public static Edge3 Edge(this IRefAxis axis) { var axisParams = axis.GetRefAxisParams().DirectCast<double[]>(); return new Edge3(new Vector3((float) axisParams[0], (float) axisParams[1], (float) axisParams[2]) ,new Vector3((float) axisParams[3], (float) axisParams[4], (float) axisParams[5])); } } }
Define the factory to handle the build of list
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace NBi.Core.Members { public class PredefinedMembersFactory { private readonly ICollection<BuilderRegistration> registrations; public PredefinedMembersFactory() { registrations = new List<BuilderRegistration>(); RegisterDefaults(); } private void RegisterDefaults() { Register(PredefinedMembers.DaysOfWeek, new DaysOfWeekBuilder()); Register(PredefinedMembers.MonthsOfYear, new MonthsOfYearBuilder()); } /// <summary> /// Register a new builder for corresponding types. If a builder was already existing for this association, it's replaced by the new one /// </summary> /// <param name="sutType">Type of System Under Test</param> /// <param name="ctrType">Type of Constraint</param> /// <param name="builder">Instance of builder deicated for these types of System Under Test and Constraint</param> public void Register(PredefinedMembers value, IPredefinedMembersBuilder builder) { if (IsHandling(value)) registrations.FirstOrDefault(reg => reg.Value == value).Builder = builder; else registrations.Add(new BuilderRegistration(value, builder)); } private bool IsHandling(PredefinedMembers value) { var existing = registrations.FirstOrDefault(reg => reg.Value == value); return (existing != null); } private class BuilderRegistration { public PredefinedMembers Value { get; set; } public IPredefinedMembersBuilder Builder { get; set; } public BuilderRegistration(PredefinedMembers value, IPredefinedMembersBuilder builder) { Value = value; Builder = builder; } } /// <summary> /// Create a new instance of a test case /// </summary> /// <param name="sutXml"></param> /// <param name="ctrXml"></param> /// <returns></returns> public IEnumerable<string> Instantiate(PredefinedMembers value, string cultureName) { if (!Enum.IsDefined(typeof(PredefinedMembers), value)) throw new ArgumentOutOfRangeException(); if (string.IsNullOrEmpty(cultureName)) throw new ArgumentNullException("cultureName"); var culture = new CultureInfo(cultureName); IPredefinedMembersBuilder builder = null; //Look for registration ... var registration = registrations.FirstOrDefault(reg => reg.Value == value); if (registration == null) throw new ArgumentException(string.Format("'{0}' has no builder registred.", Enum.GetName(typeof(PredefinedMembers), value))); //Get Builder and initiate it builder = registration.Builder; builder.Setup(culture); //Build builder.Build(); var list = builder.GetResult(); return list; } } }
Add a very basic class to allow placing buttons on-screen.
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.UI { /// <summary> /// Represents a rectangular button that can be clicked in a game. /// </summary> public class Button : DrawableGameComponent { public SpriteFont Font { get; set; } public Color TextColor { get; set; } public string Text { get; set; } public Rectangle Bounds { get; set; } public Color BackgroundColor { get; set; } private Texture2D ButtonTexture; private SpriteBatch spriteBatch; public Button(Game game, SpriteFont font, Color textColor, string text, Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game) { this.Font = font; this.TextColor = textColor; this.Text = text; this.Bounds = bounds; this.BackgroundColor = backgroundColor; this.spriteBatch = spriteBatch; } public override void Initialize() { this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1); this.ButtonTexture.SetData<Color>(new Color[] { Color.White }); base.Initialize(); } public override void Draw(GameTime gameTime) { // Draw the button background. spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor); // Draw the button text. spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor); base.Draw(gameTime); } } }
Reset the Application Entry Point
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using RapID.ClassLibrary; namespace RapID.Auth { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // callback& app var callback = DecodeUrlString(args[0]); var app = Crypt.Decrypt(Crypt.Decrypt(Crypt.Decrypt(args[1]))); var waitFrm = new Wait(callback, app); Application.Run(waitFrm); } /* * (C) 2015 @ogi from StackOverflow * Original Post: http://stackoverflow.com/questions/1405048/how-do-i-decode-a-url-parameter-using-c */ private static string DecodeUrlString(string url) { string newUrl; while ((newUrl = Uri.UnescapeDataString(url)) != url) url = newUrl; return newUrl; } } }
Add tool to update all dependencies
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.Tools.Common; using System; using System.IO; namespace Google.Cloud.Tools.ReleaseManager { public sealed class UpdateDependenciesCommand : CommandBase { public UpdateDependenciesCommand() : base("update-dependencies", "Updates dependencies for all APIs") { } protected override void ExecuteImpl(string[] args) { var catalog = ApiCatalog.Load(); var apiNames = catalog.CreateIdHashSet(); foreach (var api in catalog.Apis) { GenerateProjectsCommand.UpdateDependencies(catalog, api); var layout = DirectoryLayout.ForApi(api.Id); GenerateProjectsCommand.GenerateMetadataFile(layout.SourceDirectory, api); GenerateProjectsCommand.GenerateProjects(layout.SourceDirectory, api, apiNames); } string formatted = catalog.FormatJson(); File.WriteAllText(ApiCatalog.CatalogPath, formatted); Console.WriteLine("Updated apis.json"); } } }
Add empty report for web part performance analysis
using KenticoInspector.Core; using KenticoInspector.Core.Constants; using KenticoInspector.Core.Models; using System; using System.Collections.Generic; namespace KenticoInspector.Reports.WebPartPerformanceAnalysis { class Report : IReport { public string Codename => nameof(WebPartPerformanceAnalysis); public IList<Version> CompatibleVersions => new List<Version> { new Version("10.0"), new Version("11.0") }; public IList<Version> IncompatibleVersions => new List<Version>(); public string LongDescription => @"<p>Displays list of web parts where 'columns' property is not specified.</p> <p>Web parts without specified 'columns' property must load all field from the database.</p> <p>By specifying this property, you can significantly lower the data transmission from database to the server and improve the load times.</p> <p>For more information, <a href=""https://docs.kentico.com/k12sp/configuring-kentico/optimizing-performance-of-portal-engine-sites/loading-data-efficiently"">see documentation</a>."; public string Name => "Web Part Performance Analysis"; public string ShortDescription => "Shows potential optimization opportunities."; public IList<string> Tags => new List<string> { ReportTags.PortalEngine, ReportTags.Performance, ReportTags.WebParts, }; public ReportResults GetResults(Guid InstanceGuid) { throw new NotImplementedException(); } } }
Add unit test for SYSTEM_LANGUAGE SCPI command
using SCPI.System; using System.Text; using Xunit; namespace SCPI.Tests.System { public class SYSTEM_LANGUAGE_Tests { [Theory] [InlineData("ENGL")] [InlineData("GERM")] public void LanguageIsSetToProperty(string expected) { // Arrange var cmd = new SYSTEM_LANGUAGE(); // Act var result = cmd.Parse(Encoding.ASCII.GetBytes($"{expected}\n")); // Assert Assert.Equal(expected, cmd.Language); } } }
Add player test for osu! ruleset
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestCaseOsuPlayer : Game.Tests.Visual.TestCasePlayer { public TestCaseOsuPlayer() : base(new OsuRuleset()) { } } }
Add tests covering score preparation flow
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Scoring; using osu.Game.Screens.Ranking; namespace osu.Game.Tests.Visual.Gameplay { public class TestScenePlayerScorePreparation : OsuPlayerTestScene { protected override bool AllowFail => false; protected new PreparingPlayer Player => (PreparingPlayer)base.Player; [SetUpSteps] public override void SetUpSteps() { base.SetUpSteps(); // Ensure track has actually running before attempting to seek AddUntilStep("wait for track to start running", () => Beatmap.Value.Track.IsRunning); } [Test] public void TestPreparationOnResults() { AddUntilStep("wait for preparation", () => Player.PreparationCompleted); } [Test] public void TestPreparationOnExit() { AddStep("exit", () => Player.Exit()); AddUntilStep("wait for preparation", () => Player.PreparationCompleted); } protected override TestPlayer CreatePlayer(Ruleset ruleset) => new PreparingPlayer(); public class PreparingPlayer : TestPlayer { public bool PreparationCompleted { get; private set; } public bool ResultsCreated { get; private set; } public PreparingPlayer() : base(true, true) { } protected override ResultsScreen CreateResults(ScoreInfo score) { var results = base.CreateResults(score); ResultsCreated = true; return results; } protected override Task PrepareScoreForResultsAsync(Score score) { PreparationCompleted = true; return base.PrepareScoreForResultsAsync(score); } } } }
Hide 'vsgd' graphic devie function from Environment window
using System; using System.Threading.Tasks; using Microsoft.R.Host.Client; namespace Microsoft.VisualStudio.R.Package.Repl.Session { public static class RSessionEvaluationCommands { public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) { return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n"); } public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) { return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n"); } public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) { return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n"); } public static Task<REvaluationResult> GetGlobalEnvironmentVariables(this IRSessionEvaluation evaluation) { return evaluation.EvaluateNonReentrantAsync($".rtvs.datainspect.env_vars(.GlobalEnv)\n"); } public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) { var script = @" vsgd <- function() { .External('C_vsgd', 5, 5) } options(device='vsgd') "; return evaluation.EvaluateAsync(script, reentrant: false); } private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) { return evaluation.EvaluateAsync(FormattableString.Invariant(commandText), reentrant: false); } } }
using System; using System.Threading.Tasks; using Microsoft.R.Host.Client; namespace Microsoft.VisualStudio.R.Package.Repl.Session { public static class RSessionEvaluationCommands { public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) { return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n"); } public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) { return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n"); } public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) { return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n"); } public static Task<REvaluationResult> GetGlobalEnvironmentVariables(this IRSessionEvaluation evaluation) { return evaluation.EvaluateNonReentrantAsync($".rtvs.datainspect.env_vars(.GlobalEnv)\n"); } public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) { var script = @" .rtvs.vsgd <- function() { .External('C_vsgd', 5, 5) } options(device='.rtvs.vsgd') "; return evaluation.EvaluateAsync(script, reentrant: false); } private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) { return evaluation.EvaluateAsync(FormattableString.Invariant(commandText), reentrant: false); } } }
Disable rename for Unity event handlers
using System.Collections.Generic; using JetBrains.Application; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Refactorings.Specific.Rename; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Psi; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.Refactorings.Rename { [ShellFeaturePart] public class UnityEventTargetAtomicRenameFactory : IAtomicRenameFactory { public bool IsApplicable(IDeclaredElement declaredElement) { if (declaredElement is IMethod method) { var eventHandlerCache = declaredElement.GetSolution().GetComponent<UnityEventHandlerReferenceCache>(); return eventHandlerCache.IsEventHandler(method); } return false; } // Disable rename completely for Unity event handlers public RenameAvailabilityCheckResult CheckRenameAvailability(IDeclaredElement element) { if (IsApplicable(element)) return RenameAvailabilityCheckResult.CanNotBeRenamed; return RenameAvailabilityCheckResult.CanBeRenamed; } public IEnumerable<AtomicRenameBase> CreateAtomicRenames(IDeclaredElement declaredElement, string newName, bool doNotAddBindingConflicts) { return EmptyList<AtomicRenameBase>.Instance; } } }
Add helper to check TCP port status.
using System.Net; using System.Net.Sockets; namespace PSql.Tests { internal static class TcpPort { public static bool IsListening(ushort port) { const int TimeoutMs = 1000; try { using var client = new TcpClient(); return client.ConnectAsync(IPAddress.Loopback, port).Wait(TimeoutMs) && client.Connected; } catch (SocketException) { return false; } } } }
Add endpoints to view jobs
using BatteryCommander.Web.Models; using FluentScheduler; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Controllers.API { public class JobsController : ApiController { public JobsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public IEnumerable<Schedule> List() { return JobManager.AllSchedules; } [HttpPost("{name}")] public IActionResult Post(String name) { JobManager.GetSchedule(name)?.Execute(); return Ok(); } } }
Add unit test to check for duplicate log types
using System; using System.Linq; using Content.Shared.Administration.Logs; using NUnit.Framework; namespace Content.Tests.Shared.Administration.Logs; [TestFixture] public class LogTypeTests { [Test] public void Unique() { var types = Enum.GetValues<LogType>(); var duplicates = types .GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToArray(); Assert.That(duplicates.Length, Is.Zero, $"{nameof(LogType)} has duplicate values for: " + string.Join(", ", duplicates)); } }
Add content conveter to show DataGrid
using System; using System.Globalization; using System.Windows.Data; namespace Mastoon.Conveters { public class DataGridContentConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml((string) value); return doc.DocumentNode.InnerText; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException(); } }
Add class for exponential distribution
using System; using System.Collections.Generic; namespace Blaze.Randomization.Lab { public static class ExponentialDistribution { static readonly Random random = new Random(); public static double Next(double mean) => -mean * Math.Log(1 - random.NextDouble()); } }
Add alternate empty entries remover
#!/usr/bin/csexec -r:System.Windows.Forms.dll using System; using System.IO; using System.Resources; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; public static class Program { public static void Main (string [] args) { try { var script = new EmptyEntriesRemover () { PackageName = args [1], CultureCode = args [2].Replace ("_", "-") }; script.Run (); } catch (Exception ex) { Console.WriteLine (ex.Message); } } } internal class EmptyEntriesRemover { #region Parameters public string CultureCode { get; set; } public string PackageName { get; set; } #endregion public void Run () { try { // get translation files Directory.SetCurrentDirectory (Path.Combine (PackageName, CultureCode)); var files = Directory.GetFiles (".", string.Format ("*.{0}.resx", CultureCode), SearchOption.AllDirectories); foreach (var file in files) { RemoveEmptyEntries (file); } } catch (Exception ex) { throw ex; } } private void RemoveEmptyEntries (string file) { try { var newFile = file + ".out"; using (ResXResourceWriter resxWriter = new ResXResourceWriter (newFile)) { var resxReader = new ResXResourceReader(file); resxReader.UseResXDataNodes = true; foreach (DictionaryEntry entry in resxReader) { var node = (ResXDataNode) entry.Value; if (!string.IsNullOrEmpty (node.GetValue((ITypeResolutionService) null).ToString ())) { resxWriter.AddResource (node); } } resxReader.Close (); } if (new FileInfo (newFile).Length < new FileInfo (file).Length) { File.Delete (file); File.Move (newFile, file); } else { File.Delete (newFile); } } catch (Exception ex) { Console.WriteLine ("{0}: {1}", file, ex.Message); } } }
Add manual test to validate python cache
// ------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.Identity.Client.AppConfig; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Identity.Test.Unit.CacheTests { [TestClass] public class ManualCacheLoadTest { // This is a manual run test to be able to load a cache file from python manually until we get automated tests across the other languages/platforms. [TestMethod] [Ignore] public async Task TestLoadCacheAsync() { // string authority = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/"; string authority = "https://login.microsoftonline.com/organizations/"; string scope = "https://graph.microsoft.com/.default"; string clientId = "b945c513-3946-4ecd-b179-6499803a2167"; string accountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb"; string filePathCacheBin = @"C:\Users\mark\Downloads\python_msal_cache.bin"; var pca = PublicClientApplicationBuilder.Create(clientId).WithAuthority(authority).Build(); pca.UserTokenCache.DeserializeMsalV3(File.ReadAllBytes(filePathCacheBin)); var account = await pca.GetAccountAsync(accountId).ConfigureAwait(false); var result = await pca.AcquireTokenSilent(new List<string> { scope }, account).ExecuteAsync().ConfigureAwait(false); Console.WriteLine(); } } }
Add Acceptor for an Enumerable of objects.
using System; using System.Collections.Generic; namespace CBojar.Acceptors { public class EnumerableAcceptor<T> : IAcceptor<T> { protected IEnumerable<T> _value; public EnumerableAcceptor(IEnumerable<T> value) { _value = value; } public IAcceptor<T> Accept(Action<T> visitor) { foreach(T member in _value) { new Acceptor<T>(member).Accept(visitor); } return this; } public IAcceptor<T> Accept<U>(Action<U> visitor) where U : T { foreach(T member in _value) { new Acceptor<T>(member).Accept(visitor); } return this; } public IAcceptor<T> Accept<U, V>(Action<V> visitor) where U : T, V { foreach(T member in _value) { new Acceptor<T>(member).Accept<U, V>(visitor); } return this; } } }
Add helper methods for numeric
using System; namespace DeclarativeSql.Internals { /// <summary> /// Provides helper methods for numeric. /// </summary> internal static class NumericHelper { /// <summary> /// Gets the number of digits of the specified value. /// </summary> /// <param name="value"></param> /// <returns></returns> /// <remarks>http://smdn.jp/programming/netfx/tips/get_number_of_digits/</remarks> public static byte GetDigit(int value) { //--- 0 is special if (value == 0) return 1; //--- If smaller value, dividing by 10 is faster if (value <= 10000) { byte digit = 1; while (value >= 10) { value /= 10; digit++; } return digit; } //--- When the number is large, calculates from the logarithm return (byte)(unchecked((byte)Math.Log10(value)) + 1); } } }
Add a behaviour to drop nodes if all the current connected nodes are behind.
using System; using System.Linq; using NBitcoin; using NBitcoin.Protocol; using NBitcoin.Protocol.Behaviors; namespace Stratis.Bitcoin.Connection { /// <summary> /// If the light wallet is only connected to nodes behind /// it cannot progress progress to the tip to get the full balance /// this behaviour will make sure place is kept for nodes higher then /// current tip. /// </summary> public class DropNodesBehaviour : NodeBehavior { private readonly ConcurrentChain chain; private readonly IConnectionManager connection; private readonly decimal dropTrashold; public DropNodesBehaviour(ConcurrentChain chain, IConnectionManager connectionManager) { this.chain = chain; this.connection = connectionManager; // 80% of current max connections, the last 20% will only // connect to nodes ahead of the current best chain this.dropTrashold = 0.8M; } private void AttachedNodeOnMessageReceived(Node node, IncomingMessage message) { message.Message.IfPayloadIs<VersionPayload>(version => { var nodeGroup = this.connection.DiscoveredNodeGroup ?? this.connection.ConnectNodeGroup; // find how much 20% max nodes var connectAbove = Math.Round(nodeGroup.MaximumNodeConnection * this.dropTrashold, MidpointRounding.ToEven); if (connectAbove < this.connection.ConnectedNodes.Count()) if (version.StartHeight < this.chain.Height) this.AttachedNode.DisconnectAsync($"Node too far behind height = {version.StartHeight}"); }); } protected override void AttachCore() { this.AttachedNode.MessageReceived += this.AttachedNodeOnMessageReceived; } protected override void DetachCore() { this.AttachedNode.MessageReceived -= this.AttachedNodeOnMessageReceived; } public override object Clone() { return new DropNodesBehaviour(this.chain, this.connection); } } }
Disable concurrency for storage integration tests
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)]
Add an instance provider for Colore
// --------------------------------------------------------------------------------------- // <copyright file="ColoreProvider.cs" company="Corale"> // Copyright © 2015-2017 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore { using Corale.Colore.Api; using Corale.Colore.Implementations; using Corale.Colore.Native; using JetBrains.Annotations; /// <summary> /// Provides helper methods to instantiate a new <see cref="IChroma" /> instance. /// </summary> [PublicAPI] public static class ColoreProvider { /// <summary> /// Creates a new <see cref="IChroma" /> instance using the native Razer Chroma SDK. /// </summary> /// <returns>A new instance of <see cref="IChroma" />.</returns> public static IChroma CreateNative() { return Create(new NativeApi()); } /// <summary> /// Creates a new <see cref="IChroma" /> instance using the specified API instance. /// </summary> /// <param name="api">The API instance to use to route SDK calls.</param> /// <returns>A new instance of <see cref="IChroma" />.</returns> public static IChroma Create(IChromaApi api) { return new Chroma(api); } } }
Add missing Contract helper function file
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; namespace DotNetFrontEnd.Contracts { public static class ContractExtensions { [Pure] public static bool Implies(this bool antecedent, bool consequent) { Contract.Ensures(Contract.Result<bool>() == (!antecedent || consequent)); return !antecedent || consequent; } [Pure] public static bool OneOf<T>(this T x, T first, params T[] rest) { Contract.Requires(x != null); Contract.Requires(rest != null); Contract.Ensures(Contract.Result<bool>() == (x.Equals(first) || Contract.Exists(rest, e => x.Equals(e)))); return x.Equals(first) || rest.Any(e => x.Equals(e)); } // The type parameter K is inferred automatically from type of dictionary [Pure, System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public static bool SetEquals<K,V>(this Dictionary<K, V>.KeyCollection keys, ISet<K> set) { Contract.Requires(keys != null); Contract.Requires(set != null); Contract.Ensures(Contract.Result<bool>() == Contract.ForAll(keys, k => set.Contains(k)) && Contract.ForAll(set, k => keys.Contains(k))); return keys.All(k => set.Contains(k)) && set.All(k => keys.Contains(k)); } } }
Fix add signature and comment
using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using BatteryCommander.Web.Queries; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Commands { public class AddSUTAComment : IRequest { [FromRoute] public int Id { get; set; } [FromForm] public string Comment { get; set; } private class Handler : AsyncRequestHandler<AddSUTAComment> { private readonly Database db; private readonly IMediator dispatcher; public Handler(Database db, IMediator dispatcher) { this.db = db; this.dispatcher = dispatcher; } protected override async Task Handle(AddSUTAComment request, CancellationToken cancellationToken) { var suta = await db .SUTAs .Where(s => s.Id == request.Id) .SingleOrDefaultAsync(cancellationToken); var current_user = await dispatcher.Send(new GetCurrentUser { }); suta.Events.Add(new SUTA.Event { Author = $"{current_user}", Message = request.Comment }); await db.SaveChangesAsync(cancellationToken); } } } }
Add tests for nullable keys
using System.Collections.Generic; using AutoMapper.EquivalencyExpression; using FluentAssertions; using Xunit; namespace AutoMapper.Collection { public class NullableIdTests { [Fact] public void Should_Work_With_Null_Id() { Mapper.Reset(); Mapper.Initialize(x => { x.AddCollectionMappers(); x.CreateMap<ThingWithStringIdDto, ThingWithStringId>().EqualityComparison((dto, entity) => dto.ID == entity.ID); }); var original = new List<ThingWithStringId> { new ThingWithStringId { ID = "1", Title = "test0" }, new ThingWithStringId { ID = "2", Title = "test2" }, }; var dtos = new List<ThingWithStringIdDto> { new ThingWithStringIdDto { ID = "1", Title = "test0" }, new ThingWithStringIdDto { ID = "2", Title = "test2" }, new ThingWithStringIdDto { Title = "test3" } }; Mapper.Map(dtos, original); original.Should().HaveSameCount(dtos); } public class ThingWithStringId { public string ID { get; set; } public string Title { get; set; } public override string ToString() { return Title; } } public class ThingWithStringIdDto { public string ID { get; set; } public string Title { get; set; } } } }
Update flusher to have defaults
using System.Data; namespace ZocMonLib { public interface IRecordFlush { /// <summary> /// Flush all data accumulated thus far. /// </summary> void FlushAll(); /// <summary> /// Flush data for the lowest reduce resolution for the given configuration. /// (The rest is only written on Reduce.) /// </summary> /// <param name="configName"></param> /// <param name="conn"></param> void Flush(string configName, IDbConnection conn); } }
using System.Data; namespace ZocMonLib { public interface IRecordFlush { /// <summary> /// Flush all data accumulated thus far. /// </summary> void FlushAll(); /// <summary> /// Flush data for the lowest reduce resolution for the given configuration. /// (The rest is only written on Reduce.) /// </summary> /// <param name="configName"></param> /// <param name="conn"></param> void Flush(string configName, IDbConnection conn = null); } }
Add missing file to samples
@page Test <div class="row"> <div class="col-md-3"> <h2>RazorPages Test</h2> <ul> <li>This file should give you a quick view of a Mvc Raor Page in action.</li> </ul> </div> </div>
Make a working copy of an PCB design
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 2014-04-24 // Autor // // Make copy of job and open it in temporary path. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { string pathForWorkingODB = Path.GetTempPath() + "\\example\\WorkingJob_diehl"; parent.SaveJob(pathForWorkingODB, false); if (!parent.LoadODBJob(pathForWorkingODB)) MessageBox.Show("Can't create a temporary working copy of ODB-Data.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); else MessageBox.Show("Workingcopy is loaded.", "Finish", MessageBoxButtons.OK, MessageBoxIcon.None); } } }
Update to avoid an execption if there are no jobs and therefore no jobs folder.
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Web; using dashing.net.common; namespace dashing.net.App_Start { public class JobConfig { public static void RegisterJobs() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(HttpContext.Current.Server.MapPath("~/Jobs/"))); catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); var container = new CompositionContainer(catalog); container.ComposeParts(); var exports = container.GetExportedValues<IJob>(); foreach (var job in exports) { Jobs.Add(job); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Web; using dashing.net.common; namespace dashing.net.App_Start { using System.IO; public class JobConfig { public static void RegisterJobs() { var jobsPath = HttpContext.Current.Server.MapPath("~/Jobs/"); if (!Directory.Exists(jobsPath)) { return; } var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(jobsPath)); catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); var container = new CompositionContainer(catalog); container.ComposeParts(); var exports = container.GetExportedValues<IJob>(); foreach (var job in exports) { Jobs.Add(job); } } } }
Add tests class for NoteSubparser
using FluentAssertions; using NFugue.Parser; using NFugue.Theory; using Staccato.Subparsers.NoteSubparser; using Xunit; namespace Staccato.Tests.Subparsers { public class NoteSubparserTests : SubparserTestBase<NoteSubparser> { [Fact] public void Should_match_simple_notes() { subparser.Matches("A").Should().BeTrue(); subparser.Matches("R").Should().BeTrue(); subparser.Matches("S").Should().BeFalse(); subparser.Matches("Cb").Should().BeTrue(); subparser.Matches("B#").Should().BeTrue(); subparser.Matches("bC").Should().BeFalse(); subparser.Matches("A%").Should().BeTrue(); subparser.Matches("Ebb").Should().BeTrue(); subparser.Matches("A##").Should().BeTrue(); subparser.Matches("A#b").Should().BeTrue(); subparser.Matches("I&&").Should().BeFalse(); subparser.Matches("Eb5").Should().BeTrue(); } [Fact] public void Should_raise_note_parsed_on_simple_notes() { ParseWithSubparser("C"); VerifyEventRaised(nameof(Parser.NoteParsed)) .WithArgs<NoteEventArgs>(e => e.Note.Equals(new Note(60) { IsOctaveExplicitlySet = false })); } } }
Change file name to reflect new class name
using DotNetNuke.Security.Roles; using System; namespace Dnn.PersonaBar.Prompt.Models { public class RoleModel : RoleModelBase { public string Description; public DateTime CreatedDate; public int CreatedBy; #region Constructors public RoleModel() { } public RoleModel(RoleInfo role) { CreatedDate = role.CreatedOnDate; CreatedBy = role.CreatedByUserID; Description = role.Description; } #endregion #region Command Links public string __CreatedBy { get { return $"get-user {CreatedBy}"; } } #endregion } }
Add labelled number box control
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Graphics.UserInterface; namespace osu.Game.Graphics.UserInterfaceV2 { public class LabelledNumberBox : LabelledTextBox { protected override OsuTextBox CreateTextBox() => new OsuNumberBox(); } }
Add skeleton for Autocomplete Responses.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WundergroundClient.Autocomplete { class AutocompleteResponse { public Boolean IsSuccessful { get; private set; } public IList<AutocompleteResponseObject> Results; } }
Move initialization code into the original lock to avoid a race condition.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Csla.Security { /// <summary> /// Maintains a list of all object level /// authorization roles. /// </summary> internal class ObjectAuthorizationRules { private static Dictionary<Type, RolesForType> _managers = new Dictionary<Type, RolesForType>(); internal static RolesForType GetRoles(Type objectType) { RolesForType result = null; if (!_managers.TryGetValue(objectType, out result)) { bool createdManager = false; lock (_managers) { if (!_managers.TryGetValue(objectType, out result)) { result = new RolesForType(); _managers.Add(objectType, result); createdManager = true; } } // if necessary, create instance to trigger // static constructor if (createdManager) { lock (objectType) { var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; MethodInfo method = objectType.GetMethod( "AddObjectAuthorizationRules", flags); if (method != null) method.Invoke(null, null); } } } return result; } public static bool RulesExistFor(Type objectType) { return _managers.ContainsKey(objectType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Csla.Security { /// <summary> /// Maintains a list of all object level /// authorization roles. /// </summary> internal class ObjectAuthorizationRules { private static Dictionary<Type, RolesForType> _managers = new Dictionary<Type, RolesForType>(); internal static RolesForType GetRoles(Type objectType) { RolesForType result = null; if (!_managers.TryGetValue(objectType, out result)) { lock (_managers) { if (!_managers.TryGetValue(objectType, out result)) { result = new RolesForType(); _managers.Add(objectType, result); // invoke method to add auth roles var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; MethodInfo method = objectType.GetMethod( "AddObjectAuthorizationRules", flags); if (method != null) method.Invoke(null, null); } } } return result; } public static bool RulesExistFor(Type objectType) { return _managers.ContainsKey(objectType); } } }
Add the soft focus editor to the repository.
/* * Editors/SoftFocus.cs * * Copyright 2007 Novell Inc. * * Author * Larry Ewing <lewing@novell.com> * * See COPYING for license information. * */ using Gtk; using System; namespace FSpot.Editors { public class SoftFocus : EffectEditor { Widgets.SoftFocus soft; Scale scale; bool double_buffer; public SoftFocus (PhotoImageView view) : base (view) { } protected override void SetView (PhotoImageView value) { if (view != null) view.DoubleBuffered = double_buffer; base.SetView (value); if (value == null) return; soft = new Widgets.SoftFocus (info); effect = (IEffect) soft; double_buffer = (view.WidgetFlags & WidgetFlags.DoubleBuffered) == WidgetFlags.DoubleBuffered; view.DoubleBuffered = true; } protected override Widget CreateControls () { VBox box = new VBox (); scale = new HScale (0, 45, 1); scale.Value = 0.0; scale.ValueChanged += HandleValueChanged; scale.WidthRequest = 250; box.PackStart (scale); HBox actions = new HBox (); Button apply = new Button ("Apply"); apply.Clicked += HandleApply; actions.PackStart (apply); Button cancel = new Button ("Cancel"); cancel.Clicked += HandleCancel; actions.PackStart (cancel); box.PackStart (actions); return box; } private void HandleCancel (object sender, EventArgs args) { Close (); } private void HandleApply (object sender, EventArgs args) { Console.WriteLine ("wake up man, this is never going to work ;)"); Close (); } private void HandleValueChanged (object sender, EventArgs args) { soft.Radius = ((Scale)sender).Value; if (view != null) view.QueueDraw (); } } }
Enable limitation control for rendering
 namespace SharpexGL.Framework.Game.Timing { public enum RenderMode { /// <summary> /// Limits the render call to a fixed fps amount. /// </summary> Limited, /// <summary> /// No limitations. /// </summary> Unlimited } }
Add a few base backend tests
using Mofichan.Backend; using Mofichan.Core.Interfaces; using Moq; using Serilog; using Shouldly; using Xunit; namespace Mofichan.Tests { public class BackendSpec { private class MockBackend : BaseBackend { public bool OnStartCalled { get; private set; } public string RoomId { get; private set; } public string UserId { get; private set; } public MockBackend(ILogger logger) : base(logger) { } public override void Start() { this.OnStartCalled = true; } protected override IRoom GetRoomById(string roomId) { this.RoomId = roomId; return Mock.Of<IRoom>(); } protected override IUser GetUserById(string userId) { this.UserId = userId; return Mock.Of<IUser>(); } } [Fact] public void Backend_Should_Try_To_Get_Room_Id_When_Join_Requested() { // GIVEN a mock backend. var backend = new MockBackend(Mock.Of<ILogger>()); backend.RoomId.ShouldBeNull(); // GIVEN a room ID. var roomId = "foo"; // WHEN I try to join a room using the room ID. backend.Join(roomId); // THEN the backend should have attempted to find a room using that identifier. backend.RoomId.ShouldBe(roomId); } [Fact] public void Backend_Should_Try_To_Get_Room_Id_When_Leave_Requested() { // GIVEN a mock backend. var backend = new MockBackend(Mock.Of<ILogger>()); backend.RoomId.ShouldBeNull(); // GIVEN a room ID. var roomId = "foo"; // WHEN I try to leave a room using the room ID. backend.Leave(roomId); // THEN the backend should have attempted to find a room using that identifier. backend.RoomId.ShouldBe(roomId); } } }
Store and provide full original partition key
using System; using System.Linq; using Microsoft.WindowsAzure.Storage.Table; namespace Streamstone { public class Partition { static readonly string[] separator = {"|"}; public readonly CloudTable Table; public readonly string PartitionKey; public readonly string RowKeyPrefix; public Partition(CloudTable table, string key) { Requires.NotNull(table, "table"); Requires.NotNullOrEmpty(key, "key"); var parts = key.Split(separator, 2, StringSplitOptions.RemoveEmptyEntries); Table = table; PartitionKey = parts[0]; RowKeyPrefix = parts.Length > 1 ? parts[1] + separator[0] : ""; } public string StreamRowKey() { return string.Format("{0}{1}", RowKeyPrefix, StreamEntity.FixedRowKey); } public string EventVersionRowKey(int version) { return string.Format("{0}{1}{2:d10}", RowKeyPrefix, EventEntity.RowKeyPrefix, version); } public string EventIdRowKey(string id) { return string.Format("{0}{1}{2}", RowKeyPrefix, EventIdEntity.RowKeyPrefix, id); } public override string ToString() { return string.Format("{0}.{1}{2}", Table.Name, PartitionKey, RowKeyPrefix); } } }
using System; using System.Linq; using Microsoft.WindowsAzure.Storage.Table; namespace Streamstone { public class Partition { static readonly string[] separator = {"|"}; public readonly CloudTable Table; public readonly string PartitionKey; public readonly string RowKeyPrefix; public readonly string Key; public Partition(CloudTable table, string key) { Requires.NotNull(table, "table"); Requires.NotNullOrEmpty(key, "key"); var parts = key.Split(separator, 2, StringSplitOptions.RemoveEmptyEntries); Table = table; PartitionKey = parts[0]; RowKeyPrefix = parts.Length > 1 ? parts[1] + separator[0] : ""; Key = key; } public string StreamRowKey() { return string.Format("{0}{1}", RowKeyPrefix, StreamEntity.FixedRowKey); } public string EventVersionRowKey(int version) { return string.Format("{0}{1}{2:d10}", RowKeyPrefix, EventEntity.RowKeyPrefix, version); } public string EventIdRowKey(string id) { return string.Format("{0}{1}{2}", RowKeyPrefix, EventIdEntity.RowKeyPrefix, id); } public override string ToString() { return string.Format("{0}.{1}", Table.Name, Key); } } }
Add some very basic tests for Link
using System; using System.Collections.Generic; using Seq.Api.Model; using Xunit; namespace Seq.Api.Tests { public class LinkTests { [Fact] public void ALinkWithNoParametersIsLiteral() { const string uri = "https://example.com"; var link = new Link(uri); var constructed = link.GetUri(); Assert.Equal(uri, constructed); } [Fact] public void AParameterizedLinkCanBeConstructed() { const string template = "https://example.com/{name}"; var link = new Link(template); var constructed = link.GetUri(new Dictionary<string, object> {["name"] = "test"}); Assert.Equal("https://example.com/test", constructed); } [Fact] public void InvalidParametersAreDetected() { const string template = "https://example.com"; var link = new Link(template); Assert.Throws<ArgumentException>(() => link.GetUri(new Dictionary<string, object> {["name"] = "test"})); } } }
Remove attributes of an ODB++ job
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 27.05.2015 // Autor Gruber Fabio // // Clear Attributes of components. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { IMatrix m = parent.GetMatrix(); IStep step = parent.GetCurrentStep(); foreach (ICMPObject comp in step.GetAllCMPObjects()) { Dictionary<string ,string> attv = comp.GetComponentAttributeDictionary(); foreach (string att in attv.Keys) { comp.RemoveAttribute(att); } } parent.UpdateView(); } } }
Add basic test coverage for solid border colour
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneBorderColour : FrameworkTestScene { [Test] public void TestSolidBorder() { Container container = null; AddStep("create box with solid border", () => Child = container = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200), Masking = true, BorderThickness = 5, BorderColour = Colour4.Red, Child = new Box { RelativeSizeAxes = Axes.Both, Colour = Colour4.Blue } }); AddSliderStep("change corner radius", 0, 100, 0, radius => { if (container != null) container.CornerRadius = radius; }); AddSliderStep("change corner exponent", 0.1f, 10, 1, exponent => { if (container != null) container.CornerExponent = exponent; }); } } }
Add a script to draw all spring joints connected to an object, for debugging.
// The MIT License (MIT) // // Copyright (c) 2015 Jabavu W. Adams. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // DebugDrawSpringJoints.cs using UnityEngine; using System.Collections; public class DebugDrawSpringJoints : MonoBehaviour { public Color stretchedColor = Color.red; public Color compressedColor = Color.green; public Color neutralColor = Color.cyan; void Update() { foreach (SpringJoint spring in GetComponents<SpringJoint>()) { Vector3 p0 = transform.TransformPoint(spring.anchor); Vector3 p1 = spring.connectedBody.transform.TransformPoint( spring.connectedAnchor); // Draw the spring with varying colours depending on whether // it's stretched, compressed, or neither. float currentLength = Vector3.Distance(p0, p1); Color springColor; if (currentLength > spring.maxDistance) { springColor = stretchedColor; } else if (currentLength < spring.minDistance) { springColor = compressedColor; } else { springColor = neutralColor; } Debug.DrawLine(p0, p1, springColor); } } }
Add LegacyGlobalOptionsWorkspaceService for OmniSharp EA
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using System.Threading.Tasks; using System.Threading; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Options { /// <summary> /// Enables legacy APIs to access global options from workspace. /// </summary> [ExportWorkspaceService(typeof(ILegacyGlobalOptionsWorkspaceService)), Shared] internal sealed class OmnisharpLegacyGlobalOptionsWorkspaceService : ILegacyGlobalOptionsWorkspaceService { private readonly CleanCodeGenerationOptionsProvider _provider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmnisharpLegacyGlobalOptionsWorkspaceService() { _provider = new OmniSharpCleanCodeGenerationOptionsProvider(); } public bool RazorUseTabs => LineFormattingOptions.Default.UseTabs; public int RazorTabSize => LineFormattingOptions.Default.TabSize; public CleanCodeGenerationOptionsProvider CleanCodeGenerationOptionsProvider => _provider; /// TODO: remove. https://github.com/dotnet/roslyn/issues/57283 public bool InlineHintsOptionsDisplayAllOverride { get => false; set { } } public bool GenerateOverrides { get => true; set { } } public bool GetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language) => false; public void SetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language, bool value) { } public bool GetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language) => false; public void SetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language, bool value) { } public bool GetGenerateConstructorFromMembersOptionsAddNullChecks(string language) => false; public void SetGenerateConstructorFromMembersOptionsAddNullChecks(string language, bool value) { } internal sealed class OmniSharpCleanCodeGenerationOptionsProvider : AbstractCleanCodeGenerationOptionsProvider { public override ValueTask<CleanCodeGenerationOptions> GetCleanCodeGenerationOptionsAsync(HostLanguageServices languageServices, CancellationToken cancellationToken) { return new ValueTask<CleanCodeGenerationOptions>(CleanCodeGenerationOptions.GetDefault(languageServices)); } } } }
Define interface for a command in setup or cleanup
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Etl { public interface IEtlRunCommand: IEtl { } }
Fix on previous commit ...
using System; using System.Collections.Generic; using System.Text; using System.Windows.Media; using System.Windows.Shapes; using System.Windows; using System.Windows.Input; namespace FreeSCADA.Schema.Manipulators { class GeometryHilightManipulator:BaseManipulator { Rectangle hilightRect = new Rectangle(); public GeometryHilightManipulator(UIElement element, SchemaDocument doc) : base(element, doc) { VisualBrush brush = new VisualBrush(AdornedElement); //hilightRect.Opacity = 0.5; // hilightRect.Fill = brush; visualChildren.Add(hilightRect); } protected override Size ArrangeOverride(Size finalSize) { Rect r=AdornedElement.TransformToVisual(this).TransformBounds(new Rect(new Point(0, 0), AdornedElement.DesiredSize)); r.X = 0; r.Y = 0; hilightRect.Arrange(r); return finalSize; } } }
Add failing GL disposal stress test
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { [Ignore("This test needs a game host to be useful.")] public class TestSceneStressGLDisposal : FrameworkTestScene { private FillFlowContainer fillFlow; protected override double TimePerAction => 0.001; [SetUp] public void SetUp() => Schedule(() => { Add(fillFlow = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Full }); }); [Test] public void TestAddRemoveDrawable() { AddRepeatStep("add/remove drawables", () => { for (int i = 0; i < 50; i++) { fillFlow.Add(new Box { Size = new Vector2(5) }); if (fillFlow.Count > 100) { fillFlow.Remove(fillFlow.First()); } } }, 100000); } } }
Add unit test for getuserrole
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Http; using Moq; using NUnit.Framework; using NUnit.Framework.Internal; using SFA.DAS.CommitmentsV2.Api.Authentication; using SFA.DAS.CommitmentsV2.Authentication; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.UnitTests.Authentication { [TestFixture] public class AuthenticationServiceTests { [TestCase(Originator.Employer, Role.Employer)] [TestCase(Originator.Provider, Role.Provider)] [TestCase(Originator.Unknown, Role.Provider, Role.Employer)] [TestCase(Originator.Unknown, "someOtherRole")] public void GetUserRole(Originator expectedRole, params string[] roles) { // arrange Mock<IHttpContextAccessor> httpContextAccessorMock = new Mock<IHttpContextAccessor>(); Mock<HttpContext> httpContextMock = new Mock<HttpContext>(); Mock<ClaimsPrincipal> userMock = new Mock<ClaimsPrincipal>(); httpContextAccessorMock .Setup(hca => hca.HttpContext) .Returns(httpContextMock.Object); httpContextMock .Setup(hcm => hcm.User) .Returns(userMock.Object); userMock .Setup(um => um.IsInRole(It.IsAny<string>())) .Returns<string>(roles.Contains); var sut = new AuthenticationService(httpContextAccessorMock.Object); // act var actualRole = sut.GetUserRole(); // assert Assert.AreEqual(expectedRole, actualRole); } } }
Add test scene for arc bounding box computation
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Lines; using osu.Framework.Graphics.Shapes; using osu.Framework.Utils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneCircularArcBoundingBox : FrameworkTestScene { private SmoothPath path; private Box boundingBox; private readonly BindableList<Vector2> controlPoints = new BindableList<Vector2>(); private float startAngle, endAngle, radius; [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { boundingBox = new Box { RelativeSizeAxes = Axes.None, Colour = Color4.Red }, path = new SmoothPath { Colour = Color4.White, PathRadius = 2 } }; AddSliderStep("starting angle", 0, 360, 90, angle => { startAngle = angle; generateControlPoints(); }); AddSliderStep("end angle", 0, 360, 270, angle => { endAngle = angle; generateControlPoints(); }); AddSliderStep("radius", 1, 300, 150, radius => { this.radius = radius; generateControlPoints(); }); } protected override void LoadComplete() { controlPoints.BindCollectionChanged((_, __) => { var copy = controlPoints.ToArray(); if (copy.Length != 3) return; path.Vertices = PathApproximator.ApproximateCircularArc(copy); var bounds = PathApproximator.CircularArcBoundingBox(copy); boundingBox.Size = bounds.Size; }); } private void generateControlPoints() { float midpoint = (startAngle + endAngle) / 2; Vector2 polarToCartesian(float r, float theta) => new Vector2( r * MathF.Cos(MathHelper.DegreesToRadians(theta)), r * MathF.Sin(MathHelper.DegreesToRadians(theta))); controlPoints.Clear(); controlPoints.AddRange(new[] { polarToCartesian(radius, startAngle), polarToCartesian(radius, midpoint), polarToCartesian(radius, endAngle) }); } } }
Add extension methods to determine whether an actor is an ancestor or descendant of another actor.
using Akka.Actor; using System; namespace AKDK.Utilities { /// <summary> /// Extension methods for Akka types. /// </summary> public static class AkkaExtensions { /// <summary> /// Determine whether another actor is a descendent of the actor. /// </summary> /// <param name="actor"> /// The actor. /// </param> /// <param name="otherActor"> /// The other actor. /// </param> /// <returns> /// <c>true</c>, if <paramref name="otherActor"/> is a descendant of <paramref name="actor"/>; otherwise, <c>false</c>. /// </returns> public static bool IsDescendantOf(this IActorRef actor, IActorRef otherActor) { if (actor == null) throw new ArgumentNullException(nameof(actor)); if (otherActor == null) throw new ArgumentNullException(nameof(otherActor)); ActorPath parentPath = actor.Path; ActorPath otherParentPath = otherActor.Path.Parent; ActorPath rootPath = otherActor.Path.Root; while (otherParentPath != rootPath) { if (otherParentPath == parentPath) return true; otherParentPath = otherParentPath.Parent; } return false; } /// <summary> /// Determine whether another actor is an ancestor of the actor. /// </summary> /// <param name="actor"> /// The actor. /// </param> /// <param name="otherActor"> /// The other actor. /// </param> /// <returns> /// <c>true</c>, if <paramref name="otherActor"/> is an ancestor of <paramref name="actor"/>; otherwise, <c>false</c>. /// </returns> public static bool IsAncestorOf(this IActorRef actor, IActorRef otherActor) { if (actor == null) throw new ArgumentNullException(nameof(actor)); if (otherActor == null) throw new ArgumentNullException(nameof(otherActor)); return otherActor.IsDescendantOf(actor); } } }
Add test coverage of PlayingUsers tracking
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using Humanizer; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Online.Multiplayer; using osu.Game.Tests.Visual.Multiplayer; using osu.Game.Users; namespace osu.Game.Tests.NonVisual.Multiplayer { [HeadlessTest] public class StatefulMultiplayerClientTest : MultiplayerTestScene { [Test] public void TestPlayingUserTracking() { int id = 2000; AddRepeatStep("add some users", () => Client.AddUser(new User { Id = id++ }), 5); checkPlayingUserCount(0); changeState(3, MultiplayerUserState.WaitingForLoad); checkPlayingUserCount(3); changeState(3, MultiplayerUserState.Playing); checkPlayingUserCount(3); changeState(3, MultiplayerUserState.Results); checkPlayingUserCount(0); changeState(6, MultiplayerUserState.WaitingForLoad); checkPlayingUserCount(6); AddStep("another user left", () => Client.RemoveUser(Client.Room?.Users.Last().User)); checkPlayingUserCount(5); AddStep("leave room", () => Client.LeaveRoom()); checkPlayingUserCount(0); } private void checkPlayingUserCount(int expectedCount) => AddAssert($"{"user".ToQuantity(expectedCount)} playing", () => Client.PlayingUsers.Count == expectedCount); private void changeState(int userCount, MultiplayerUserState state) => AddStep($"{"user".ToQuantity(userCount)} in {state}", () => { for (int i = 0; i < userCount; ++i) { var userId = Client.Room?.Users[i].UserID ?? throw new AssertionException("Room cannot be null!"); Client.ChangeUserState(userId, state); } }); } }
Move serialization end event firing into a pipeline processor
using System.Linq; using Sitecore.Configuration; using Sitecore.Data; using Sitecore.Data.Serialization; using Sitecore.Diagnostics; using Sitecore.Eventing; using Unicorn.Predicates; namespace Unicorn.Pipelines.UnicornSyncEnd { public class SendSerializationCompleteEvent : IUnicornSyncEndProcessor { public void Process(UnicornSyncEndPipelineArgs args) { var databases = args.SyncedConfigurations.SelectMany(config => config.Resolve<IPredicate>().GetRootPaths()) .Select(path => path.Database) .Distinct(); foreach (var database in databases) { DeserializationComplete(database); } } protected virtual void DeserializationComplete(string databaseName) { Assert.ArgumentNotNullOrEmpty(databaseName, "databaseName"); EventManager.RaiseEvent(new SerializationFinishedEvent()); Database database = Factory.GetDatabase(databaseName, false); if (database != null) { database.RemoteEvents.Queue.QueueEvent(new SerializationFinishedEvent()); } } } }
Add back obsoleted mapping to improve backwards compatibility
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Framework.Graphics { [Obsolete("Use BlendingParameters statics instead")] // can be removed 20200220 public static class BlendingMode { /// <summary> /// Inherits from parent. /// </summary> [Obsolete("Use BlendingParameters statics instead")] public static BlendingParameters Inherit => BlendingParameters.Inherit; /// <summary> /// Mixes with existing colour by a factor of the colour's alpha. /// </summary> [Obsolete("Use BlendingParameters statics instead")] public static BlendingParameters Mixture => BlendingParameters.Mixture; /// <summary> /// Purely additive (by a factor of the colour's alpha) blending. /// </summary> [Obsolete("Use BlendingParameters statics instead")] public static BlendingParameters Additive => BlendingParameters.Additive; /// <summary> /// No alpha blending whatsoever. /// </summary> [Obsolete("Use BlendingParameters statics instead")] public static BlendingParameters None => BlendingParameters.None; } }
Rename UpdateHUD lives to DisplayLives.
using UnityEngine; using UnityEngine.UI; using System.Collections; using DG.Tweening; using Matcha.Game.Tweens; public class UpdateHUDLives : BaseBehaviour { public Sprite threeLives; public Sprite twoLives; public Sprite oneLife; private Image lives; private float timeToFade = 2f; void Start() { lives = gameObject.GetComponent<Image>(); lives.sprite = threeLives; lives.DOKill(); MTween.FadeOutImage(lives, 0, 0); MTween.FadeInImage(lives, HUD_FADE_IN_AFTER, timeToFade); } // EVENT LISTENERS void OnEnable() { Messenger.AddListener<string, Collider2D>( "player dead", OnPlayerDead); } void OnDestroy() { Messenger.RemoveListener<string, Collider2D>( "player dead", OnPlayerDead); } void OnPlayerDead(string methodOfDeath, Collider2D coll) { MTween.FadeOutImage(lives, HUD_FADE_OUT_AFTER, timeToFade); } }
Add more tests for surface
using Microsoft.VisualStudio.TestTools.UnitTesting; using SadRogue.Primitives; namespace SadConsole.Tests { public partial class CellSurface { [TestMethod] public void Glyph_SetForeground() { var surface1 = new SadConsole.CellSurface(20, 20); surface1.FillWithRandomGarbage(); Color cellForeground = surface1[0].Foreground; Color newForeground = Color.Blue.GetRandomColor(new System.Random()); Assert.IsFalse(newForeground == surface1[0, 0].Foreground); surface1.SetForeground(0, 0, newForeground); Assert.IsTrue(newForeground == surface1[0, 0].Foreground); } [TestMethod] public void Glyph_SetBackground() { var surface1 = new SadConsole.CellSurface(20, 20); surface1.FillWithRandomGarbage(); Color newBackground = Color.Blue.GetRandomColor(new System.Random()); Assert.IsFalse(newBackground == surface1[0, 0].Background); surface1.SetBackground(0, 0, newBackground); Assert.IsTrue(newBackground == surface1[0, 0].Background); } [TestMethod] public void Glyph_SetGlyph() { var surface1 = new SadConsole.CellSurface(20, 20); surface1.FillWithRandomGarbage(); int newGlyph = new System.Random().Next(0, 256); Assert.IsFalse(newGlyph == surface1[0, 0].Glyph); surface1.SetGlyph(0, 0, newGlyph); Assert.IsTrue(newGlyph == surface1[0, 0].Glyph); } [TestMethod] public void Glyph_SetMirror() { var surface1 = new SadConsole.CellSurface(20, 20); surface1.FillWithRandomGarbage(); Mirror cellMirror = surface1[0].Mirror; Mirror newMirror = cellMirror switch { Mirror.None => Mirror.Horizontal, Mirror.Horizontal => Mirror.Vertical, _ => Mirror.None }; Assert.IsFalse(newMirror == surface1[0, 0].Mirror); surface1.SetMirror(0, 0, newMirror); Assert.IsTrue(newMirror == surface1[0, 0].Mirror); } } }
Set default db for existing raven instances
using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; if (string.IsNullOrEmpty(GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey))) { ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; } else { ravenStore = new DocumentStore { Url = GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey) }; } ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; if (string.IsNullOrEmpty(GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey))) { ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; } else { ravenStore = new DocumentStore { DefaultDatabase = "qed", Url = GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey) }; } ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
Add sample to illustrate lack of ordering of type compilation, for a future branch.
using System; using System.Collections.Generic; using System.Text; using VCSFramework; namespace Samples { public static class Foo { [AlwaysInline] public static void Run() { } } // TODO - This is not supported yet. public static class TypeCompilationOrderTesting { private static byte TestByte; // AlwaysInline exacerbates the issue since since it requires the method to already be compiled by the // time it finds any call sites for it. public static void Main() { Foo.Run(); TestByte++; Bar.Run(); } } public static class Bar { [AlwaysInline] public static void Run() { } } }
Add new bip 157 p2p message cfilter
using System; using System.Collections.Generic; namespace NBitcoin.Protocol { /// <summary> /// Represents the p2p message payload used for sharing a block's compact filter. /// </summary> [Payload("cfilter")] public class CompactFilterPayload : Payload { private byte _FilterType = (byte)FilterType.Basic; private byte[] _FilterBytes; private uint256 _BlockHash = new uint256(); /// <summary> /// Gets the Filter type for which headers are requested. /// </summary> public FilterType FilterType { get => (FilterType)_FilterType; internal set => _FilterType = (byte)value; } /// <summary> /// Gets the serialized compact filter for this block. /// </summary> public byte[] FilterBytes => _FilterBytes; /// <summary> /// Gets block hash of the Bitcoin block for which the filter is being returned. /// </summary> public uint256 BlockHash => _BlockHash; public CompactFilterPayload(FilterType filterType, uint256 blockhash, byte[] filterBytes) { if (filterType != FilterType.Basic) throw new ArgumentException($"'{filterType}' is not a valid value.", nameof(filterType)); if (blockhash == null) throw new ArgumentNullException(nameof(blockhash)); if (filterBytes == null) throw new ArgumentNullException(nameof(filterBytes)); FilterType = filterType; _BlockHash = blockhash; _FilterBytes = filterBytes; } public CompactFilterPayload() { } public new void ReadWrite(BitcoinStream stream) { stream.ReadWrite(ref _FilterType); stream.ReadWrite(ref _BlockHash); stream.ReadWrite(ref _FilterBytes); } } }
Define enumeration for supported list of predefined members
using System; using System.Linq; using System.Xml.Serialization; namespace NBi.Core.Members { public enum PredefinedMembers { [XmlEnum(Name = "weekdays")] DaysOfWeek = 1, [XmlEnum(Name = "months")] MonthsOfYear = 2 } }
Add support for 8 bit raw bitmap
using System; using System.Drawing; using System.IO; using OpenKh.Imaging; namespace OpenKh.Kh2 { public class RawBitmap : IImageRead { private const int PaletteCount = 256; private const int BitsPerColor = 32; private readonly byte[] _data; private readonly byte[] _clut; private RawBitmap(Stream stream, int width, int height) { Size = new Size(width, height); var reader = new BinaryReader(stream); _data = reader.ReadBytes(width * height); _clut = reader.ReadBytes(PaletteCount * BitsPerColor / 8); } public Size Size { get; } public PixelFormat PixelFormat => PixelFormat.Indexed8; public byte[] GetClut() { var data = new byte[256 * 4]; for (var i = 0; i < 256; i++) { var srcIndex = Ps2.Repl(i); data[i * 4 + 0] = _clut[srcIndex * 4 + 0]; data[i * 4 + 1] = _clut[srcIndex * 4 + 1]; data[i * 4 + 2] = _clut[srcIndex * 4 + 2]; data[i * 4 + 3] = Ps2.FromPs2Alpha(_clut[srcIndex * 4 + 3]); } return data; } public byte[] GetData() => _data; public static RawBitmap Read(Stream stream, int width, int height) => new RawBitmap(stream, width, height); } }
Add needed generated file for Live Preview.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Pinta { public partial class ProgressDialog { private Gtk.Label label; private Gtk.ProgressBar progress_bar; private Gtk.Button buttonCancel; protected virtual void Build() { Stetic.Gui.Initialize(this); // Widget Pinta.ProgressDialog this.Name = "Pinta.ProgressDialog"; this.WindowPosition = ((Gtk.WindowPosition)(4)); // Internal child Pinta.ProgressDialog.VBox Gtk.VBox w1 = this.VBox; w1.Name = "dialog1_VBox"; w1.BorderWidth = ((uint)(2)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.label = new Gtk.Label(); this.label.Name = "label"; this.label.LabelProp = Mono.Unix.Catalog.GetString("label2"); w1.Add(this.label); Gtk.Box.BoxChild w2 = ((Gtk.Box.BoxChild)(w1[this.label])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child dialog1_VBox.Gtk.Box+BoxChild this.progress_bar = new Gtk.ProgressBar(); this.progress_bar.Name = "progress_bar"; w1.Add(this.progress_bar); Gtk.Box.BoxChild w3 = ((Gtk.Box.BoxChild)(w1[this.progress_bar])); w3.Position = 1; w3.Expand = false; w3.Fill = false; // Internal child Pinta.ProgressDialog.ActionArea Gtk.HButtonBox w4 = this.ActionArea; w4.Name = "dialog1_ActionArea"; w4.Spacing = 10; w4.BorderWidth = ((uint)(5)); w4.LayoutStyle = ((Gtk.ButtonBoxStyle)(4)); // Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild this.buttonCancel = new Gtk.Button(); this.buttonCancel.CanDefault = true; this.buttonCancel.CanFocus = true; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseStock = true; this.buttonCancel.UseUnderline = true; this.buttonCancel.Label = "gtk-cancel"; this.AddActionWidget(this.buttonCancel, -6); Gtk.ButtonBox.ButtonBoxChild w5 = ((Gtk.ButtonBox.ButtonBoxChild)(w4[this.buttonCancel])); w5.Expand = false; w5.Fill = false; if ((this.Child != null)) { this.Child.ShowAll(); } this.DefaultWidth = 400; this.DefaultHeight = 114; this.Show(); } } }
Add model class for realm skin
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Testing; using osu.Game.Database; using osu.Game.Extensions; using osu.Game.IO; using osu.Game.Skinning; using Realms; #nullable enable namespace osu.Game.Models { [ExcludeFromDynamicCompile] [MapTo("Skin")] public class RealmSkin : RealmObject, IHasRealmFiles, IEquatable<RealmSkin>, IHasGuidPrimaryKey, ISoftDelete { public Guid ID { get; set; } public string Name { get; set; } = string.Empty; public string Creator { get; set; } = string.Empty; public string Hash { get; set; } = string.Empty; public string InstantiationInfo { get; set; } = string.Empty; public virtual Skin CreateInstance(IStorageResourceProvider resources) { var type = string.IsNullOrEmpty(InstantiationInfo) // handle the case of skins imported before InstantiationInfo was added. ? typeof(LegacySkin) : Type.GetType(InstantiationInfo).AsNonNull(); return (Skin)Activator.CreateInstance(type, this, resources); } public IList<RealmNamedFileUsage> Files { get; } = null!; public bool DeletePending { get; set; } public static RealmSkin Default { get; } = new RealmSkin { Name = "osu! (triangles)", Creator = "team osu!", InstantiationInfo = typeof(DefaultSkin).GetInvariantInstantiationInfo() }; public bool Equals(RealmSkin? other) { if (ReferenceEquals(this, other)) return true; if (other == null) return false; return ID == other.ID; } public override string ToString() { string author = string.IsNullOrEmpty(Creator) ? string.Empty : $"({Creator})"; return $"{Name} {author}".Trim(); } } }
Use name that doesn't clash with unit-testing classes
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ExpressionToCodeLib { /// <summary> /// Intended to be used as a static import; i.e. via "using static ExpressionToCodeLib.ExpressionAssertions;" /// </summary> public static class ExpressionAssertions { /// <summary> /// Evaluates an assertion and throws an exception the assertion it returns false or throws an exception. /// The exception includes the code of the assertion annotated with runtime values for its sub-expressions. /// </summary> public static void Assert(Expression<Func<bool>> assertion, string msg = null) { ExpressionToCodeConfiguration.CurrentConfiguration.Assert(assertion, msg); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ExpressionToCodeLib { /// <summary> /// Intended to be used as a static import; i.e. via "using static ExpressionToCodeLib.ExpressionAssertions;" /// </summary> public static class ExpressionAssertions { /// <summary> /// Evaluates an assertion and throws an exception the assertion it returns false or throws an exception. /// The exception includes the code of the assertion annotated with runtime values for its sub-expressions. /// </summary> public static void Expect(Expression<Func<bool>> assertion, string msg = null) { ExpressionToCodeConfiguration.CurrentConfiguration.Assert(assertion, msg); } } }
Add a controller for authorized user s.t. they can retrieve their info and update password.
using A2BBCommon; using A2BBCommon.Models; using A2BBIdentityServer.DTO; using A2BBIdentityServer.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using A2BBCommon.DTO; namespace A2BBIdentityServer.Controllers { /// <summary> /// Controller to deal with user. /// </summary> [Produces("application/json")] [Route("api/me")] [Authorize] public class MeController : Controller { #region Private fields /// <summary> /// The ASP NET identity user manager. /// </summary> private readonly UserManager<User> _userManager; /// <summary> /// The ASP NET identity sign in manager. /// </summary> private readonly SignInManager<User> _signInManager; /// <summary> /// The logger. /// </summary> private readonly ILogger _logger; #endregion #region Public methods /// <summary> /// Create a new instance of this class. /// </summary> /// <param name="userManager">The DI user manager for ASP NET identity.</param> /// <param name="signInManager">The DI sign in manager for ASP NET identity.</param> /// <param name="loggerFactory">The DI logger factory.</param> public MeController(UserManager<User> userManager, SignInManager<User> signInManager, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _logger = loggerFactory.CreateLogger<AdminUsersController>(); } /// <summary> /// List all users. /// </summary> /// <returns></returns> [HttpGet] public User GetInfo() { return _userManager.Users.FirstOrDefault(u => u.Id == User.Claims.FirstOrDefault(c => c.Type == "sub").Value); } /// <summary> /// Update an user password. /// </summary> /// <param name="req">The request parameters.</param> /// <returns>The response with status.</returns> [HttpPut] public async Task<ResponseWrapper<IdentityResult>> UpdateUserPass([FromBody] ChangePassRequestDTO req) { User user = _userManager.Users.FirstOrDefault(u => u.Id == User.Claims.FirstOrDefault(c => c.Type == "sub").Value); IdentityResult res = await _userManager.ChangePasswordAsync(user, req.OldPassword, req.NewPassword); if (!res.Succeeded) { return new ResponseWrapper<IdentityResult>(res, Constants.RestReturn.ERR_USER_UPDATE); } return new ResponseWrapper<IdentityResult>(res); } #endregion } }
Add THE IDOLM@STER CINDERELLA GIRLS ANIMATION PROJECTシリーズCD発売記念イベント
@using System.Text @using CsQuery @RadioWhip.Feedify( "http://columbia.jp/idolmaster/cinderellaapevent/", "THE IDOLM@STER CINDERELLA GIRLS ANIMATION PROJECTシリーズCD発売記念イベント", (content, cq) => { return cq["#newsContent h3"] .Select(x => x.Cq()) .Select(x => { var id = ""; var idE = x.PrevUntil("[id],h3").Prev(); if (idE.Count() != 0 && idE[0].NodeName != "H3") { id = idE.Attr("id"); } var lastE = x.NextUntil("h3").Last()[0]; var node = x[0]; var html = new StringBuilder(); while (node.NextSibling != null) { html.Append(node.NodeType == NodeType.ELEMENT_NODE ? node.OuterHTML : node.NodeValue); if (node.NextSibling == lastE) { break; } node = node.NextSibling; } return new RadioWhip.Entry { Title = x.Text(), Url = "http://columbia.jp/idolmaster/cinderellaapevent/#" + id, Content = html.ToString(), }; }); })
Add custom project exception type.
// --------------------------------------------------------------------------------------- // <copyright file="ColoreException.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore { using System; using System.Runtime.Serialization; public class ColoreException : Exception { public ColoreException(string message = null, Exception innerException = null) : base(message, innerException) { } protected ColoreException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
Add missing file for 0188bf6b.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace ElasticSearch.Client { [JsonObject] public class MultiHit<T> where T : class { [JsonProperty("docs")] public IEnumerable<Hit<T>> Hits { get; internal set; } } }
Add ninject module for mvp
using System; using System.Linq; using Ninject; using Ninject.Activation; using Ninject.Modules; using Ninject.Parameters; using WebFormsMvp; namespace ZobShop.Web.App_Start.NinjectModules { public class MvpNinjectModule : NinjectModule { private const string ViewConstructorArgumentName = "view"; public override void Load() { throw new System.NotImplementedException(); } private IPresenter GetPresenter(IContext context) { var parameters = context.Parameters.ToList(); var presenterType = (Type)parameters[0].GetValue(context, null); var view = (IView)parameters[1].GetValue(context, null); var constructorParameter = new ConstructorArgument(ViewConstructorArgumentName, view); var presenter = (IPresenter)context.Kernel.Get(presenterType, constructorParameter); return presenter; } } }
Revert "Revert "Privide equivalent to System.currentTimeMillis()""
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adaptive.Arp.Impl.Util { public class TimeUtils { private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private TimeUtils() { } public static long CurrentTimeMillis() { return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds; } } }
Add structure for path control points
using System; using osu.Framework.Bindables; using osu.Game.Rulesets.Objects.Types; using osuTK; namespace osu.Game.Rulesets.Objects { public class PathControlPoint : IEquatable<PathControlPoint> { public readonly Bindable<Vector2> Position = new Bindable<Vector2>(); public readonly Bindable<PathType?> Type = new Bindable<PathType?>(); public bool Equals(PathControlPoint other) => Position.Value == other.Position.Value && Type.Value == other.Type.Value; } }
Add new Author: Victor Silva
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class VictorSilva : IAmAMicrosoftMVP, IFilterMyBlogPosts { public string FirstName => "Victor"; public string LastName => "Silva"; public string ShortBioOrTagLine => ""; public string StateOrRegion => "Montevideo, Uruguay"; public string EmailAddress => "vmsilvamolina@hotmail.com"; public string TwitterHandle => "vmsilvamolina"; public string GitHubHandle => "vmsilvamolina"; public string GravatarHash => "f641e3c18a5af7afb0e78527f2ceaa99"; public GeoPosition Position => new GeoPosition(-34.908, -56.176); public Uri WebSite => new Uri("https://blog.victorsilva.com.uy"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://feeds.feedburner.com/vmsilvamolina"); } } public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
Add a realtime room manager
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Logging; using osu.Game.Online.Multiplayer; using osu.Game.Online.RealtimeMultiplayer; using osu.Game.Screens.Multi.Components; namespace osu.Game.Screens.Multi.RealtimeMultiplayer { public class RealtimeRoomManager : RoomManager { [Resolved] private StatefulMultiplayerClient multiplayerClient { get; set; } public override void CreateRoom(Room room, Action<Room> onSuccess = null, Action<string> onError = null) => base.CreateRoom(room, r => joinMultiplayerRoom(r, onSuccess), onError); public override void JoinRoom(Room room, Action<Room> onSuccess = null, Action<string> onError = null) => base.JoinRoom(room, r => joinMultiplayerRoom(r, onSuccess), onError); private void joinMultiplayerRoom(Room room, Action<Room> onSuccess = null) { Debug.Assert(room.RoomID.Value != null); var joinTask = multiplayerClient.JoinRoom(room); joinTask.ContinueWith(_ => onSuccess?.Invoke(room)); joinTask.ContinueWith(t => { PartRoom(); if (t.Exception != null) Logger.Error(t.Exception, "Failed to join multiplayer room."); }, TaskContinuationOptions.NotOnRanToCompletion); } protected override RoomPollingComponent[] CreatePollingComponents() => new RoomPollingComponent[] { new ListingPollingComponent() }; } }
Remove info that's now elsewhere.
/* DOESN'T WORK YET! 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("ExpressionToCodeLib")] [assembly: AssemblyDescription( @"Create readable C# assertions (or other code) from an expression tree; can annotate subexpressions with their runtime value. Integrates with xUnit.NET, NUnit and MSTest." )] [assembly: AssemblyProduct("ExpressionToCodeLib")] [assembly: AssemblyCompany("Eamon Nerbonne")] [assembly: AssemblyCopyright("Copyright © Eamon Nerbonne")] // 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("008ee713-7baa-491a-96f3-0a8ce3a473b1")] [assembly: AssemblyVersion("1.9.9")] */ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ExpressionToCodeTest")]
/* DOESN'T WORK YET! 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("ExpressionToCodeLib")] */ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ExpressionToCodeTest")]
Allow test assembly to access internals
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("ExpressionToCodeLib")] [assembly: AssemblyDescription( @"Create readable C# assertions (or other code) from an expression tree; can annotate subexpressions with their runtime value. Integrates with xUnit.NET, NUnit and MSTest." )] [assembly: AssemblyProduct("ExpressionToCodeLib")] [assembly: AssemblyCompany("Eamon Nerbonne")] [assembly: AssemblyCopyright("Copyright © Eamon Nerbonne")] // 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("008ee713-7baa-491a-96f3-0a8ce3a473b1")] [assembly: AssemblyVersion("1.9.9")]
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("ExpressionToCodeLib")] [assembly: AssemblyDescription( @"Create readable C# assertions (or other code) from an expression tree; can annotate subexpressions with their runtime value. Integrates with xUnit.NET, NUnit and MSTest." )] [assembly: AssemblyProduct("ExpressionToCodeLib")] [assembly: AssemblyCompany("Eamon Nerbonne")] [assembly: AssemblyCopyright("Copyright © Eamon Nerbonne")] // 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("008ee713-7baa-491a-96f3-0a8ce3a473b1")] [assembly: AssemblyVersion("1.9.9")] [assembly: InternalsVisibleTo("ExpressionToCodeTest")]
Implement extension method get max array element
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; namespace Microsoft.PowerShell.EditorServices.Utility { internal static class ObjectExtensions { /// <summary> /// Extension to evaluate an object's ToString() method in an exception safe way. This will /// extension method will not throw. /// </summary> /// <param name="obj">The object on which to call ToString()</param> /// <returns>The ToString() return value or a suitable error message is that throws.</returns> public static string SafeToString(this object obj) { string str; try { str = obj.ToString(); } catch (Exception ex) { str = $"<Error converting poperty value to string - {ex.Message}>"; } return str; } } }
// // 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.Linq; using System.Collections.Generic; using System.Management.Automation.Language; namespace Microsoft.PowerShell.EditorServices.Utility { internal static class ObjectExtensions { /// <summary> /// Extension to evaluate an object's ToString() method in an exception safe way. This will /// extension method will not throw. /// </summary> /// <param name="obj">The object on which to call ToString()</param> /// <returns>The ToString() return value or a suitable error message is that throws.</returns> public static string SafeToString(this object obj) { string str; try { str = obj.ToString(); } catch (Exception ex) { str = $"<Error converting poperty value to string - {ex.Message}>"; } return str; } public static T MaxElement<T>(this IEnumerable<T> elements, Func<T,T,int> comparer) where T:class { if (elements == null) { throw new ArgumentNullException(nameof(elements)); } if (comparer == null) { throw new ArgumentNullException(nameof(comparer)); } if (!elements.Any()) { return null; } var maxElement = elements.First(); foreach(var element in elements.Skip(1)) { if (element != null && comparer(element, maxElement) > 0) { maxElement = element; } } return maxElement; } } }
Add integration test for relative path
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using FluentAssertions; using NuGet.Test.Helpers; using Sleet.Test; using Xunit; namespace Sleet.Integration.Test { public class LocalFeedTests { [Fact] public async Task LocalFeed_RelativePath() { using (var target = new TestFolder()) using (var cache = new LocalCache()) { var baseUri = UriUtility.CreateUri("https://localhost:8080/testFeed/"); var log = new TestLogger(); var sleetConfig = TestUtility.CreateConfigWithLocal("local", "output", baseUri.AbsoluteUri); var sleetConfigPath = Path.Combine(target.Root, "sleet.config"); await JsonUtility.SaveJsonAsync(new FileInfo(sleetConfigPath), sleetConfig); var settings = LocalSettings.Load(sleetConfigPath); var fileSystem = FileSystemFactory.CreateFileSystem(settings, cache, "local") as PhysicalFileSystem; fileSystem.Should().NotBeNull(); fileSystem.LocalRoot.Should().Be(Path.Combine(target.Root, "output") + Path.DirectorySeparatorChar); } } } }
Add basic VirtualTrack retrieval test
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.IO.Stores; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioComponentTest { [Test] public void TestVirtualTrack() { var thread = new AudioThread(); var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources"); var manager = new AudioManager(thread, store, store); thread.Start(); var track = manager.Tracks.GetVirtual(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(0, track.CurrentTime); track.Start(); Task.Delay(50); Assert.Greater(track.CurrentTime, 0); track.Stop(); Assert.IsFalse(track.IsRunning); thread.Exit(); Task.Delay(500); Assert.IsFalse(thread.Exited); } } }
Add JS zone requirement to asmdef namespace
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Psi.JavaScript; namespace JetBrains.ReSharper.Plugins.Unity.Json { [ZoneMarker] public class ZoneMarker : IRequire<ILanguageJavaScriptZone> { } }
Add Beta to the version
using System; using System.Reflection; namespace Umbraco.Core.Configuration { public class UmbracoVersion { private static readonly Version Version = new Version(6, 0, 0); /// <summary> /// Gets the current version of Umbraco. /// Version class with the specified major, minor, build (Patch), and revision numbers. /// </summary> /// <remarks> /// CURRENT UMBRACO VERSION ID. /// </remarks> public static Version Current { get { return Version; } } /// <summary> /// Gets the version comment (like beta or RC). /// </summary> /// <value>The version comment.</value> public static string CurrentComment { get { return ""; } } // Get the version of the umbraco.dll by looking at a class in that dll // Had to do it like this due to medium trust issues, see: http://haacked.com/archive/2010/11/04/assembly-location-and-medium-trust.aspx public static string AssemblyVersion { get { return new AssemblyName(typeof(ActionsResolver).Assembly.FullName).Version.ToString(); } } } }
using System; using System.Reflection; namespace Umbraco.Core.Configuration { public class UmbracoVersion { private static readonly Version Version = new Version(6, 0, 0); /// <summary> /// Gets the current version of Umbraco. /// Version class with the specified major, minor, build (Patch), and revision numbers. /// </summary> /// <remarks> /// CURRENT UMBRACO VERSION ID. /// </remarks> public static Version Current { get { return Version; } } /// <summary> /// Gets the version comment (like beta or RC). /// </summary> /// <value>The version comment.</value> public static string CurrentComment { get { return "Beta"; } } // Get the version of the umbraco.dll by looking at a class in that dll // Had to do it like this due to medium trust issues, see: http://haacked.com/archive/2010/11/04/assembly-location-and-medium-trust.aspx public static string AssemblyVersion { get { return new AssemblyName(typeof(ActionsResolver).Assembly.FullName).Version.ToString(); } } } }
Add support for mediapicker3 in mappers.
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Services; using Umbraco.Extensions; using uSync.Core.Dependency; using static Umbraco.Cms.Core.Constants; namespace uSync.Core.Mapping.Mappers { public class MediaPicker3Mapper : SyncValueMapperBase, ISyncMapper { public MediaPicker3Mapper(IEntityService entityService) : base(entityService) { } public override string Name => "MediaPicker3 Mapper"; public override string[] Editors => new string[] { "Umbraco.MediaPicker3" }; public override string GetExportValue(object value, string editorAlias) => string.IsNullOrEmpty(value.ToString()) ? null : value.ToString(); public override IEnumerable<uSyncDependency> GetDependencies(object value, string editorAlias, DependencyFlags flags) { // validate string var stringValue = value?.ToString(); if (string.IsNullOrWhiteSpace(stringValue) || !stringValue.DetectIsJson()) return Enumerable.Empty<uSyncDependency>(); // convert to an array. var images = JsonConvert.DeserializeObject<JArray>(value.ToString()); if (images == null || !images.Any()) return Enumerable.Empty<uSyncDependency>(); var dependencies = new List<uSyncDependency>(); foreach (var image in images.Cast<JObject>()) { var key = GetGuidValue(image, "mediaKey"); if (key != Guid.Empty) { var udi = GuidUdi.Create(UdiEntityType.Media, key); dependencies.Add(CreateDependency(udi as GuidUdi, flags)); } } return dependencies; } private Guid GetGuidValue(JObject obj, string key) { if (obj != null && obj.ContainsKey(key)) { var attempt = obj[key].TryConvertTo<Guid>(); if (attempt.Success) return attempt.Result; } return Guid.Empty; } } }
Use correct element name for admins
using System.Xml.Linq; using Hacknet; using Pathfinder.Util; using Pathfinder.Util.XML; namespace Pathfinder.Administrator; public abstract class BaseAdministrator : Hacknet.Administrator { protected Computer computer; protected OS opSystem; public BaseAdministrator(Computer computer, OS opSystem) : base() { this.computer = computer; this.opSystem = opSystem; } public virtual void LoadFromXml(ElementInfo info) { base.ResetsPassword = info.Attributes.GetBool("resetPass"); base.IsSuper = info.Attributes.GetBool("isSuper"); XMLStorageAttribute.ReadFromElement(info, this); } public virtual XElement GetSaveElement() { return XMLStorageAttribute.WriteToElement(this); } }
using System.Xml.Linq; using Hacknet; using Pathfinder.Util; using Pathfinder.Util.XML; namespace Pathfinder.Administrator; public abstract class BaseAdministrator : Hacknet.Administrator, IXmlName { protected Computer computer; protected OS opSystem; public BaseAdministrator(Computer computer, OS opSystem) : base() { this.computer = computer; this.opSystem = opSystem; } public string XmlName => "admin"; public virtual void LoadFromXml(ElementInfo info) { base.ResetsPassword = info.Attributes.GetBool("resetPass"); base.IsSuper = info.Attributes.GetBool("isSuper"); XMLStorageAttribute.ReadFromElement(info, this); } public virtual XElement GetSaveElement() { return XMLStorageAttribute.WriteToElement(this); } }
Modify to work with new n-level undo behaviors.
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private AChildList _children; public AChildList ChildList { get { if (_children == null) { _children = new AChildList(); for (int count = 0; count < EditLevel; count++) ((Csla.Core.IUndoableObject)_children).CopyState(); } return _children; } } public AChildList GetChildList() { return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private AChildList _children; public AChildList ChildList { get { if (_children == null) { _children = new AChildList(); for (int count = 0; count < EditLevel; count++) ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel); } return _children; } } public AChildList GetChildList() { return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } }
Add basic tests for pipeline
using System; using System.Linq; using System.Threading.Tasks; using BulkWriter.Pipeline; using Xunit; namespace BulkWriter.Tests.Pipeline { public class EtlPipelineTests { private readonly string _connectionString = TestHelpers.ConnectionString; public class PipelineTestsMyTestClass { public int Id { get; set; } public string Name { get; set; } } [Fact] public async Task WritesToBulkWriter() { var tableName = TestHelpers.DropCreate(nameof(PipelineTestsMyTestClass)); using (var writer = new BulkWriter<PipelineTestsMyTestClass>(_connectionString)) { var items = Enumerable.Range(1, 1000).Select(i => new PipelineTestsMyTestClass { Id = i, Name = "Bob" }); var pipeline = EtlPipeline .StartWith(items) .WriteTo(writer); await pipeline.ExecuteAsync(); var count = (int)await TestHelpers.ExecuteScalar(_connectionString, $"SELECT COUNT(1) FROM {tableName}"); Assert.Equal(1000, count); } } [Fact] public async Task RunsToCompletionWhenAStepThrows() { var tableName = TestHelpers.DropCreate(nameof(PipelineTestsMyTestClass)); using (var writer = new BulkWriter<PipelineTestsMyTestClass>(_connectionString)) { var items = Enumerable.Range(1, 1000).Select(i => new PipelineTestsMyTestClass { Id = i, Name = "Bob" }); var pipeline = EtlPipeline .StartWith(items) .Project<PipelineTestsMyTestClass>(i => throw new Exception()) .WriteTo(writer); await pipeline.ExecuteAsync(); var count = (int)await TestHelpers.ExecuteScalar(_connectionString, $"SELECT COUNT(1) FROM {tableName}"); Assert.Equal(0, count); } } } }
Add test coverage ensuring unique acronyms
// 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.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] public class TestSceneNoConflictingModAcronyms : TestSceneAllRulesetPlayers { protected override void AddCheckSteps() { AddStep("Check all mod acronyms are unique", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<string> acronyms = mods.Select(m => m.Acronym); Assert.That(acronyms, Is.Unique); }); } } }
Remove third and fourth digits from version
using System.Reflection; // common assembly attributes [assembly: AssemblyDescription("Lean Engine is an open-source, plataform agnostic C# and Python algorithmic trading engine. " + "Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")] [assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")] [assembly: AssemblyCompany("QuantConnect Corporation")] [assembly: AssemblyVersion("2.4.0.1")] // Configuration used to build the assembly is by defaulting 'Debug'. // To create a package using a Release configuration, -properties Configuration=Release on the command line must be use. // source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens
using System.Reflection; // common assembly attributes [assembly: AssemblyDescription("Lean Engine is an open-source, plataform agnostic C# and Python algorithmic trading engine. " + "Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")] [assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")] [assembly: AssemblyCompany("QuantConnect Corporation")] [assembly: AssemblyVersion("2.4")] // Configuration used to build the assembly is by defaulting 'Debug'. // To create a package using a Release configuration, -properties Configuration=Release on the command line must be use. // source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens
Add tablet information class to ferry information from OTD
// 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 osuTK; namespace osu.Framework.Input.Handlers.Tablet { /// <summary> /// A class that carries the information we care about from the tablet provider. /// Note that we are note using the exposed classes from OTD due to conditional compilation pains. /// </summary> public class TabletInfo { /// <summary> /// The name of this tablet. /// </summary> public string Name { get; } /// <summary> /// The size (in millimetres) of the connected tablet's full area. /// </summary> public Vector2 Size { get; } public TabletInfo(string name, Vector2 size) { Size = size; Name = name; } } }
Add path element factory for selection access
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Pather.CSharp.PathElements { public class SelectionFactory : IPathElementFactory { private const string selectionIndicator = "[]"; public IPathElement Create(string path, out string newPath) { newPath = path.Remove(0, selectionIndicator.Length); return new SelectionAccess(); } public bool IsApplicable(string path) { return path.StartsWith(selectionIndicator); } } }
Print pairs with difference k
// http://careercup.com/question?id=5727804001878016 // // Given a sorted array of positive integers and a positive value // return all pairs which differ by k. using System; using System.Collections.Generic; using System.Linq; static class Program { static IEnumerable<Tuple<int, int>> Pairs(this int[] array, int k) { for (int low = 0, high = 1; low < high && high < array.Length;) { int diff = array[high] - array[low]; if (diff == k) { yield return Tuple.Create(array[low], array[high]); high++; } if (diff < k) { high++; } else { low++; } } } static void Main() { Console.WriteLine(String.Join(Environment.NewLine, new int[] {1, 2, 3, 5, 6, 8, 9, 11, 12, 13}. Pairs(3). Select(x => String.Format("First: {0} Second: {1}", x.Item1, x.Item2)))); } }
Add tests for Base64 encoding/decoding
namespace Easy.Common.Tests.Unit.BaseEncoding { using NUnit.Framework; using Shouldly; [TestFixture] public class Base64Tests { [TestCase] public void When_encoding() => Base64.Encode(new byte[] {1, 15, 30, 40, 0, 13, 10, 43}).ShouldBe("AQ8eKAANCis"); [TestCase] public void When_decoding() => Base64.Decode("AQ8eKAANCis").ShouldBe(new byte[] { 1, 15, 30, 40, 0, 13, 10, 43 }); } }
Fix - Corretto bug notifica delete chiamata in corso Add - Gestito GeneratoreCodiciRichieste nel Fake Json Chg - TitoTerreno modificato in List Chg - Stato modificato in String (Era int)
using System; using System.Collections.Generic; using System.Text; namespace SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso { interface IGetRichiesteAssistenza { } }
Add a switch test to cover Jit codegen.
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; class SwitchTest { const int Pass = 100; const int Fail = -1; public static int Main() { int sum =0; for(int i=2; i < 5; i++) { switch(i) { case 2: sum += i; break; case 3: sum += i; break; default: sum -= 5; break; } } return sum == 0 ? Pass : Fail; } }