Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add test scene for setup screen | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneSetupScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneSetupScreen()
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap());
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new SetupScreen();
}
}
}
| |
Add equality check test to ensure correct values | // 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;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class BeatmapSetInfoEqualityTest
{
[Test]
public void TestOnlineWithOnline()
{
var ourInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 123 };
var otherInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithDatabased()
{
var ourInfo = new BeatmapSetInfo { ID = 123 };
var otherInfo = new BeatmapSetInfo { ID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithOnline()
{
var ourInfo = new BeatmapSetInfo { ID = 123, OnlineBeatmapSetID = 12 };
var otherInfo = new BeatmapSetInfo { OnlineBeatmapSetID = 12 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestCheckNullID()
{
var ourInfo = new BeatmapSetInfo { Status = BeatmapSetOnlineStatus.Loved };
var otherInfo = new BeatmapSetInfo { Status = BeatmapSetOnlineStatus.Approved };
Assert.AreNotEqual(ourInfo, otherInfo);
}
}
}
| |
Add in byte array serializer | using Microsoft.ServiceFabric.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceFabric.Bond
{
public class ByteArrayStateSerializer : IStateSerializer<byte[]>
{
public byte[] Read(BinaryReader binaryReader)
{
var count = binaryReader.ReadInt32();
var bytes = binaryReader.ReadBytes(count);
return bytes;
}
public byte[] Read(byte[] baseValue, BinaryReader binaryReader) => Read(binaryReader);
public void Write(byte[] value, BinaryWriter binaryWriter)
{
binaryWriter.Write(value.Length);
binaryWriter.Write(value, 0, value.Length);
}
public void Write(byte[] baseValue, byte[] targetValue, BinaryWriter binaryWriter) =>
Write(targetValue, binaryWriter);
}
}
| |
Increase R version cap to 3.9 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.R.Actions.Utility {
public static class SupportedRVersionList {
// TODO: this probably needs configuration file
// or another dynamic source of supported versions.
public const int MinMajorVersion = 3;
public const int MinMinorVersion = 2;
public const int MaxMajorVersion = 3;
public const int MaxMinorVersion = 3;
public static readonly Version MinVersion = new Version(MinMajorVersion, MinMinorVersion);
public static readonly Version MaxVersion = new Version(MaxMajorVersion, MaxMinorVersion);
public static bool IsCompatibleVersion(Version v) {
var verMajorMinor = new Version(v.Major, v.Minor);
return verMajorMinor >= MinVersion && verMajorMinor <= MaxVersion;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.R.Actions.Utility {
public static class SupportedRVersionList {
// TODO: this probably needs configuration file
// or another dynamic source of supported versions.
public const int MinMajorVersion = 3;
public const int MinMinorVersion = 2;
public const int MaxMajorVersion = 3;
public const int MaxMinorVersion = 9;
public static readonly Version MinVersion = new Version(MinMajorVersion, MinMinorVersion);
public static readonly Version MaxVersion = new Version(MaxMajorVersion, MaxMinorVersion);
public static bool IsCompatibleVersion(Version v) {
var verMajorMinor = new Version(v.Major, v.Minor);
return verMajorMinor >= MinVersion && verMajorMinor <= MaxVersion;
}
}
}
|
Allow to specify which package to assert against | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NuGet;
namespace NuProj.Tests.Infrastructure
{
public static class Scenario
{
public static async Task<IPackage> RestoreAndBuildSinglePackage(string scenarioName, IDictionary<string, string> properties = null)
{
var packages = await RestoreAndBuildPackages(scenarioName, properties);
return packages.Single();
}
public static async Task<IReadOnlyCollection<IPackage>> RestoreAndBuildPackages(string scenarioName, IDictionary<string, string> properties = null)
{
var projectFullPath = Assets.GetScenarioSolutionPath(scenarioName);
var projectDirectory = Path.GetDirectoryName(projectFullPath);
await NuGetHelper.RestorePackagesAsync(projectDirectory);
var result = await MSBuild.RebuildAsync(projectFullPath, properties);
result.AssertSuccessfulBuild();
return NuPkg.GetPackages(projectDirectory);
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NuGet;
namespace NuProj.Tests.Infrastructure
{
public static class Scenario
{
public static async Task<IPackage> RestoreAndBuildSinglePackage(string scenarioName, string packageId = null, IDictionary<string, string> properties = null)
{
var packages = await RestoreAndBuildPackages(scenarioName, properties);
return packageId == null
? packages.Single()
: packages.Single(p => string.Equals(p.Id, packageId, StringComparison.OrdinalIgnoreCase));
}
public static async Task<IReadOnlyCollection<IPackage>> RestoreAndBuildPackages(string scenarioName, IDictionary<string, string> properties = null)
{
var projectFullPath = Assets.GetScenarioSolutionPath(scenarioName);
var projectDirectory = Path.GetDirectoryName(projectFullPath);
await NuGetHelper.RestorePackagesAsync(projectDirectory);
var result = await MSBuild.RebuildAsync(projectFullPath, properties);
result.AssertSuccessfulBuild();
return NuPkg.GetPackages(projectDirectory);
}
}
} |
Add view model factory interface | using ZobShop.ModelViewPresenter.Product.Details;
namespace ZobShop.ModelViewPresenter
{
public interface IViewModelFactory
{
ProductDetailsViewModel CreateProductDetailsViewModel(string name, string category, decimal price, double volume, string maker);
}
}
| |
Add [ThreadSafe] attribute so it can be used for documentation purpose (not just for bindings) | //
// ThreadSafe attribute
//
// Copyright 2012, Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
namespace MonoMac.ObjCRuntime {
public class ThreadSafeAttribute : Attribute {
public ThreadSafeAttribute ()
{
}
}
} | |
Add test for winforms converters. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.WinForms;
namespace Tests.WinFormsTests
{
class Converters : AgateApplication, IAgateTest
{
public string Name
{
get { return "Conversion Tests"; }
}
public string Category
{
get { return "WinForms"; }
}
public void Main(string[] args)
{
Run(args);
}
protected override void Initialize()
{
Surface surf = new Surface("attacke.png");
System.Drawing.Bitmap bmp = surf.ToBitmap();
bmp.Save("test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
}
}
| |
Add generator test for REPEAT | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oberon0.Generator.Msil.Tests.Statements
{
using System.IO;
using NUnit.Framework;
using Oberon0.Compiler;
using Oberon0.Compiler.Definitions;
[TestFixture]
public class StatementTests
{
[Test]
public void RepeatTest()
{
string source = @"MODULE Test;
VAR
i: INTEGER;
BEGIN
i := 1;
REPEAT
WriteInt(i);
WriteLn;
i := i+1;
UNTIL i > 5
END Test.";
Module m = Oberon0Compiler.CompileString(source);
CodeGenerator cg = new CodeGenerator(m);
cg.Generate();
StringBuilder sb = new StringBuilder();
using (StringWriter w = new StringWriter(sb))
{
cg.DumpCode(w);
}
var code = sb.ToString();
Assert.IsTrue(MsilTestHelper.CompileRunTest(code, null, out var outputData));
Assert.AreEqual("1\n2\n3\n4\n5\n", outputData.NlFix());
}
}
}
| |
Fix Windows file format issues | /*
Copyright © Iain McDonald 2010-2019
This file is part of Decider.
Unlike the Expression type which is wholly supported on its own, the MetaExpression relies
on the values of other supporting variables. Thus, if those variables change, the bounds
of the MetaExpression need to be re-evaluated.
*/
using System.Collections.Generic;
namespace Decider.Csp.BaseTypes
{
public interface IMetaExpression<T>
{
IList<IVariable<T>> Support { get; }
}
}
| |
Implement calculation of absolute position in the document text, given a line and column number. | using System;
using MSBuildProjectTools.LanguageServer.XmlParser;
namespace MSBuildProjectTools.LanguageServer.Utilities
{
/// <summary>
/// A quick-and-dirty calculator for text positions.
/// </summary>
/// <remarks>
/// This could easily be improved by also storing a character sub-total for each line.
/// </remarks>
public sealed class TextPositions
{
/// <summary>
/// The lengths of each line of the text.
/// </summary>
readonly int[] _lineLengths;
/// <summary>
/// Create a new <see cref="TextPositions"/> for the specified text.
/// </summary>
/// <param name="text">
/// The text.
/// </param>
public TextPositions(string text)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
string[] lines = text.Split(
separator: new string[] { Environment.NewLine },
options: StringSplitOptions.None
);
_lineLengths = new int[lines.Length];
for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
_lineLengths[lineIndex] = lines[lineIndex].Length + Environment.NewLine.Length;
}
/// <summary>
/// Convert a <see cref="Position"/> to an absolute position within the text.
/// </summary>
/// <param name="line">
/// The target line (1-based).
/// </param>
/// <param name="column">
/// The target column (1-based).
/// </param>
/// <returns>
/// The equivalent absolute position within the text.
/// </returns>
public int GetAbsolutePosition(Position position)
{
if (position == null)
throw new ArgumentNullException(nameof(position));
position = position.ToOneBased();
return GetAbsolutePosition(position.LineNumber, position.ColumnNumber);
}
/// <summary>
/// Convert line and column numbers to an absolute position within the text.
/// </summary>
/// <param name="line">
/// The target line (1-based).
/// </param>
/// <param name="column">
/// The target column (1-based).
/// </param>
/// <returns>
/// The equivalent absolute position within the text.
/// </returns>
public int GetAbsolutePosition(int line, int column)
{
// Indexes are 0-based.
int targetLine = line - 1;
int targetColumn = column - 1;
if (targetLine >= _lineLengths.Length)
throw new ArgumentOutOfRangeException(nameof(line), line, "Line is past the end of the text.");
if (targetColumn >= _lineLengths[targetLine])
throw new ArgumentOutOfRangeException(nameof(column), column, "Column is past the end of the line.");
if (targetLine == 0)
return targetColumn;
// Position up to preceding line.
int targetPosition = 0;
for (int lineIndex = 0; lineIndex < targetLine; lineIndex++)
targetPosition += _lineLengths[lineIndex];
// And the final line.
targetPosition += targetColumn;
return targetPosition;
}
}
}
| |
Add coverage for operation tracker with failing tests | // 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 NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Testing;
using osu.Game.Screens.OnlinePlay;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.NonVisual
{
[HeadlessTest]
public class OngoingOperationTrackerTest : OsuTestScene
{
private OngoingOperationTracker tracker;
private IBindable<bool> operationInProgress;
[SetUpSteps]
public void SetUp()
{
AddStep("create tracker", () => Child = tracker = new OngoingOperationTracker());
AddStep("bind to operation status", () => operationInProgress = tracker.InProgress.GetBoundCopy());
}
[Test]
public void TestOperationTracking()
{
IDisposable firstOperation = null;
IDisposable secondOperation = null;
AddStep("begin first operation", () => firstOperation = tracker.BeginOperation());
AddAssert("operation in progress", () => operationInProgress.Value);
AddStep("cannot start another operation",
() => Assert.Throws<InvalidOperationException>(() => tracker.BeginOperation()));
AddStep("end first operation", () => firstOperation.Dispose());
AddAssert("operation is ended", () => !operationInProgress.Value);
AddStep("start second operation", () => secondOperation = tracker.BeginOperation());
AddAssert("operation in progress", () => operationInProgress.Value);
AddStep("dispose first operation again", () => firstOperation.Dispose());
AddAssert("operation in progress", () => operationInProgress.Value);
AddStep("dispose second operation", () => secondOperation.Dispose());
AddAssert("operation is ended", () => !operationInProgress.Value);
}
[Test]
public void TestOperationDisposalAfterTracker()
{
IDisposable operation = null;
AddStep("begin operation", () => operation = tracker.BeginOperation());
AddStep("dispose tracker", () => tracker.Expire());
AddStep("end operation", () => operation.Dispose());
AddAssert("operation is ended", () => !operationInProgress.Value);
}
}
}
| |
Add static file options startup sample | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApp
{
/// <summary>
/// Startup configuration example with user defined static file options
/// To use this configuration, webpack static assets have to be built
/// with public path set to /public/:
/// unix: export PUBLIC_PATH=/public/ && npm run build
/// windows: set "PUBLIC_PATH=/public/" && npm run build
/// </summary>
public class StartupWithStaticFileOptions
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddWebpack(options =>
{
options.UseStaticFiles(opts => {
opts.RequestPath = "/public";
opts.OnPrepareResponse = responseContext =>
responseContext.Context.Response.Headers.Add(
key: "Cache-control",
value: "public,max-age=31536000"
);
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseWebpack();
app.UseMvcWithDefaultRoute();
}
}
}
| |
Update link to SharpaDoc on github | @*
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -------------------------------------------------------------------------------
// Override this template to modify the generated html footer for all body
// -------------------------------------------------------------------------------
*@
<div class="footer_copyright">@Param.Copyright</div><div class="footer_generated">Documentation generated by <a href="http://sharpdx.org/documentation/tools/sharpdoc" target="_blank">SharpDoc</a></div>
<div style="clear: both;"></div> | @*
// Copyright (c) 2010-2013 SharpDoc - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -------------------------------------------------------------------------------
// Override this template to modify the generated html footer for all body
// -------------------------------------------------------------------------------
*@
<div class="footer_copyright">@Param.Copyright</div><div class="footer_generated">Documentation generated by <a href="https://github.com/xoofx/SharpDoc" target="_blank">SharpDoc</a></div>
<div style="clear: both;"></div> |
Make sure async API tests are testing what we think they’re testing | // ***********************************************************************
// Copyright (c) 2018 Charlie Poole, Rob Prouse
//
// 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.
// ***********************************************************************
#if ASYNC
using System.Threading.Tasks;
namespace NUnit.Framework
{
// Make sure other tests are testing what we think they’re testing
public static class AsyncExecutionApiAdapterTests
{
[TestCaseSource(typeof(AsyncExecutionApiAdapter), nameof(AsyncExecutionApiAdapter.All))]
public static void ExecutesAsyncUserCode(AsyncExecutionApiAdapter adapter)
{
var didExecute = false;
adapter.Execute(async () =>
{
#if NET40
await TaskEx.Yield();
#else
await Task.Yield();
#endif
didExecute = true;
});
Assert.That(didExecute);
}
}
}
#endif
| |
Implement utlity for httprequest as string | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic
{
class HttpRequestor
{
public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input)
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = requestTask(input);
var response = httpClient.SendAsync(request);
var result = await response.Result.Content.ReadAsStringAsync();
return result;
}
}
}
| |
Add empty Startup configuration service implementation | namespace GeekLearning.Test.Integration.Environment
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
public class StartupConfigurationService : IStartupConfigurationService
{
public IServiceProvider ServiceProvider
{
get
{
throw new NotImplementedException();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { }
public void ConfigureEnvironment(IHostingEnvironment env) { }
public void ConfigureService(IServiceCollection services, IConfigurationRoot configuration) { }
public void RegisterExternalStartupConfigured(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
Add serviceable attribute to projects. | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
[assembly: AssemblyMetadata("Serviceable", "True")] | |
Support meta-data to define config relationship between classes | using System;
namespace Zyborg.Vault.Server.Util
{
/// <summary>
/// This attribute allows you to specify what type is used to configure
/// the behavior of another type instance, such as a service provider.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class ConfiguredByAttribute : Attribute
{
public ConfiguredByAttribute(Type type)
{
this.Type = type;
}
public Type Type
{ get; }
}
} | |
Add sample of an HTTP function integration test | // Copyright 2020 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.
// [START functions_http_integration_test]
using Google.Cloud.Functions.Invoker.Testing;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace HelloHttp.Tests
{
public class FunctionIntegrationTest
{
[Fact]
public async Task GetRequest_NoParameters()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "uri");
string text = await ExecuteRequest(request);
Assert.Equal("Hello world!", text);
}
[Fact]
public async Task GetRequest_UrlParameters()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "uri?name=Cho");
string text = await ExecuteRequest(request);
Assert.Equal("Hello Cho!", text);
}
[Fact]
public async Task PostRequest_BodyParameters()
{
string json = "{\"name\":\"Julie\"}";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "uri")
{
Content = new StringContent(json)
};
string text = await ExecuteRequest(request);
Assert.Equal("Hello Julie!", text);
}
/// <summary>
/// Executes the given request in the function in an in-memory test server,
/// validates that the response status code is 200, and returns the text of the
/// response body. FunctionTestServer{T} is provided by the
/// Google.Cloud.Functions.Invoker.Testing package.
/// </summary>
private static async Task<string> ExecuteRequest(HttpRequestMessage request)
{
using (var server = new FunctionTestServer<Function>())
{
using (HttpClient client = server.CreateClient())
{
HttpResponseMessage response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return await response.Content.ReadAsStringAsync();
}
}
}
}
}
// [END functions_http_integration_test]
| |
Add test scene for visually adjusting mania `BarLine`s | // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
public class TestSceneBarLine : ManiaSkinnableTestScene
{
[Test]
public void TestMinor()
{
AddStep("Create barlines", () => recreate());
}
private void recreate(Func<IEnumerable<BarLine>>? createBarLines = null)
{
var stageDefinitions = new List<StageDefinition>
{
new StageDefinition { Columns = 4 },
};
SetContents(_ => new ManiaPlayfield(stageDefinitions).With(s =>
{
if (createBarLines != null)
{
var barLines = createBarLines();
foreach (var b in barLines)
s.Add(b);
return;
}
for (int i = 0; i < 64; i++)
{
s.Add(new BarLine
{
StartTime = Time.Current + i * 500,
Major = i % 4 == 0,
});
}
}));
}
}
}
| |
Add an abstraction for either reporting an array or results, or streaming them in LSP scenarios. | // 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.
#nullable enable
using System;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Helper type to allow command handlers to report data either in a streaming fashion (if a client supports that),
/// or as an array of results.
/// </summary>
/// <typeparam name="T"></typeparam>
internal struct BufferedProgress<T> : IProgress<T>, IDisposable
{
/// <summary>
/// The progress stream to report results to. May be <see langword="null"/> for clients that do not support streaming.
/// If <see langword="null"/> then <see cref="_buffer"/> will be non null and will contain all the produced values.
/// </summary>
private readonly IProgress<T[]>? _underlyingProgress;
/// <summary>
/// A buffer that results are held in if the client does not support streaming. Values of this can be retrieved
/// using <see cref="GetValues"/>.
/// </summary>
private readonly ArrayBuilder<T>? _buffer;
public BufferedProgress(IProgress<T[]>? underlyingProgress)
{
_underlyingProgress = underlyingProgress;
_buffer = underlyingProgress == null ? ArrayBuilder<T>.GetInstance() : null;
}
public void Dispose()
=> _buffer?.Free();
/// <summary>
/// Report a value either in a streaming or buffered fashion depending on what the client supports.
/// </summary>
public void Report(T value)
{
_underlyingProgress?.Report(new[] { value });
_buffer?.Add(value);
}
/// <summary>
/// Gets the set of buffered values. Will return null if the client supports streaming.
/// </summary>
public T[]? GetValues()
=> _buffer?.ToArray();
}
internal static class BufferedProgress
{
public static BufferedProgress<T> Create<T>(IProgress<T[]>? progress)
=> new BufferedProgress<T>(progress);
}
}
| |
Test to repro multiple subscribers issue | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MassTransit.Tests.TextFixtures;
using MassTransit.TestFramework;
using MassTransit.BusConfigurators;
using NUnit.Framework;
using Magnum.TestFramework;
using Magnum;
using Magnum.Extensions;
namespace MassTransit.Tests.Subscriptions
{
[TestFixture]
public class when_multiple_subscribers_to_same_message
: LoopbackLocalAndRemoteTestFixture
{
protected override void EstablishContext()
{
base.EstablishContext();
RemoteBus.ShouldHaveSubscriptionFor<MyMessage>();
LocalBus.Publish(new MyMessage());
}
private List<Tuple<string, MyMessage>> receivedMessages = new List<Tuple<string, MyMessage>>();
protected override void ConfigureRemoteBus(ServiceBusConfigurator configurator)
{
base.ConfigureLocalBus(configurator);
configurator.Subscribe(cf =>
{
cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("One", message)));
cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("Two", message)));
});
}
[Test]
public void each_subscriber_should_only_receive_once()
{
ThreadUtil.Sleep(4.Seconds());
var byReceiver = receivedMessages.GroupBy(r => r.Item1);
byReceiver.All(g => g.Count() == 1).ShouldBeTrue();
}
}
public class MyMessage
{
}
}
| |
Add test cases for ViewModels.AboutWindowViewModel | using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Models;
using ThScoreFileConverter.Properties;
using ThScoreFileConverter.ViewModels;
namespace ThScoreFileConverterTests.ViewModels
{
[TestClass]
public class AboutWindowViewModelTests
{
[TestMethod]
public void TitleTest()
{
var window = new AboutWindowViewModel();
Assert.AreEqual(Utils.GetLocalizedValues<string>(nameof(Resources.AboutWindowTitle)), window.Title);
}
[TestMethod]
public void IconTest()
{
var window = new AboutWindowViewModel();
Assert.IsNotNull(window.Icon);
}
[TestMethod]
public void NameTest()
{
var window = new AboutWindowViewModel();
Assert.AreEqual(nameof(ThScoreFileConverter), window.Name);
}
[TestMethod]
public void VersionTest()
{
var window = new AboutWindowViewModel();
StringAssert.StartsWith(window.Version, Utils.GetLocalizedValues<string>(nameof(Resources.VersionPrefix)));
}
[TestMethod]
public void CopyrightTest()
{
var window = new AboutWindowViewModel();
Assert.IsFalse(string.IsNullOrEmpty(window.Copyright));
}
[TestMethod]
public void UriTest()
{
var window = new AboutWindowViewModel();
Assert.AreEqual(Resources.ProjectUrl, window.Uri);
}
[TestMethod]
public void OpenUriCommandTest()
{
var window = new AboutWindowViewModel();
var command = window.OpenUriCommand;
Assert.IsNotNull(command);
Assert.IsTrue(command.CanExecute(Resources.ProjectUrl));
command.Execute(Resources.ProjectUrl);
}
[TestMethod]
public void CanCloseDialogTest()
{
var window = new AboutWindowViewModel();
Assert.IsTrue(window.CanCloseDialog());
}
}
}
| |
Add test suite with tests for MySQL 5.6 | using System;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
using Xunit;
using Microsoft.EntityFrameworkCore.Internal;
using Moq;
using MySql.Data.MySqlClient;
namespace Pomelo.EntityFrameworkCore.MySql.Tests.Migrations
{
public class MigrationSqlGeneratorMySql56Test : MigrationSqlGeneratorTestBase
{
protected override IMigrationsSqlGenerator SqlGenerator
{
get
{
// type mapper
var typeMapper = new MySqlTypeMapper(new RelationalTypeMapperDependencies());
// migrationsSqlGeneratorDependencies
var commandBuilderFactory = new RelationalCommandBuilderFactory(
new FakeDiagnosticsLogger<DbLoggerCategory.Database.Command>(),
typeMapper);
var migrationsSqlGeneratorDependencies = new MigrationsSqlGeneratorDependencies(
commandBuilderFactory,
new MySqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
typeMapper);
var mySqlOptions = new Mock<IMySqlOptions>();
mySqlOptions.SetupGet(opts => opts.ConnectionSettings).Returns(
new MySqlConnectionSettings(new MySqlConnectionStringBuilder(), new ServerVersion("5.6.2")));
return new MySqlMigrationsSqlGenerator(
migrationsSqlGeneratorDependencies,
mySqlOptions.Object);
}
}
private static FakeRelationalConnection CreateConnection(IDbContextOptions options = null)
=> new FakeRelationalConnection(options ?? CreateOptions());
private static IDbContextOptions CreateOptions(RelationalOptionsExtension optionsExtension = null)
{
var optionsBuilder = new DbContextOptionsBuilder();
((IDbContextOptionsBuilderInfrastructure)optionsBuilder)
.AddOrUpdateExtension(optionsExtension
?? new FakeRelationalOptionsExtension().WithConnectionString("test"));
return optionsBuilder.Options;
}
public override void RenameIndexOperation_works()
{
base.RenameIndexOperation_works();
Assert.Equal("ALTER TABLE `People` DROP INDEX `IX_People_Name`;" + EOL
+ "ALTER TABLE `People` CREATE INDEX `IX_People_Better_Name`;" + EOL,
Sql);
}
}
}
| |
Add test coverage of startup ruleset being non-default | // 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.Development;
using osu.Game.Configuration;
namespace osu.Game.Tests.Visual.Navigation
{
[TestFixture]
public class TestSceneStartupRuleset : OsuGameTestScene
{
protected override TestOsuGame CreateTestGame()
{
// Must be done in this function due to the RecycleLocalStorage call just before.
var config = DebugUtils.IsDebugBuild
? new DevelopmentOsuConfigManager(LocalStorage)
: new OsuConfigManager(LocalStorage);
config.SetValue(OsuSetting.Ruleset, "mania");
config.Save();
return base.CreateTestGame();
}
[Test]
public void TestRulesetConsumed()
{
AddUntilStep("ruleset correct", () => Game.Ruleset.Value.ShortName == "mania");
}
}
}
| |
Add missing file in the previous commit. | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using NuGet;
using NuGetPackageExplorer.Types;
namespace PackageExplorerViewModel.Rules {
[Export(typeof(IPackageRule))]
internal class NonAssemblyReferenceName : IPackageRule {
public string Name {
get {
return "Non-Assembly Reference Name";
}
}
public IEnumerable<PackageIssue> Check(IPackage package) {
return from reference in package.References
let file = reference.File
where !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
!file.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
select CreateIssue(file);
}
private static PackageIssue CreateIssue(string reference) {
return new PackageIssue(
PackageIssueLevel.Warning,
"Non-assembly reference name",
"The name '" + reference + "' in the Filtered Assembly References is not a valid assembly name. An assembly name must have extension as either .dll or .exe.",
"Remove this assembly reference name.");
}
}
} | |
Add Interleaved 2 of 5 Barcode | using System;
using System.Collections.Generic;
namespace BinaryKits.Utility.ZPLUtility.Elements
{
/// <summary>
/// Interleaved 2 of 5 Barcode
/// </summary>
public class ZPLBarCodeInterleaved2of5 : ZPLBarcode
{
public bool Mod10CheckDigit { get; private set; }
public ZPLBarCodeInterleaved2of5(string content, int positionX, int positionY, int height = 100, string orientation = "N", bool printInterpretationLine = true, bool printInterpretationLineAboveCode = false, bool mod10CheckDigit = false)
: base(content, positionX, positionY, height, orientation, printInterpretationLine, printInterpretationLineAboveCode)
{
if (!IsDigitsOnly(content))
{
throw new ArgumentException("Interleaved 2 of 5 Barcode allow only digits", nameof(content));
}
Mod10CheckDigit = mod10CheckDigit;
}
public override IEnumerable<string> Render(ZPLRenderOptions context)
{
var result = new List<string>();
result.AddRange(Origin.Render(context));
result.Add($"^B2{Orientation},{context.Scale(Height)},{(PrintInterpretationLine ? "Y" : "N")},{(PrintInterpretationLineAboveCode ? "Y" : "N")},{(Mod10CheckDigit ? "Y" : "N")}");
result.Add($"^FD{Content}^FS");
return result;
}
private bool IsDigitsOnly(string text)
{
foreach (char c in text)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
}
}
| |
Add unit tests covering update | using System;
using System.Xml.Linq;
using Buildalyzer.Construction;
using NUnit.Framework;
using Shouldly;
namespace Buildalyzer.Tests.Construction
{
[TestFixture]
public class PackageReferenceFixture
{
[Test]
public void PackageReferenceWithInclude_Should_ContainName()
{
// Given
XElement xml = XElement.Parse(@"<PackageReference Include=""IncludedDependency"" Version=""1.0.0"" />");
// When
PackageReference packageReference = new PackageReference(xml);
// Then
packageReference.Name.ShouldBe("IncludedDependency");
}
[Test]
public void PackageReferenceWithVersion_Should_ContainVersion()
{
// Given
XElement xml = XElement.Parse(@"<PackageReference Include=""IncludedDependency"" Version=""1.0.0"" />");
// When
PackageReference packageReference = new PackageReference(xml);
// Then
packageReference.Version.ShouldBe("1.0.0");
}
[Test]
public void PackageReferenceWithUpgrade_Should_ContainName()
{
// Given
XElement xml = XElement.Parse(@"<PackageReference Update=""UpdatedDependency"" Version=""1.0.0"" />");
// When
PackageReference packageReference = new PackageReference(xml);
// Then
packageReference.Name.ShouldBe("UpdatedDependency");
}
}
}
| |
Add one unit test to a new method | using FonctionsUtiles.Fred.Csharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace TestProjectCoreUseFulFunctions
{
[TestClass]
public class UnitTestFunctionsString
{
[DataTestMethod]
[TestCategory("String")]
public void TestMethod_SplitString_One_Word()
{
string source = "azerty";
const int source2 = 3;
List<string> expected = new List<string>() { "az", "rt", "" };
List<string> result = (List<string>)FunctionsString.SplitString(source, source2);
CollectionAssert.AreEquivalent(result, expected);
}
}
}
| |
Add abstraction for connection string | namespace ServiceBus.AttachmentPlugin
{
/// <summary>
/// Storage account connection string provider.
/// </summary>
public interface IProvideStorageConnectionString
{
/// <summary>
/// Connection string for storage account to be used.
/// </summary>
string GetConnectionString();
}
} | |
Add full screen initialization test. | using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class HelloWorldProgram : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (!(Display.CurrentWindow.IsClosed || Keyboard.Keys[KeyCode.Escape]))
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
} | |
Add test coverage of `ShearedOverlayContainer` | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneShearedOverlayContainer : OsuManualInputManagerTestScene
{
private TestShearedOverlayContainer overlay;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create overlay", () =>
{
Child = overlay = new TestShearedOverlayContainer
{
State = { Value = Visibility.Visible }
};
});
}
[Test]
public void TestClickAwayToExit()
{
AddStep("click inside header", () =>
{
InputManager.MoveMouseTo(overlay.ChildrenOfType<ShearedOverlayHeader>().First().ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
});
AddAssert("overlay not dismissed", () => overlay.State.Value == Visibility.Visible);
AddStep("click inside content", () =>
{
InputManager.MoveMouseTo(overlay.ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
});
AddAssert("overlay not dismissed", () => overlay.State.Value == Visibility.Visible);
AddStep("click outside header", () =>
{
InputManager.MoveMouseTo(new Vector2(overlay.ScreenSpaceDrawQuad.TopLeft.X, overlay.ScreenSpaceDrawQuad.Centre.Y));
InputManager.Click(MouseButton.Left);
});
AddAssert("overlay dismissed", () => overlay.State.Value == Visibility.Hidden);
}
public class TestShearedOverlayContainer : ShearedOverlayContainer
{
protected override OverlayColourScheme ColourScheme => OverlayColourScheme.Green;
[BackgroundDependencyLoader]
private void load()
{
Header.Title = "Sheared overlay header";
Header.Description = string.Join(" ", Enumerable.Repeat("This is a description.", 20));
MainAreaContent.Child = new InputBlockingContainer
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.9f),
Children = new Drawable[]
{
new Box
{
Colour = Color4.Blue,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Font = OsuFont.Default.With(size: 24),
Text = "Content",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
}
};
}
}
}
}
| |
Allow event handler to have many IHandleEventOf<T> implementation and ensure the most relevent Handle method is invoked | using System;
using System.Collections.Generic;
namespace JustGiving.EventStore.Http.SubscriberHost
{
/// <summary>
/// Compares Types resulting in the most derived being at the top
/// </summary>
public class TypeInheritanceComparer : IComparer<Type>
{
public int Compare(Type x, Type y)
{
if (x == y)
{
return 0;
}
if (x.IsAssignableFrom(y))
{
return 1;
}
return -1;
}
}
} | |
Add Test for removing readonly flag when copying readonly library assets | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Xunit;
using Microsoft.DotNet.Cli.Compiler.Common;
using Microsoft.DotNet.ProjectModel.Compilation;
using System.IO;
using System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.DotNet.Cli.Compiler.Common.Tests
{
public class GivenThatICopyLibraryAssets
{
[Fact]
public void LibraryAsset_CopyTo_Clears_Readonly()
{
var libraryAsset = GetMockLibraryAsset(nameof(LibraryAsset_CopyTo_Clears_Readonly));
MakeFileReadonly(libraryAsset.ResolvedPath);
IEnumerable<LibraryAsset> assets = new LibraryAsset[] { libraryAsset };
var outputDirectory = Path.Combine(AppContext.BaseDirectory,$"{nameof(LibraryAsset_CopyTo_Clears_Readonly)}_out");
assets.CopyTo(outputDirectory);
var copiedFile = Directory.EnumerateFiles(outputDirectory, Path.GetFileName(libraryAsset.RelativePath)).First();
FileIsReadonly(copiedFile).Should().BeFalse();
}
[Fact]
public void LibraryAsset_StructuredCopyTo_Clears_Readonly()
{
var libraryAsset = GetMockLibraryAsset(nameof(LibraryAsset_StructuredCopyTo_Clears_Readonly));
MakeFileReadonly(libraryAsset.ResolvedPath);
IEnumerable<LibraryAsset> assets = new LibraryAsset[] { libraryAsset };
var intermediateDirectory = Path.Combine(AppContext.BaseDirectory,$"{nameof(LibraryAsset_StructuredCopyTo_Clears_Readonly)}_obj");
var outputDirectory = Path.Combine(AppContext.BaseDirectory,$"{nameof(LibraryAsset_StructuredCopyTo_Clears_Readonly)}_out");
assets.StructuredCopyTo(outputDirectory, intermediateDirectory);
var copiedFile = Directory.EnumerateFiles(outputDirectory, Path.GetFileName(libraryAsset.RelativePath)).First();
FileIsReadonly(copiedFile).Should().BeFalse();
}
private void MakeFileReadonly(string file)
{
File.SetAttributes(file, File.GetAttributes(file) | FileAttributes.ReadOnly);
}
private bool FileIsReadonly(string file)
{
return (File.GetAttributes(file) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
}
private LibraryAsset GetMockLibraryAsset(string mockedLibraryAssetName)
{
var mockedLibraryAssetFileName = $"{mockedLibraryAssetName}.dll";
var fakeFile = Path.Combine(AppContext.BaseDirectory, mockedLibraryAssetFileName);
File.WriteAllText(fakeFile, mockedLibraryAssetName);
return new LibraryAsset(mockedLibraryAssetName, mockedLibraryAssetFileName, fakeFile);
}
}
}
| |
Add option for fixed provider | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class FixedRequestAuthorizerProvider : IRequestAuthorizerProvider
{
public FixedRequestAuthorizerProvider()
: this(Enumerable.Empty<IRequestAuthorizer>())
{
}
public FixedRequestAuthorizerProvider(IEnumerable<IRequestAuthorizer> controllerTypes)
{
Policies = new List<IRequestAuthorizer>(controllerTypes);
}
public IList<IRequestAuthorizer> Policies { get; }
IEnumerable<IRequestAuthorizer> IRequestAuthorizerProvider.Authorizers => Policies;
}
} | |
Read and update time zone settings | // CSOM Package (16.1.3912.1204)
// Gets and sets the current Time Zone settings from the given SharePoint site
// Get access to source site
using (var ctx = new ClientContext("https://spknowledge.sharepoint.com"))
{
//Provide count and pwd for connecting to the source
var passWord = new SecureString();
foreach (char c in "<mypassword>".ToCharArray()) passWord.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials("<office 365 mail id>", passWord);
// Actual code for operations
Web web = ctx.Web;
RegionalSettings regSettings = web.RegionalSettings;
ctx.Load(web);
ctx.Load(regSettings); //To get regional settings properties
Microsoft.SharePoint.Client.TimeZone currentTimeZone = regSettings.TimeZone;
ctx.Load(currentTimeZone); //To get the TimeZone propeties for the current web region settings
ctx.ExecuteQuery();
//Get the current site TimeZone
Console.WriteLine(string.Format("Connected to site with title of {0}", web.Title));
Console.WriteLine("Current TimeZone Settings: " + currentTimeZone.Id.ToString() +" - "+ currentTimeZone.Description);
//Update the TimeZone setting to (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi. TimeZone Id is 23
TimeZoneCollection globalTimeZones = RegionalSettings.GetGlobalTimeZones(ctx);
ctx.Load(globalTimeZones);
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.TimeZone newTimeZone = globalTimeZones.GetById(23);
regSettings.TimeZone = newTimeZone;
regSettings.Update(); //Update New settings to the web
ctx.ExecuteQuery();
Console.WriteLine("New TimeZone settings are updated.");
Console.ReadLine();
}
| |
Add bubbled word class for use in attribute rows | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
namespace osu.Game.Screens.Edit.Timing.RowAttributes
{
public class AttributeBubbledWord : CompositeDrawable
{
private readonly ControlPoint controlPoint;
private OsuSpriteText textDrawable;
private string text;
public string Text
{
get => text;
set
{
if (value == text)
return;
text = value;
if (textDrawable != null)
textDrawable.Text = text;
}
}
public AttributeBubbledWord(ControlPoint controlPoint)
{
this.controlPoint = controlPoint;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, OverlayColourProvider overlayColours)
{
AutoSizeAxes = Axes.X;
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
Height = 12;
InternalChildren = new Drawable[]
{
new Circle
{
Colour = controlPoint.GetRepresentingColour(colours),
RelativeSizeAxes = Axes.Both,
},
textDrawable = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Padding = new MarginPadding(3),
Font = OsuFont.Default.With(weight: FontWeight.SemiBold, size: 12),
Text = text,
Colour = colours.Gray0
},
};
}
}
}
| |
Add visual test for Tournament Mod Display | // 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests.Components
{
public class TestSceneTournamentModDisplay : TournamentTestScene
{
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
private FillFlowContainer<TournamentBeatmapPanel> fillFlow;
private BeatmapInfo beatmap;
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 490154 });
req.Success += success;
api.Queue(req);
Add(fillFlow = new FillFlowContainer<TournamentBeatmapPanel>
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Full,
Spacing = new osuTK.Vector2(10)
});
}
[Test]
public void TestModDisplay()
{
AddUntilStep("beatmap is available", () => beatmap != null);
AddStep("add maps with available mods for ruleset", () => displayForRuleset(Ladder.Ruleset.Value.ID ?? 0));
}
private void displayForRuleset(int rulesetId)
{
fillFlow.Clear();
var mods = rulesets.GetRuleset(rulesetId).CreateInstance().GetAllMods();
foreach (var mod in mods)
{
fillFlow.Add(new TournamentBeatmapPanel(beatmap, mod.Acronym));
}
}
private void success(APIBeatmap apiBeatmap) => beatmap = apiBeatmap.ToBeatmap(rulesets);
}
}
| |
Add fixed implementation for RequestRuntime provider | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class FixedRequestRuntimeProvider : IRequestRuntimeProvider
{
public FixedRequestRuntimeProvider()
: this(Enumerable.Empty<IRequestRuntime>())
{
}
public FixedRequestRuntimeProvider(IEnumerable<IRequestRuntime> controllerTypes)
{
Runtimes = new List<IRequestRuntime>(controllerTypes);
}
public IList<IRequestRuntime> Runtimes { get; }
IEnumerable<IRequestRuntime> IRequestRuntimeProvider.Runtimes => Runtimes;
}
} | |
Test to repro multiple subscribers issue | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MassTransit.Tests.TextFixtures;
using MassTransit.TestFramework;
using MassTransit.BusConfigurators;
using NUnit.Framework;
using Magnum.TestFramework;
using Magnum;
using Magnum.Extensions;
namespace MassTransit.Tests.Subscriptions
{
[TestFixture]
public class when_multiple_subscribers_to_same_message
: LoopbackLocalAndRemoteTestFixture
{
protected override void EstablishContext()
{
base.EstablishContext();
RemoteBus.ShouldHaveSubscriptionFor<MyMessage>();
LocalBus.Publish(new MyMessage());
}
private List<Tuple<string, MyMessage>> receivedMessages = new List<Tuple<string, MyMessage>>();
protected override void ConfigureRemoteBus(ServiceBusConfigurator configurator)
{
base.ConfigureLocalBus(configurator);
configurator.Subscribe(cf =>
{
cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("One", message)));
cf.Handler<MyMessage>(message => receivedMessages.Add(new Tuple<string, MyMessage>("Two", message)));
});
}
[Test]
public void each_subscriber_should_only_receive_once()
{
ThreadUtil.Sleep(4.Seconds());
var byReceiver = receivedMessages.GroupBy(r => r.Item1);
byReceiver.All(g => g.Count() == 1).ShouldBeTrue();
}
}
public class MyMessage
{
}
}
| |
Add a test scene for non-top level menus | // 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.UserInterface;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneClosableMenu : MenuTestScene
{
protected override Menu CreateMenu() => new BasicMenu(Direction.Vertical)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
State = MenuState.Open,
Items = new[]
{
new MenuItem("Item #1")
{
Items = new[]
{
new MenuItem("Sub-item #1"),
new MenuItem("Sub-item #2"),
}
},
new MenuItem("Item #2")
{
Items = new[]
{
new MenuItem("Sub-item #1"),
new MenuItem("Sub-item #2"),
}
},
}
};
[Test]
public void TestClickItemClosesMenus()
{
AddStep("click item", () => ClickItem(0, 0));
AddStep("click item", () => ClickItem(1, 0));
AddAssert("all menus closed", () =>
{
for (int i = 1; i >= 0; --i)
{
if (Menus.GetSubMenu(i).State == MenuState.Open)
return false;
}
return true;
});
}
}
}
| |
Add failing tests for in parameters | using NUnit.Framework;
namespace ApiContractGenerator.Tests.Integration
{
public sealed class SignatureTests : IntegrationTests
{
[Test]
public static void Ref_readonly_method_parameter_should_use_in()
{
Assert.That("public struct A { public void Test(in int x) { } }", HasContract(
"public struct A",
"{",
" public void Test(in int x);",
"}"));
}
[Test]
public static void Ref_readonly_delegate_parameter_should_use_in()
{
Assert.That("public delegate void Test(in int x);", HasContract(
"public delegate void Test(in int x);"));
}
}
}
| |
Create view model for tracking last logs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Baskerville.Models.ViewModels
{
public class LastLogsViewModel
{
public string Username { get; set; }
public DateTime Date { get; set; }
}
}
| |
Add ExtensionMethod class for supporting functions. Added function to shift number of decimal points | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LogFilterApplication
{
public static class ExtensionMethods
{
public static string ShiftDecimalPoint(double inputNumber, int decimalToShift)
{
string retVal = "";
inputNumber /= Math.Pow(10.0, decimalToShift);
retVal = inputNumber.ToString();
return retVal;
}
}
}
| |
Revert "GraphQL: Default to use builtin GUID primitives" | using System;
using GraphQL.Language.AST;
using GraphQL.Types;
namespace GraphQL.Types
{
public class GuidGraphType : ScalarGraphType
{
public GuidGraphType()
{
Name = "Guid";
Description = "Globally Unique Identifier.";
}
public override object ParseValue(object value) =>
ValueConverter.ConvertTo(value, typeof(Guid));
public override object Serialize(object value) => ParseValue(value);
/// <inheritdoc/>
public override object ParseLiteral(IValue value)
{
if (value is GuidValue guidValue)
{
return guidValue.Value;
}
if (value is StringValue str)
{
return ParseValue(str.Value);
}
return null;
}
}
}
| |
Add delivery client factory simple tests | using FakeItEasy;
using FluentAssertions;
using Kentico.Kontent.Delivery.Abstractions;
using Kentico.Kontent.Delivery.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Kentico.Kontent.Delivery.Tests.Factories
{
public class DeliveryClientFactoryTests
{
private readonly IOptions<DeliveryOptions> _deliveryOptionsMock;
private readonly IOptionsMonitor<DeliveryClientFactoryOptions> _deliveryClientFactoryOptionsMock;
private readonly IServiceProvider _serviceProviderMock;
private const string _clientName = "ClientName";
public DeliveryClientFactoryTests()
{
_deliveryOptionsMock = A.Fake<IOptions<DeliveryOptions>>();
_deliveryClientFactoryOptionsMock = A.Fake<IOptionsMonitor<DeliveryClientFactoryOptions>>();
_serviceProviderMock = A.Fake<IServiceProvider>();
}
[Fact]
public void GetNamedClient_WithCorrectName_GetClient()
{
var deliveryClient = new DeliveryClient(_deliveryOptionsMock);
var deliveryClientFactoryOptions = new DeliveryClientFactoryOptions();
deliveryClientFactoryOptions.DeliveryClientsActions.Add(() => deliveryClient);
A.CallTo(() => _deliveryClientFactoryOptionsMock.Get(_clientName))
.Returns(deliveryClientFactoryOptions);
var deliveryClientFactory = new Delivery.DeliveryClientFactory(_deliveryClientFactoryOptionsMock, _serviceProviderMock);
var result = deliveryClientFactory.Get(_clientName);
result.Should().Be(deliveryClient);
}
[Fact]
public void GetNamedClient_WithWrongName_GetNull()
{
var deliveryClient = new DeliveryClient(_deliveryOptionsMock);
var deliveryClientFactoryOptions = new DeliveryClientFactoryOptions();
deliveryClientFactoryOptions.DeliveryClientsActions.Add(() => deliveryClient);
A.CallTo(() => _deliveryClientFactoryOptionsMock.Get(_clientName))
.Returns(deliveryClientFactoryOptions);
var deliveryClientFactory = new Delivery.DeliveryClientFactory(_deliveryClientFactoryOptionsMock, _serviceProviderMock);
var result = deliveryClientFactory.Get("WrongName");
result.Should().BeNull();
}
}
}
| |
Add partial class for retry settings | // Copyright 2019 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 System;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using sys = System;
namespace Google.Cloud.Redis.V1
{
// This is a partial class introduced for backward compatibility with earlier versions.
public partial class CloudRedisSettings
{
/// <summary>
/// In previous releases, this property returned a filter used by default for "Idempotent" RPC methods.
/// It is now unused, and may not represent the current default behavior.
/// </summary>
[Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);
/// <summary>
/// In previous releases, this property returned a filter used by default for "NonIdempotent" RPC methods.
/// It is now unused, and may not represent the current default behavior.
/// </summary>
[Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes();
/// <summary>
/// In previous releases, this method returned the backoff used by default for "Idempotent" RPC methods.
/// It is now unused, and may not represent the current default behavior.
/// </summary>
[Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(100),
maxDelay: sys::TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// In previous releases, this method returned the backoff used by default for "NonIdempotent" RPC methods.
/// It is now unused, and may not represent the current default behavior.
/// </summary>
[Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(20000),
maxDelay: sys::TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
}
} | |
Add test file for FileCallbackResult action | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NUnit.Framework;
using NUnit.Framework.Internal;
using SFA.DAS.CommitmentsV2.Shared.ActionResults;
namespace SFA.DAS.CommitmentsV2.Shared.UnitTests.ActionResults
{
public class FileCallbackResultTests
{
[Test]
public void Then_If_The_Media_Type_Is_Not_Correct_An_Exception_Is_Thrown()
{
Assert.Throws<FormatException>(() => new FileCallbackResult("wrong", delegate{ return null; }));
}
[Test]
public void Then_If_There_Is_No_Callback_An_Exception_Is_Thrown()
{
Assert.Throws<ArgumentNullException>(() => new FileCallbackResult("text/csv", null));
}
}
}
| |
Add event handler for picking up prizes | using UnityEngine;
using UnityEngine.Assertions;
[RequireComponent(typeof(AudioSource))]
//uses mp3 for music, and ogg for sound effects
public class SoundManager : BaseBehaviour
{
public AudioClip collectPrize;
private new AudioSource audio;
void Awake()
{
audio = GetComponent<AudioSource>();
Assert.IsNotNull(audio);
AudioListener.volume = 1F;
}
void OnPrizeCollected(int worth)
{
if (worth > 5)
{
audio.PlayOneShot(collectPrize, 0F);
}
}
void OnEnable()
{
EventKit.Subscribe<int>("prize collected", OnPrizeCollected);
}
void OnDestroy()
{
EventKit.Unsubscribe<int>("prize collected", OnPrizeCollected);
}
}
| |
Add file to the last commit | using System;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace Lokad.Cqrs.Feature.AtomicStorage
{
[TestFixture, Explicit]
public sealed class Stand_alone_tests
{
// ReSharper disable InconsistentNaming
[Test]
public void Test()
{
var nuclearStorage = FileStorage.CreateNuclear(GetType().Name);
var writer = nuclearStorage.Factory.GetEntityWriter<unit,Dunno>();
writer.UpdateEnforcingNew(unit.it, dunno => dunno.Count += 1);
writer.UpdateEnforcingNew(unit.it, dunno => dunno.Count += 1);
var count = nuclearStorage.Factory.GetEntityReader<unit,Dunno>().GetOrNew().Count;
Console.WriteLine(count);
}
[DataContract]
public sealed class Dunno
{
[DataMember]
public int Count { get; set; }
}
}
} | |
Add DeleteMessage Job & TriggerQueue | using Quartz;
using System;
using System.Threading.Tasks;
using Discord;
using Microsoft.Extensions.DependencyInjection;
using NLog;
namespace NoAdsHere.Services.Penalties
{
public static class JobQueue
{
private static IScheduler _scheduler;
public static Task Install(IServiceProvider provider)
{
_scheduler = provider.GetService<IScheduler>();
return Task.CompletedTask;
}
public static async Task QueueTrigger(IUserMessage message)
{
var job = JobBuilder.Create<DeleteMessageJob>()
.StoreDurably()
.Build();
var trigger = TriggerBuilder.Create()
.StartAt(DateTimeOffset.Now.AddSeconds(10))
.ForJob(job)
.Build();
trigger.JobDataMap["message"] = message;
await _scheduler.ScheduleJob(job, trigger);
}
}
public class DeleteMessageJob : IJob
{
private readonly Logger _logger = LogManager.GetLogger("AntiAds");
public async Task Execute(IJobExecutionContext context)
{
var datamap = context.Trigger.JobDataMap;
var message = (IUserMessage)datamap["message"];
try
{
await message.DeleteAsync();
}
catch (Exception e)
{
_logger.Warn(e, $"Unable to delete Message {message.Id}.");
}
}
}
} | |
Add properties file for donet | 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("RocketMQ.Interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RocketMQ.Interop")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("057deebc-ec31-4265-b1ab-6738d51ef463")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| |
Add generic ILogger<> registration for Unity | // Problem: You need to register in Unity factory method that has single type parameters (a.k.a generic) to produce some generics
// var logger = ILoggerFactory.CreateLogger<T>()
// var logger = container.Resolve<ILogger<T>>();
public static class LoggerFactoryExtensions
{
/// <summary>
/// Creates a new ILogger instance using the full name of the given type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="factory">The factory.</param>
public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory)
{
// create something
}
}
// register factory
container.RegisterType<LoggerFactory>(new SingletonLifetimeManager());
// lets capture method
/* Capture CreateLogger<T>() method extension */
var factoryMethod = typeof(LoggerFactoryExtensions)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.First(x => x.ContainsGenericParameters && x.Name == "CreateLogger");
// register factory method
container.RegisterType(typeof(ILogger<>), new InjectionFactory((c, t, s) =>
{
var loggerFactory = c.Resolve<LoggerFactory>();
/* Resolve all ILogger<> dependencies by creating new logger */
var genFactoryMethod = factoryMethod.MakeGenericMethod(t.GetGenericArguments()[0]);
return genFactoryMethod.Invoke(loggerFactory, new object[] { });
})); | |
Add extension method to check value is in specified range | namespace SCPI.Extensions
{
public static class ValueTypeExtensions
{
/// <summary>
/// Checks that the value is within specified range
/// </summary>
/// <param name="value">Value to check</param>
/// <param name="minValue">The inclusive lower bound</param>
/// <param name="maxValue">The inclusive upper bound</param>
/// <returns>True if the value is within range otherwise false</returns>
public static bool IsWithin(this int value, int minValue, int maxValue)
{
var ret = false;
if (value >= minValue && value <= maxValue)
{
ret = true;
}
return ret;
}
}
}
| |
Create basic class representing an API instance. | using System;
namespace PortableWordPressApi
{
public class WordPressApi
{
public Uri ApiRootUri
{
get;
internal set;
}
}
}
| |
Add charting for user comments stats | @model IEnumerable<OCM.API.Common.DataSummary.GeneralStats>
<canvas id="userCommentsChart" width="280" height="200"></canvas>
<script>
//Get the context of the canvas element we want to select
var ctx = document.getElementById("userCommentsChart").getContext("2d");
var data = {
labels: [
@foreach (var stat in Model){
@Html.Raw("'"+stat.Month.ToString().PadLeft(2,'0')+"/"+stat.Year+"',")
}
],
datasets: [
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [
@foreach (var stat in Model){
@Html.Raw(stat.Quantity)
@Html.Raw(",")
}
]
}
]
}
var userCommentsChart = new Chart(ctx).Line(data, {});
</script> | |
Change the version number from 1.1.0 to 1.2.0 | /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
Add cake script for components | #addin "Cake.Xamarin"
var username = Argument("XamarinLicenseUser", "");
var password = Argument("XamarinLicensePassword", "");
var TARGET = Argument ("target", Argument ("t", "Default"));
Task ("Default").Does (() =>
{
RestoreComponents ("./MyTrips.sln", new XamarinComponentRestoreSettings
{
Email = username,
Password = password
});
});
RunTarget (TARGET);
| |
Add misssing file from previous checkin | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class CrossHierarchyCut
{
}
}
| |
Define a mapping of well-known storage names to impls | using System;
using System.Collections.Generic;
namespace Zyborg.Vault.Server.Storage
{
public static class Standard
{
public static readonly IReadOnlyDictionary<string, Type> StorageTypes =
new Dictionary<string, Type>
{
["in-memory"] = typeof(InMemoryStorage),
["file"] = typeof(FileStorage),
["json-file"] = typeof(JsonFileStorage),
};
}
} | |
Test that asserts all characters can be displayed properly | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace CSharpMath.Rendering.Tests {
using BackEnd;
public class TestCommandDisplay {
public TestCommandDisplay() =>
typefaces = Fonts.GlobalTypefaces.ToArray();
readonly Typography.OpenFont.Typeface[] typefaces;
public static IEnumerable<object[]> AllCommandValues =>
Atom.LaTeXSettings.Commands.Values
.SelectMany(v => v.Nucleus.EnumerateRunes())
.Distinct()
.OrderBy(r => r.Value)
.Select(rune => new object[] { rune });
[Theory]
[MemberData(nameof(AllCommandValues))]
public void CommandsAreDisplayable(Rune ch) =>
Assert.Contains(typefaces, font => font.GetGlyphIndex(ch.Value) != 0);
}
}
| |
Add StringBuilder extensions to accept a StringSlice | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Text;
namespace Markdig.Helpers
{
/// <summary>
/// Extensions for StringBuilder with <see cref="StringSlice"/>
/// </summary>
public static class StringBuilderExtensions
{
/// <summary>
/// Appends the specified slice to this <see cref="StringBuilder"/> instance.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="slice">The slice.</param>
public static StringBuilder Append(this StringBuilder builder, StringSlice slice)
{
return builder.Append(slice.Text, slice.Start, slice.Length);
}
}
} | |
Add RFC 7748 test vectors | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Rfc
{
public static class X25519Tests
{
public static readonly TheoryData<string, string, string> Rfc7748TestVectors = new TheoryData<string, string, string>
{
{ "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552" },
{ "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957" },
};
[Theory]
[MemberData(nameof(Rfc7748TestVectors))]
public static void TestRfc7748(string privateKey, string publicKey, string sharedSecret)
{
var a = new X25519();
var kdf = new HkdfSha256();
using (var k = Key.Import(a, privateKey.DecodeHex(), KeyBlobFormat.RawPrivateKey))
using (var sharedSecretExpected = SharedSecret.Import(sharedSecret.DecodeHex()))
using (var sharedSecretActual = a.Agree(k, PublicKey.Import(a, publicKey.DecodeHex(), KeyBlobFormat.RawPublicKey)))
{
var expected = kdf.Extract(sharedSecretExpected, ReadOnlySpan<byte>.Empty);
var actual = kdf.Extract(sharedSecretActual, ReadOnlySpan<byte>.Empty);
Assert.Equal(expected, actual);
}
}
}
}
| |
Test illustrating a way to find the composed character sequences. They are the indexes missing from the array. | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace CSharpMath.Tests {
public class ComposedCharacterTests {
[Fact]
public void TestCharacterRanges() {
string foo = "\u0104\u0301Hello\u0104\u0304 world";
int length = foo.Length;
var unicode = new UnicodeEncoding();
byte[] encodeFoo = unicode.GetBytes(foo);
int[] fooInfo = StringInfo.ParseCombiningCharacters(foo);
Assert.DoesNotContain(1, fooInfo);
Assert.DoesNotContain(8, fooInfo);
}
}
}
| |
Change name to match what's being tested | using System.Text;
using Sodium;
using NUnit.Framework;
namespace Tests
{
/// <summary>
/// Tests for Random Bytes support
/// </summary>
[TestFixture]
public class RandomBytesTest
{
/// <summary>
/// Does SodiumCore.GetRandomBytes() return something
/// </summary>
[Test]
public void GenerateBytesTest()
{
byte[] v16, v32, v64;
v16 = SodiumCore.GetRandomBytes(16);
v32 = SodiumCore.GetRandomBytes(32);
v64 = SodiumCore.GetRandomBytes(64);
Assert.IsNotNull(v16);
Assert.IsNotNull(v32);
Assert.IsNotNull(v64);
Assert.AreEqual(16U, v16.Length);
Assert.AreEqual(32U, v32.Length);
Assert.AreEqual(64U, v64.Length);
}
}
}
| using System.Text;
using Sodium;
using NUnit.Framework;
namespace Tests
{
/// <summary>
/// Tests for Random Bytes support
/// </summary>
[TestFixture]
public class RandomBytesTest
{
/// <summary>
/// Does SodiumCore.GetRandomBytes() return something
/// </summary>
[Test]
public void GetRandomBytesTest()
{
byte[] v16, v32, v64;
v16 = SodiumCore.GetRandomBytes(16);
v32 = SodiumCore.GetRandomBytes(32);
v64 = SodiumCore.GetRandomBytes(64);
Assert.IsNotNull(v16);
Assert.IsNotNull(v32);
Assert.IsNotNull(v64);
Assert.AreEqual(16U, v16.Length);
Assert.AreEqual(32U, v32.Length);
Assert.AreEqual(64U, v64.Length);
}
}
}
|
Add failing test for editor gameplay test using wrong ruleset | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osu.Game.Screens.Edit.GameplayTest;
using osu.Game.Screens.Select;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneEditorNavigation : OsuGameTestScene
{
[Test]
public void TestEditorGameplayTestAlwaysUsesOriginalRuleset()
{
BeatmapSetInfo beatmapSet = null!;
AddStep("import test beatmap", () => Game.BeatmapManager.Import(TestResources.GetTestBeatmapForImport()).WaitSafely());
AddStep("retrieve beatmap", () => beatmapSet = Game.BeatmapManager.QueryBeatmapSet(set => !set.Protected).AsNonNull().Value.Detach());
AddStep("present beatmap", () => Game.PresentBeatmap(beatmapSet));
AddUntilStep("wait for song select",
() => Game.Beatmap.Value.BeatmapSetInfo.Equals(beatmapSet)
&& Game.ScreenStack.CurrentScreen is PlaySongSelect songSelect
&& songSelect.IsLoaded);
AddStep("switch ruleset", () => Game.Ruleset.Value = new ManiaRuleset().RulesetInfo);
AddStep("open editor", () => ((PlaySongSelect)Game.ScreenStack.CurrentScreen).Edit(beatmapSet.Beatmaps.First(beatmap => beatmap.Ruleset.OnlineID == 0)));
AddUntilStep("wait for editor open", () => Game.ScreenStack.CurrentScreen is Editor editor && editor.IsLoaded);
AddStep("test gameplay", () =>
{
var testGameplayButton = this.ChildrenOfType<TestGameplayButton>().Single();
InputManager.MoveMouseTo(testGameplayButton);
InputManager.Click(MouseButton.Left);
});
AddUntilStep("wait for player", () => Game.ScreenStack.CurrentScreen is EditorPlayer editorPlayer && editorPlayer.IsLoaded);
AddAssert("current ruleset is osu!", () => Game.Ruleset.Value.Equals(new OsuRuleset().RulesetInfo));
AddStep("exit to song select", () => Game.PerformFromScreen(_ => { }, typeof(PlaySongSelect).Yield()));
AddUntilStep("wait for song select", () => Game.ScreenStack.CurrentScreen is PlaySongSelect);
AddAssert("previous ruleset restored", () => Game.Ruleset.Value.Equals(new ManiaRuleset().RulesetInfo));
}
}
}
| |
Fix join-path tests on Unix. | // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using NUnit.Framework;
using System;
namespace TestHost.Cmdlets
{
[TestFixture]
public class JoinPathTests
{
[Test]
public void OneParentFolderAndChildFolder()
{
string result = TestHost.Execute(@"Join-Path 'parent' 'child'");
Assert.AreEqual(@"parent\child" + Environment.NewLine, result);
}
[Test]
public void TwoParentFoldersAndOneChildFolder()
{
string result = TestHost.Execute(@"Join-Path parent1,parent2 child");
Assert.AreEqual(string.Format(@"parent1\child{0}parent2\child{0}", Environment.NewLine), result);
}
}
}
| // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using NUnit.Framework;
using System;
namespace TestHost.Cmdlets
{
[TestFixture]
public class JoinPathTests
{
[Test]
[Platform("Win")]
public void OneParentFolderAndChildFolderUnderWindows()
{
string result = TestHost.Execute(@"Join-Path 'parent' 'child'");
Assert.AreEqual(@"parent\child" + Environment.NewLine, result);
}
[Test]
[Platform("Unix")]
public void OneParentFolderAndChildFolderUnderUnix()
{
string result = TestHost.Execute(@"Join-Path 'parent' 'child'");
Assert.AreEqual(@"parent/child" + Environment.NewLine, result);
}
[Test]
[Platform("Win")]
public void TwoParentFoldersAndOneChildFolderUnderWindows()
{
string result = TestHost.Execute(@"Join-Path parent1,parent2 child");
Assert.AreEqual(string.Format(@"parent1\child{0}parent2\child{0}", Environment.NewLine), result);
}
[Test]
[Platform("Unix")]
public void TwoParentFoldersAndOneChildFolderUnderUnix()
{
string result = TestHost.Execute(@"Join-Path parent1,parent2 child");
Assert.AreEqual(string.Format(@"parent1/child{0}parent2/child{0}", Environment.NewLine), result);
}
}
}
|
Add a (disabled by default) map loading test for Generals | using System.Linq;
using OpenSage.Data;
using OpenSage.Mods.Generals;
using OpenSage.Tests.Data;
using Veldrid;
using Xunit;
using Xunit.Abstractions;
namespace OpenSage.Tests.Content
{
public class LoadMapsTests
{
private readonly ITestOutputHelper _testOutputHelper;
public LoadMapsTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[GameFact(SageGame.CncGenerals, Skip = "Can take up to 30 minutes to run")]
public void LoadGeneralsMaps()
{
var rootFolder = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);
var fileSystem = installation.CreateFileSystem();
var maps = fileSystem.GetFiles("maps").Where(x => x.FilePath.EndsWith(".map")).ToList();
Platform.Start();
using (var window = new GameWindow("OpenSAGE test runner", 100, 100, 800, 600, GraphicsBackend.Direct3D11))
{
using (var game = GameFactory.CreateGame(installation, fileSystem, GamePanel.FromGameWindow(window)))
{
foreach (var map in maps)
{
_testOutputHelper.WriteLine($"Loading {map.FilePath}...");
var scene = game.ContentManager.Load<Scene3D>(map.FilePath);
Assert.NotNull(scene);
game.ContentManager.Unload();
}
}
}
Platform.Stop();
}
}
}
| |
Add failing tests for coverage of `GetDisplayString()` | // 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 Moq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Scoring;
using osu.Game.Users;
namespace osu.Game.Tests.Models
{
[TestFixture]
public class DisplayStringTest
{
private static readonly object[][] test_cases =
{
new object[] { makeMockBeatmapSet(), "artist - title (author)" },
new object[] { makeMockBeatmap(), "artist - title (author) [difficulty]" },
new object[] { makeMockMetadata(), "artist - title (author)" },
new object[] { makeMockScore(), "user playing artist - title (author) [difficulty]" },
new object[] { makeMockRuleset(), "ruleset" },
new object[] { makeMockUser(), "user" },
new object[] { new Fallback(), "fallback" }
};
[TestCaseSource(nameof(test_cases))]
public void TestDisplayString(object model, string expected) => Assert.That(model.GetDisplayString(), Is.EqualTo(expected));
private static IBeatmapSetInfo makeMockBeatmapSet()
{
var mock = new Mock<IBeatmapSetInfo>();
mock.Setup(m => m.Metadata).Returns(makeMockMetadata);
return mock.Object;
}
private static IBeatmapInfo makeMockBeatmap()
{
var mock = new Mock<IBeatmapInfo>();
mock.Setup(m => m.Metadata).Returns(makeMockMetadata);
mock.Setup(m => m.DifficultyName).Returns("difficulty");
return mock.Object;
}
private static IBeatmapMetadataInfo makeMockMetadata()
{
var mock = new Mock<IBeatmapMetadataInfo>();
mock.Setup(m => m.Artist).Returns("artist");
mock.Setup(m => m.Title).Returns("title");
mock.Setup(m => m.Author.Username).Returns("author");
return mock.Object;
}
private static IScoreInfo makeMockScore()
{
var mock = new Mock<IScoreInfo>();
mock.Setup(m => m.User).Returns(new APIUser { Username = "user" }); // TODO: temporary.
mock.Setup(m => m.Beatmap).Returns(makeMockBeatmap);
return mock.Object;
}
private static IRulesetInfo makeMockRuleset()
{
var mock = new Mock<IRulesetInfo>();
mock.Setup(m => m.Name).Returns("ruleset");
return mock.Object;
}
private static IUser makeMockUser()
{
var mock = new Mock<IUser>();
mock.Setup(m => m.Username).Returns("user");
return mock.Object;
}
private class Fallback
{
public override string ToString() => "fallback";
}
}
}
| |
Add simple use integration tests | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RawRabbit.Client;
using RawRabbit.IntegrationTests.TestMessages;
using Xunit;
namespace RawRabbit.IntegrationTests.SimpleUse
{
public class PublishAndSubscribeTests : IntegrationTestBase
{
public override void Dispose()
{
TestChannel.QueueDelete("basicmessage");
TestChannel.ExchangeDelete("rawrabbit.integrationtests.testmessages");
base.Dispose();
}
[Fact]
public async void Should_Be_Able_To_Subscribe_Without_Any_Additional_Config()
{
/* Setup */
var message = new BasicMessage { Prop = "Hello, world!" };
var recievedTcs = new TaskCompletionSource<BasicMessage>();
var publisher = BusClientFactory.CreateDefault();
var subscriber = BusClientFactory.CreateDefault();
await subscriber.SubscribeAsync<BasicMessage>((msg, info) =>
{
recievedTcs.SetResult(msg);
return recievedTcs.Task;
});
/* Test */
publisher.PublishAsync(message);
await recievedTcs.Task;
/* Assert */
Assert.Equal(recievedTcs.Task.Result.Prop, message.Prop);
}
}
}
| |
Add an optimization test problem to check the implementation of the differential evolution algorithm. | using ISAAR.MSolve.Analyzers.Optimization;
using ISAAR.MSolve.Analyzers.Optimization.Algorithms;
using ISAAR.MSolve.SamplesConsole.Optimization.BenchmarkFunctions;
using System;
namespace ISAAR.MSolve.SamplesConsole.Optimization
{
public class OptimizationTest
{
public static void Main()
{
//IObjectiveFunction objective = new Ackley();
//double[] lowerBounds = { -5, -5 };
//double[] upperBounds = { 5, 5 };
//IObjectiveFunction objective = new Beale();
//double[] lowerBounds = { -4.5, -4.5 };
//double[] upperBounds = { 4.5, 4.5 };
//IObjectiveFunction objective = new GoldsteinPrice();
//double[] lowerBounds = {-2, -2 };
//double[] upperBounds = { 2, 2 };
IObjectiveFunction objective = new McCormick();
double[] lowerBounds = { -1.5, -3.0 };
double[] upperBounds = { 4.0, 4.0 };
DifferentialEvolution de = new DifferentialEvolution(lowerBounds.Length, lowerBounds, upperBounds, objective);
IOptimizationAnalyzer analyzer = new OptimizationAnalyzer(de);
analyzer.Optimize();
// Print results
Console.WriteLine("\n Best Position:");
for (int i = 0; i < lowerBounds.Length; i++)
{
Console.WriteLine(String.Format(@" x[{0}] = {1} ", i, de.BestPosition[i]));
}
Console.WriteLine(String.Format(@"Best Fitness: {0}", de.BestFitness));
}
}
}
| |
Fix test - explicitly set the NancyBootstrapperLocator.Bootstrapper | namespace Nancy.Tests.Unit
{
using Nancy.Owin;
using Xunit;
public class NancyOptionsFixture
{
private readonly NancyOptions nancyOptions;
public NancyOptionsFixture()
{
this.nancyOptions = new NancyOptions();
}
[Fact]
public void Bootstrapper_should_not_be_null()
{
this.nancyOptions.Bootstrapper.ShouldNotBeNull();
}
[Fact]
public void PerformPassThrough_should_not_be_null()
{
this.nancyOptions.PerformPassThrough.ShouldNotBeNull();
}
[Fact]
public void PerformPassThrough_delegate_should_return_false()
{
this.nancyOptions.PerformPassThrough(new NancyContext()).ShouldBeFalse();
}
}
} | namespace Nancy.Tests.Unit
{
using Nancy.Bootstrapper;
using Nancy.Owin;
using Xunit;
public class NancyOptionsFixture
{
private readonly NancyOptions nancyOptions;
public NancyOptionsFixture()
{
this.nancyOptions = new NancyOptions();
}
[Fact]
public void Bootstrapper_should_use_locator_if_not_specified()
{
// Given
var bootstrapper = new DefaultNancyBootstrapper();
NancyBootstrapperLocator.Bootstrapper = bootstrapper;
//When
//Then
this.nancyOptions.Bootstrapper.ShouldNotBeNull();
this.nancyOptions.Bootstrapper.ShouldBeSameAs(bootstrapper);
}
[Fact]
public void Bootstrapper_should_use_chosen_bootstrapper_if_specified()
{
// Given
var bootstrapper = new DefaultNancyBootstrapper();
var specificBootstrapper = new DefaultNancyBootstrapper();
NancyBootstrapperLocator.Bootstrapper = bootstrapper;
//When
this.nancyOptions.Bootstrapper = specificBootstrapper;
//Then
this.nancyOptions.Bootstrapper.ShouldNotBeNull();
this.nancyOptions.Bootstrapper.ShouldBeSameAs(specificBootstrapper);
}
[Fact]
public void PerformPassThrough_should_not_be_null()
{
this.nancyOptions.PerformPassThrough.ShouldNotBeNull();
}
[Fact]
public void PerformPassThrough_delegate_should_return_false()
{
this.nancyOptions.PerformPassThrough(new NancyContext()).ShouldBeFalse();
}
}
} |
Add extension method to handle cases of fire-and-forget async usage | // 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 osu.Framework.Logging;
namespace osu.Game.Extensions
{
public static class TaskExtensions
{
/// <summary>
/// Denote a task which is to be run without local error handling logic, where failure is not catastrophic.
/// Avoids unobserved exceptions from being fired.
/// </summary>
/// <param name="task">The task.</param>
/// <param name="logOnError">Whether errors should be logged as important, or silently ignored.</param>
public static void FireAndForget(this Task task, bool logOnError = false)
{
task.ContinueWith(t =>
{
if (logOnError)
Logger.Log($"Error running task: {t.Exception?.Message ?? "unknown"}", LoggingTarget.Runtime, LogLevel.Important);
}, TaskContinuationOptions.NotOnRanToCompletion);
}
}
}
| |
Support for calculating odd length Fletcher checksums. | using System.Diagnostics;
namespace BTDB.Buffer
{
public static class Checksum
{
public static uint CalcFletcher32(byte[] data, uint position, uint length)
{
Debug.Assert((length & 1) == 0);
length >>= 1;
uint sum1 = 0xffff;
uint sum2 = 0xffff;
while (length > 0)
{
uint tlen = length > 360 ? 360 : length;
length -= tlen;
do
{
sum1 += (uint)(data[position] + data[position + 1] * 256);
position += 2;
sum2 += sum1;
}
while (--tlen > 0);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
// Second reduction step to reduce sums to 16 bits
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
return sum2 << 16 | sum1;
}
}
} | using System.Diagnostics;
namespace BTDB.Buffer
{
public static class Checksum
{
public static uint CalcFletcher32(byte[] data, uint position, uint length)
{
var odd = (length & 1) != 0;
length >>= 1;
uint sum1 = 0xffff;
uint sum2 = 0xffff;
while (length > 0)
{
uint tlen = length > 360 ? 360 : length;
length -= tlen;
do
{
sum1 += (uint)(data[position] + data[position + 1] * 256);
position += 2;
sum2 += sum1;
}
while (--tlen > 0);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
if (odd)
{
sum1 += data[position];
sum2 += sum1;
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
// Second reduction step to reduce sums to 16 bits
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
return sum2 << 16 | sum1;
}
}
} |
Create red card by country method | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RedCard.API.Contexts;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace RedCard.API.Controllers
{
[Route("api/[controller]")]
public class StatsController : Controller
{
public StatsController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
readonly ApplicationDbContext _dbContext;
[HttpGet]
public IActionResult RedCardCountForCountry()
{
var redCardCount = _dbContext.Players
.GroupBy(player => player.Country)
.Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) })
.ToArray();
return new ObjectResult(new { redCardCountForCountry = redCardCount });
}
}
}
| |
Add partial classes for legacy retry filters. | // Copyright 2019 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.Api.Gax.Grpc;
using Grpc.Core;
using System;
namespace Google.Cloud.PubSub.V1
{
// This file contains retry filters which have been removed from the GAPIC configuration,
// but still need to be present for backward compatibility purposes.
public partial class PublisherServiceApiSettings
{
/// <summary>
/// Legacy property for a retry filter for status codes of Aborted,
/// Cancelled, DeadlineExceeded, Internal, ResourceExhausted, Unavailable and Unknown.
/// This property is no longer used in any default settings, and is only present
/// for backward compatibility purposes.
/// </summary>
[Obsolete("This property is no longer used in any settings")]
public static Predicate<RpcException> OnePlusDeliveryRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.Aborted, StatusCode.Cancelled, StatusCode.DeadlineExceeded, StatusCode.Internal, StatusCode.ResourceExhausted, StatusCode.Unavailable, StatusCode.Unknown);
}
public partial class SubscriberServiceApiSettings
{
/// <summary>
/// Legacy property for a retry filter for status codes of
/// DeadlineExceeded, Internal, ResourceExhausted and Unavailable.
/// This property is no longer used in any default settings, and is only present
/// for backward compatibility purposes.
/// </summary>
[Obsolete("This property is no longer used in any settings")]
public static Predicate<RpcException> PullRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Internal, StatusCode.ResourceExhausted, StatusCode.Unavailable);
}
}
| |
Add custom combo list item | using System.Windows.Controls;
namespace food_tracker {
public class FoodComboItem : ComboBoxItem {
public double calories { get; set; }
public double fats { get; set; }
public double saturatedFat { get; set; }
public double carbohydrates { get; set; }
public double sugar { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public string name { get; set; }
public int nutritionId { get; set; }
public FoodComboItem() : base() { }
public FoodComboItem(string name, int itemId, double cals, double fats, double satFat, double carbs, double sugars, double protein, double salt, double fibre) {
this.name = name;
this.calories = cals;
this.fats = fats;
this.salt = salt;
this.saturatedFat = satFat;
this.carbohydrates = carbs;
this.sugar = sugars;
this.protein = protein;
this.fibre = fibre;
this.nutritionId = itemId;
}
public override string ToString() {
return this.name;
}
}
} | |
Add Fixed Provider for RequestHandling | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class FixedRequestHandlerProvider : IRequestHandlerProvider
{
public FixedRequestHandlerProvider()
: this(Enumerable.Empty<IRequestHandler>())
{
}
public FixedRequestHandlerProvider(IEnumerable<IRequestHandler> controllerTypes)
{
Handlers = new List<IRequestHandler>(controllerTypes);
}
public IList<IRequestHandler> Handlers { get; }
IEnumerable<IRequestHandler> IRequestHandlerProvider.Handlers => Handlers;
}
} | |
Add too many players exception | // TooManyPlayersException.cs
// <copyright file="TooManyPlayersException.cs"> This code is protected under the MIT License. </copyright>
using System;
namespace Tron.Exceptions
{
/// <summary>
/// An exception thrown when too many players are in the game.
/// </summary>
public class TooManyPlayersException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="TooManyPlayersException" /> class.
/// </summary>
public TooManyPlayersException()
{
}
}
}
| |
Add hosting startup to SpaFallback | using Hellang.Middleware.SpaFallback;
using Microsoft.AspNetCore.Hosting;
[assembly: HostingStartup(typeof(SpaFallbackHostingStartup))]
namespace Hellang.Middleware.SpaFallback
{
public class SpaFallbackHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices(services => services.AddSpaFallback());
}
}
}
| |
Remove duplicates from sorted array II | using System;
static class Program {
static int RemoveDupes(this int[] a) {
int write = 1;
int read = 0;
bool same = false;
int count = 0;
for (int i = 1; i < a.Length; i++) {
read = i;
if (same && a[read] == a[write]) {
count++;
continue;
}
same = a[read] == a[write];
a[write++] = a[read];
}
return a.Length - count;
}
static void Main() {
int[] a = new int[] {1, 1, 1, 2, 2, 3, 3, 3};
int c = RemoveDupes(a);
for (int i = 0; i < c; i++) {
Console.Write("{0} ", a[i]);
}
Console.WriteLine();
}
}
| |
Add unit tests for RefundClient to make sure the query parameter works as expected | using Mollie.Api.Client;
using NUnit.Framework;
using System.Net.Http;
using System.Threading.Tasks;
namespace Mollie.Tests.Unit.Client {
[TestFixture]
public class RefundClientTests : BaseClientTests {
public const string defaultGetRefundResponse = @"{
""resource"": ""refund"",
""id"": ""re_4qqhO89gsT"",
""amount"": {
""currency"": ""EUR"",
""value"": ""5.95""
},
""status"": ""pending"",
""createdAt"": ""2018-03-14T17:09:02.0Z"",
""description"": ""Order #33"",
""metadata"": {
""bookkeeping_id"": 12345
},
""paymentId"": ""tr_WDqYK6vllg"",
""_links"": {
""self"": {
""href"": ""https://api.mollie.com/v2/payments/tr_WDqYK6vllg/refunds/re_4qqhO89gsT"",
""type"": ""application/hal+json""
},
""payment"": {
""href"": ""https://api.mollie.com/v2/payments/tr_WDqYK6vllg"",
""type"": ""application/hal+json""
},
""documentation"": {
""href"": ""https://docs.mollie.com/reference/v2/refunds-api/get-refund"",
""type"": ""text/html""
}
}
}";
[TestCase("payments/paymentId/refunds/refundId", null)]
[TestCase("payments/paymentId/refunds/refundId", false)]
[TestCase("payments/paymentId/refunds/refundId?testmode=true", true)]
public async Task GetRefundAsync_TestModeParameterCase_QueryStringOnlyContainsTestModeParameterIfTrue(string expectedUrl, bool? testModeParameter) {
// Given: We make a request to retrieve a payment without wanting any extra data
bool testMode = testModeParameter ?? false;
var mockHttp = this.CreateMockHttpMessageHandler(HttpMethod.Get, $"{BaseMollieClient.ApiEndPoint}{expectedUrl}", defaultGetRefundResponse);
HttpClient httpClient = mockHttp.ToHttpClient();
RefundClient refundClient = new RefundClient("abcde", httpClient);
// When: We send the request
await refundClient.GetRefundAsync("paymentId", "refundId", testmode: testMode);
// Then
mockHttp.VerifyNoOutstandingExpectation();
}
}
}
| |
Add known runtime names for .NET core. | namespace AsmResolver.DotNet
{
/// <summary>
/// Provides strings of known runtime names used in .NET Core, .NET 5.0 and later.
/// </summary>
public static class KnownRuntimeNames
{
/// <summary>
/// Indicates an application targeting the default .NET Core runtime.
/// </summary>
public const string NetCoreApp = "Microsoft.NETCore.App";
/// <summary>
/// Indicates an application targeting the Windows Desktop environment runtime.
/// </summary>
public const string WindowsDesktopApp = "Microsoft.WindowsDesktop.App";
}
}
| |
Add missing test for PG object metadata | using Marten.Testing.Documents;
using Marten.Util;
using Xunit;
namespace Marten.Testing.Schema
{
public class add_origin_Tests
{
[Fact]
public void origin_is_added_to_tables()
{
var user1 = new User { FirstName = "Jeremy" };
var user2 = new User { FirstName = "Max" };
var user3 = new User { FirstName = "Declan" };
using (var store = DocumentStore.For(ConnectionSource.ConnectionString))
{
store.Advanced.Clean.CompletelyRemoveAll();
store.BulkInsert(new User[] { user1, user2, user3 });
}
using (var store = DocumentStore.For(ConnectionSource.ConnectionString))
using (var session = store.QuerySession())
using (var cmd = session.Connection.CreateCommand())
{
var mapping = store.Schema.MappingFor(typeof(User));
cmd.CommandText = "SELECT description from pg_description " +
"join pg_class on pg_description.objoid = pg_class.oid where relname = :name";
cmd.AddParameter("name", mapping.Table.Name);
var result = (string)cmd.ExecuteScalar();
Assert.NotNull(result);
Assert.Contains(typeof(IDocumentStore).AssemblyQualifiedName, result);
}
}
}
} | |
Add Thread Queue Size Setting | using Hudl.FFmpeg.Attributes;
using Hudl.FFmpeg.Enums;
using Hudl.FFmpeg.Resources.BaseTypes;
using Hudl.FFmpeg.Settings.Attributes;
using Hudl.FFmpeg.Settings.Interfaces;
namespace Hudl.FFmpeg.Settings
{
/// <summary>
/// This option sets the maximum number of queued packets when reading from the file or device. With low latency / high
/// rate live streams, packets may be discarded if they are not read in a timely manner; raising this value can avoid
/// it.
/// </summary>
[ForStream(Type = typeof (VideoStream))]
[ForStream(Type = typeof (AudioStream))]
[Setting(Name = "thread_queue_size", IsPreDeclaration = true, ResourceType = SettingsCollectionResourceType.Input)]
public class ThreadQueueSize : ISetting
{
public ThreadQueueSize(int queueSize)
{
QueueSize = queueSize;
}
[SettingParameter]
public int QueueSize { get; set; }
}
} | |
Move database interactions into repository. This contains the actions for both days and items. | using System.Collections.Generic;
using System.Linq;
namespace food_tracker.Repository {
public class NutritionRepository {
private readonly IMyEntitiesContext _db = null;
public NutritionRepository(IMyEntitiesContext db) {
_db = db;
}
public WholeDay GetDay(string id) {
var day = Md5Hashing.CreateMD5(id);
var dayExists = _db.Days.FirstOrDefault(x => x.WholeDayId == day);
return dayExists = dayExists ?? null;
}
public void AddDay(WholeDay day) {
_db.Days.Add(day);
_db.SaveChanges();
}
public IEnumerable<NutritionItem> GetItems(string id) {
return _db.Nutrition.Where(x => x.dayId == id).ToList();
}
public IEnumerable<NutritionItem> GetItemsUnique() {
// cost involved with below query, with buffering all the data before returning anything.
return _db.Nutrition.GroupBy(x => x.name).Select(group => group.FirstOrDefault()).ToArray().Distinct().OrderBy(o => o.dateTime).ThenBy(b => b.name);
}
public NutritionItem GetItem(int id) {
return _db.Nutrition.FirstOrDefault(x => x.NutritionItemId == id);
}
public void AddItem(NutritionItem item) {
_db.Nutrition.Add(item);
_db.SaveChanges();
}
public bool RemoveItem(int id) {
var entity = _db.Nutrition.FirstOrDefault(x => x.NutritionItemId == id);
if(entity != null) {
_db.Nutrition.Remove(entity);
_db.SaveChanges();
return true;
}
return false;
}
}
}
| |
Remove TFM requirement from API | // 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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService
{
/// <summary>
/// Return the set of direct Project and Package References for the given project. This
/// is used to get the initial state of the TreatAsUsed attribute for each reference.
/// </summary>
Task<ImmutableArray<ProjectSystemReferenceInfo>> GetProjectReferencesAsync(
string projectPath,
string targetFrameworkMoniker,
CancellationToken cancellationToken);
/// <summary>
/// Updates the project’s references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
/// <returns>True, if the reference was updated.</returns>
Task<bool> TryUpdateReferenceAsync(
string projectPath,
string targetFrameworkMoniker,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken cancellationToken);
}
}
| // 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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService
{
/// <summary>
/// Return the set of direct Project and Package References for the given project. This
/// is used to get the initial state of the TreatAsUsed attribute for each reference.
/// </summary>
Task<ImmutableArray<ProjectSystemReferenceInfo>> GetProjectReferencesAsync(
string projectPath,
CancellationToken cancellationToken);
/// <summary>
/// Updates the project’s references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
/// <returns>True, if the reference was updated.</returns>
Task<bool> TryUpdateReferenceAsync(
string projectPath,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken cancellationToken);
}
}
|
Fix FindByAccessibilityId bug where you were not to find a subelement of an element in a dom | using System.Collections.ObjectModel;
namespace OpenQA.Selenium.Appium.Interfaces
{
internal interface IFindByAccessibilityId
{
/// <summary>
/// Finds the first of elements that match the Accessibility Id selector supplied
/// </summary>
/// <param name="selector">an Accessibility Id selector</param>
/// <returns>IWebElement object so that you can interact that object</returns>
IWebElement FindElementByAccessibilityId(string selector);
/// <summary>
/// Finds a list of elements that match the Accessibility Id selector supplied
/// </summary>
/// <param name="selector">an Accessibility Id selector</param>
/// <returns>IWebElement object so that you can interact that object</returns>
ReadOnlyCollection<IWebElement> FindElementsByAccessibilityId(string selector);
}
}
| |
Move a small part of current | using System;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Composing
{
/// <summary>
/// Provides a static service locator for most singletons.
/// </summary>
/// <remarks>
/// <para>This class is initialized with the container in UmbracoApplicationBase,
/// right after the container is created in UmbracoApplicationBase.HandleApplicationStart.</para>
/// <para>Obviously, this is a service locator, which some may consider an anti-pattern. And yet,
/// practically, it works.</para>
/// </remarks>
public static class CurrentCore
{
private static IFactory _factory;
private static ILogger _logger;
private static IProfiler _profiler;
private static IProfilingLogger _profilingLogger;
/// <summary>
/// Gets or sets the factory.
/// </summary>
public static IFactory Factory
{
get
{
if (_factory == null) throw new InvalidOperationException("No factory has been set.");
return _factory;
}
set
{
if (_factory != null) throw new InvalidOperationException("A factory has already been set.");
// if (_configs != null) throw new InvalidOperationException("Configs are unlocked.");
_factory = value;
}
}
internal static bool HasFactory => _factory != null;
#region Getters
public static ILogger Logger
=> _logger ?? (_logger = _factory?.TryGetInstance<ILogger>() ?? throw new Exception("TODO Fix")); //?? new DebugDiagnosticsLogger(new MessageTemplates()));
public static IProfiler Profiler
=> _profiler ?? (_profiler = _factory?.TryGetInstance<IProfiler>()
?? new LogProfiler(Logger));
public static IProfilingLogger ProfilingLogger
=> _profilingLogger ?? (_profilingLogger = _factory?.TryGetInstance<IProfilingLogger>())
?? new ProfilingLogger(Logger, Profiler);
#endregion
}
}
| |
Fix Windows file format issues | /*
Copyright © Iain McDonald 2010-2019
This file is part of Decider.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Decider.Csp.BaseTypes;
namespace Decider.Csp.Integer
{
public class MetaExpressionInteger : ExpressionInteger, IMetaExpression<int>
{
private readonly IList<IVariable<int>> support;
IList<IVariable<int>> IMetaExpression<int>.Support
{
get { return this.support; }
}
public MetaExpressionInteger(Expression<int> left, Expression<int> right, IEnumerable<IVariable<int>> support)
: base(left, right)
{
this.support = support.ToList();
}
public MetaExpressionInteger(int integer, IEnumerable<IVariable<int>> support)
: base(integer)
{
this.support = support.ToList();
}
internal MetaExpressionInteger(VariableInteger variable,
Func<ExpressionInteger, ExpressionInteger, int> evaluate,
Func<ExpressionInteger, ExpressionInteger, Bounds<int>> evaluateBounds,
Func<ExpressionInteger, ExpressionInteger, Bounds<int>, ConstraintOperationResult> propagator,
IEnumerable<IVariable<int>> support)
: base(variable, evaluate, evaluateBounds, propagator)
{
this.support = support.ToList();
}
}
}
| |
Add unit tests for HtmlTemplatePrivider | namespace Host.UnitTests.Conversion
{
using Crest.Host.Conversion;
using NUnit.Framework;
[TestFixture]
public sealed class HtmlTemplateProviderTests
{
[Test]
public void ContentLocationShouldReturnTheLocationAfterTheBodyTag()
{
var provider = new HtmlTemplateProvider();
string beforeLocation = provider.Template.Substring(0, provider.ContentLocation);
Assert.That(beforeLocation, Does.EndWith("<body>"));
}
[Test]
public void HintTextShouldReturnANonEmptyValue()
{
var provider = new HtmlTemplateProvider();
Assert.That(provider.HintText, Is.Not.Null.Or.Empty);
}
[Test]
public void TemplateShouldReturnANonEmptyValue()
{
var provider = new HtmlTemplateProvider();
Assert.That(provider.Template, Is.Not.Null.Or.Empty);
}
}
}
| |
Add Microsoft Graph API calls | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace SampleAADV2Bot.Helpers
{
public class MeetingRoom
{
public string DisplayName { get; set; }
public string LocationEmailAddress { get; set; }
}
public class GraphHelper
{
public string Token { get; set; }
public async Task<string> GetDisplayName()
{
try
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + this.Token);
var userresponse = await client.GetAsync("https://graph.microsoft.com/beta/me/");
dynamic userInfo = JObject.Parse(await userresponse.Content.ReadAsStringAsync());
return userInfo.displayName;
}
catch (Exception)
{
throw;
}
}
public async Task<List<MeetingRoom>> GetMeetingRoomSuggestions()
{
try
{
List<MeetingRoom> suggestions = new List<MeetingRoom>();
HttpClient client = new HttpClient();
var meetingresponse = await client.PostAsync("https://graph.microsoft.com/beta/me/findMeetingTimes", new StringContent(String.Empty));
dynamic meetingTimes = JObject.Parse(await meetingresponse.Content.ReadAsStringAsync());
foreach (var item in meetingTimes.meetingTimeSuggestions[0].locations)
{
// Add only locations with an email address -> meeting rooms
if (!String.IsNullOrEmpty(item.locationEmailAddress.ToString()))
suggestions.Add(new MeetingRoom()
{
DisplayName = item.displayName,
LocationEmailAddress = item.locationEmailAddress
});
}
return suggestions;
}
catch (Exception)
{
throw;
}
}
}
} | |
Add StackOverflow InteractiveWindow test for .NET Core | // 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.
extern alias InteractiveHost;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostCoreTests : AbstractInteractiveHostTests
{
internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Core;
internal override bool UseDefaultInitializationFile => false;
[Fact]
public async Task StackOverflow()
{
var process = Host.TryGetProcess();
await Execute(@"
int goo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
{
return goo(0,1,2,3,4,5,6,7,8,9) + goo(0,1,2,3,4,5,6,7,8,9);
}
goo(0,1,2,3,4,5,6,7,8,9)
");
var output = await ReadOutputToEnd();
Assert.Equal("", output);
// Hosting process exited with exit code ###.
var errorOutput = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOutput.StartsWith("Stack overflow.\n"));
Assert.True(errorOutput.EndsWith(string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, process!.ExitCode)));
await Execute(@"1+1");
output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output.ToString());
}
}
}
| |
Change prefab for different categories. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _prefab;
private Stack<GameObject> _pool;
public GameObject GetGameObject()
{
if (_pool != null)
{
if (_pool.Count > 0)
return _pool.Pop();
else
return GameObject.Instantiate<GameObject>(_prefab);
}
else
{
_pool = new Stack<GameObject>();
return GameObject.Instantiate<GameObject>(_prefab);
}
}
public void Put(GameObject obj)
{
if (_pool == null)
_pool = new Stack<GameObject>();
_pool.Push(obj);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _prefab;
private Stack<GameObject> _pool;
public GameObject prefab
{
set {
_prefab = value;
}
}
//TODO: Add possibility to differentiate between prefabs
public GameObject GetGameObject()
{
if (_pool != null)
{
if (_pool.Count > 0)
return _pool.Pop();
else
return GameObject.Instantiate<GameObject>(_prefab);
}
else
{
_pool = new Stack<GameObject>();
return GameObject.Instantiate<GameObject>(_prefab);
}
}
public void Put(GameObject obj)
{
if (_pool == null)
_pool = new Stack<GameObject>();
_pool.Push(obj);
}
}
|
Add mania player test scene | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Mania.Tests
{
public class TestScenePlayer : PlayerTestScene
{
public TestScenePlayer()
: base(new ManiaRuleset())
{
}
}
}
| |
Add code example for wiki. | using System;
using EOpt.Math.Optimization;
using EOpt.Math;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Func<double[], double> func = (x) => 20 + (x[0] * x[0] - 10 * Math.Cos(2 * Math.PI * x[0])) +
(x[1] * x[1] - 10 * Math.Cos(2 * Math.PI * x[1]));
IOptimizer[] opts = {
new BBBCOptimizer(),
new FireworksOptimizer(),
new GEMOptimizer()
};
// Distance between points need for Fireworks method.
// It is squared Euclidean distance.
Func<PointND, PointND, double> distance = (a, b) => (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
object[] parameters = {
new BBBCParams(20, 100, 0.4, 0.5),
new FireWorksParams(20, 50, distance, 20),
new GEMParams(1, 20, 50, 2 * Math.Sqrt(2), 100)
};
double[] constr1 = { -5.12, -5.12 };
double[] constr2 = { 5.12, 5.12 };
GeneralParams param = new GeneralParams(func, constr1, constr2);
string[] names =
{
"BBBC",
"Fireworks",
"GEM"
};
for (int i = 0; i < opts.Length; i++)
{
opts[i].InitializeParameters(parameters[i]);
opts[i].Optimize(param);
Console.WriteLine($"Method: {names[i]}.");
Console.WriteLine(opts[i].Solution);
Console.WriteLine();
}
Console.WriteLine("Complete");
Console.ReadKey();
}
}
}
| |
Implement the longest common pattern | using System;
using Algorithms.Sorting;
namespace Algorithms.Strings.Search
{
public class LongestCommonPattern
{
public String Find(String s1, String s2)
{
int N = s1.Length;
String[] a = new String[N];
for (var i = 0; i < N; ++i)
{
a[i] = s1.Substring(i, N);
}
QuickSort.Sort(a);
String lcs = "";
for (var i = 0; i < N; ++i)
{
String s = LongestCommonString(a[i], s2);
if (s.Length > lcs.Length)
{
lcs = s;
}
}
return lcs;
}
public String LongestCommonString(String s, String pat)
{
int J = 0;
for (var i = 0; i < s.Length; ++i)
{
for (var j = 0; j < pat.Length; ++j)
{
if (i+j >= s.Length || s[i + j] != pat[j])
{
J = Math.Max(J, j);
break;
}
}
}
return pat.Substring(0, J);
}
}
} | |
Add test scene for previewing Torus alternates | // 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.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneOsuFont : OsuTestScene
{
private OsuSpriteText spriteText;
private readonly BindableBool useAlternates = new BindableBool();
private readonly Bindable<FontWeight> weight = new Bindable<FontWeight>(FontWeight.Regular);
[BackgroundDependencyLoader]
private void load()
{
Child = spriteText = new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
RelativeSizeAxes = Axes.X,
AllowMultiline = true,
};
}
protected override void LoadComplete()
{
base.LoadComplete();
useAlternates.BindValueChanged(_ => updateFont());
weight.BindValueChanged(_ => updateFont(), true);
}
private void updateFont()
{
FontUsage usage = useAlternates.Value ? OsuFont.TorusAlternate : OsuFont.Torus;
spriteText.Font = usage.With(size: 40, weight: weight.Value);
}
[Test]
public void TestTorusAlternates()
{
AddStep("set all ASCII letters", () => spriteText.Text = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz");
AddStep("set all alternates", () => spriteText.Text = @"A Á Ă Â Ä À Ā Ą Å Ã
Æ B D Ð Ď Đ E É Ě Ê
Ë Ė È Ē Ę F G Ğ Ģ Ġ
H I Í Î Ï İ Ì Ī Į K
Ķ O Œ P Þ Q R Ŕ Ř Ŗ
T Ŧ Ť Ţ Ț V W Ẃ Ŵ Ẅ
Ẁ X Y Ý Ŷ Ÿ Ỳ a á ă
â ä à ā ą å ã æ b d
ď đ e é ě ê ë ė è ē
ę f g ğ ģ ġ k ķ m n
ń ň ņ ŋ ñ o œ p þ q
t ŧ ť ţ ț u ú û ü ù
ű ū ų ů w ẃ ŵ ẅ ẁ x
y ý ŷ ÿ ỳ");
AddToggleStep("toggle alternates", alternates => useAlternates.Value = alternates);
addSetWeightStep(FontWeight.Light);
addSetWeightStep(FontWeight.Regular);
addSetWeightStep(FontWeight.SemiBold);
addSetWeightStep(FontWeight.Bold);
void addSetWeightStep(FontWeight newWeight) => AddStep($"set weight {newWeight}", () => weight.Value = newWeight);
}
}
}
| |
Load cadence constraint file to PCB-Investigator | //Synchronous template
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 29.06.2016
// Autor Guenther
//
// Empty template to fill for synchronous script.
//-----------------------------------------------------------------------------------
// GUID newScript_636028110537710508
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
using System.Diagnostics;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
public void Execute(IPCBIWindow parent)
{
//your code here
ProcessStartInfo psi = new ProcessStartInfo();
string realPCBI = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + System.IO.Path.DirectorySeparatorChar + "EasyLogix" + System.IO.Path.DirectorySeparatorChar + "PCB-Investigator" + Path.DirectorySeparatorChar + "Scripts" + Path.DirectorySeparatorChar;
psi.FileName = realPCBI + @"\CadanceNetGroup2PCBI.exe";
psi.Arguments = parent.GetODBJobDirectory() + " -step " + parent.GetCurrentStep().Name;
Process.Start(psi);
parent.UpdateView();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.