Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix weaver project search path in Linux | using System;
using System.IO;
using System.Linq;
public partial class Processor
{
public string WeaverAssemblyPath;
public bool FoundWeaverProjectFile;
public virtual void FindWeaverProjectFile()
{
GetValue();
if (WeaverAssemblyPath == null)
{
Logger.LogDebug("No Weaver project file found.");
FoundWeaverProjectFile = false;
}
else
{
Logger.LogDebug(string.Format("Weaver project file found at '{0}'.", WeaverAssemblyPath));
FoundWeaverProjectFile = true;
}
}
void GetValue()
{
var weaversBin = Path.Combine(SolutionDirectory, @"Weavers\bin");
if (Directory.Exists(weaversBin))
{
WeaverAssemblyPath = Directory.EnumerateFiles(weaversBin, "Weavers.dll", SearchOption.AllDirectories)
.OrderByDescending(File.GetLastWriteTime)
.FirstOrDefault();
return;
}
//Hack for ncrunch
//<Reference Include="...\AppData\Local\NCrunch\2544\1\Integration\Weavers\bin\Debug\Weavers.dll" />
WeaverAssemblyPath = References.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault(x => x.EndsWith("Weavers.dll"));
}
} | using System;
using System.IO;
using System.Linq;
public partial class Processor
{
public string WeaverAssemblyPath;
public bool FoundWeaverProjectFile;
public virtual void FindWeaverProjectFile()
{
GetValue();
if (WeaverAssemblyPath == null)
{
Logger.LogDebug("No Weaver project file found.");
FoundWeaverProjectFile = false;
}
else
{
Logger.LogDebug(string.Format("Weaver project file found at '{0}'.", WeaverAssemblyPath));
FoundWeaverProjectFile = true;
}
}
void GetValue()
{
var weaversBin = Path.Combine(SolutionDirectory, "Weavers", "bin");
if (Directory.Exists(weaversBin))
{
WeaverAssemblyPath = Directory.EnumerateFiles(weaversBin, "Weavers.dll", SearchOption.AllDirectories)
.OrderByDescending(File.GetLastWriteTime)
.FirstOrDefault();
return;
}
//Hack for ncrunch
//<Reference Include="...\AppData\Local\NCrunch\2544\1\Integration\Weavers\bin\Debug\Weavers.dll" />
WeaverAssemblyPath = References.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault(x => x.EndsWith("Weavers.dll"));
}
} |
Add interface for main character animations |
public interface IPlayerAnimator
{
void PlayIdleAnimation();
void PlayRunAnimation();
void PlayJumpAnimation();
void PlayAttackAnimation();
void PlayRunAttackAnimation();
void PlayJumpAttackAnimation();
bool ExitTimeReached();
} | |
Test matching composite type handling | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.Testing
{
public class TestSceneTestingExtensions : FrameworkTestScene
{
[Test]
public void TestChildrenOfTypeMatchingComposite()
{
Container container = null;
AddStep("create children", () =>
{
Child = container = new Container { Child = new Box() };
});
AddAssert("ChildrenOfType returns 2 children", () => container.ChildrenOfType<Drawable>().Count() == 2);
}
}
}
| |
Create a case insensitive expando object | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataReaderExtensions.cs" company="Bosbec AB">
// Copyright © Bosbec AB 2014
// </copyright>
// <summary>
// Defines extension methods for data readers.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Bosbec
{
/// <summary>
/// Defines extension methods for data readers.
/// </summary>
public static class DataReaderExtensions
{
/// <summary>
/// Create a dynamic object from the values contained within a
/// data reader.
/// </summary>
/// <param name="reader">
/// The reader.
/// </param>
/// <returns>
/// The dynamic object.
/// </returns>
public static dynamic ToDynamic(this IDataReader reader)
{
var values = new Dictionary<string, object>();
for (var i = 0; i < reader.FieldCount; i++)
{
var name = reader.GetName(i);
var value = reader[i];
values.Add(name, value);
}
return new CaseInsensitiveExpandoObject(values);
}
}
}
| |
Add a new baked texure module methid to support baked texturing mesh avatars | ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
| ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
void UpdateMeshAvatar(UUID id);
}
}
|
Add first attempt of the Git unit tests | using System;
using System.IO;
using Ionic.Zip;
using NUnit.Framework;
namespace MSBuild.Version.Tasks.Tests
{
[TestFixture]
public class GitVersionFileTest
{
[SetUp]
public void SetUp()
{
// extract the repositories in the 'Git.zip' file into the 'temp' folder
using (ZipFile zipFile = ZipFile.Read(Path.Combine(RepositoriesDirectory, "Git.zip")))
{
foreach (ZipEntry zipEntry in zipFile)
{
zipEntry.Extract(TempDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
}
[TearDown]
public void TearDown()
{
// delete the 'temp' folder
Directory.Delete(TempDirectory, true);
}
[Test]
public void Execute_WriteRevision_ShouldWriteRevision()
{
Execute("Revision.tmp", "Git1Revision.txt", "git1");
Assert.AreEqual(ReadFirstLine("Git1Revision.txt"), "2");
Execute("Revision.tmp", "Git2Revision.txt", "git2");
Assert.AreEqual(ReadFirstLine("Git2Revision.txt"), "4");
Execute("Revision.tmp", "Git3Revision.txt", "git3");
Assert.AreEqual(ReadFirstLine("Git3Revision.txt"), "2");
}
private static readonly string TemplatesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data\\Templates");
private static readonly string RepositoriesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data\\Repositories");
private static readonly string TempDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data\\Temp");
private static void Execute(string templateFile, string destinationFile, string workingDirectory)
{
GitVersionFile gitVersionFile = new GitVersionFile
{
TemplateFile = Path.Combine(TemplatesDirectory, templateFile),
DestinationFile = Path.Combine(TempDirectory, destinationFile),
WorkingDirectory = Path.Combine(TempDirectory, workingDirectory)
};
gitVersionFile.Execute();
}
private static string ReadFirstLine(string fileName)
{
using (StreamReader streamReader = new StreamReader(Path.Combine(TempDirectory, fileName)))
{
return streamReader.ReadLine();
}
}
}
}
| |
Add tracingheader for support Diagnostics | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DotNetCore.CAP.Diagnostics
{
public class TracingHeaders : IEnumerable<KeyValuePair<string, string>>
{
private List<KeyValuePair<string, string>> _dataStore;
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _dataStore.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string name, string value)
{
if (_dataStore == null)
{
_dataStore = new List<KeyValuePair<string, string>>();
}
_dataStore.Add(new KeyValuePair<string, string>(name, value));
}
public bool Contains(string name)
{
return _dataStore != null && _dataStore.Any(x => x.Key == name);
}
public void Remove(string name)
{
_dataStore?.RemoveAll(x => x.Key == name);
}
public void Cleaar()
{
_dataStore?.Clear();
}
}
} | |
Add unit test for SecurityKeyEntropyMode. | // 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.ServiceModel.Security;
using Infrastructure.Common;
using Xunit;
public static class SecurityKeyEntropyModeTest
{
[WcfTheory]
[InlineData(SecurityKeyEntropyMode.ClientEntropy)]
[InlineData(SecurityKeyEntropyMode.ServerEntropy)]
[InlineData(SecurityKeyEntropyMode.CombinedEntropy)]
public static void Set_EnumMembers(SecurityKeyEntropyMode skem)
{
SecurityKeyEntropyMode entropyMode = skem;
Assert.Equal(skem, entropyMode);
}
[WcfTheory]
[InlineData(0, SecurityKeyEntropyMode.ClientEntropy)]
[InlineData(1, SecurityKeyEntropyMode.ServerEntropy)]
[InlineData(2, SecurityKeyEntropyMode.CombinedEntropy)]
public static void TypeConvert_EnumToInt(int value, SecurityKeyEntropyMode sem)
{
Assert.Equal(value, (int)sem);
}
}
| |
Add failing test coverage of loading with an unavailable 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.IO;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Rulesets;
using osu.Game.Tests;
namespace osu.Game.Tournament.Tests.NonVisual
{
public class DataLoadTest : TournamentHostTest
{
[Test]
public void TestUnavailableRuleset()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(TestUnavailableRuleset)))
{
try
{
var osu = new TestTournament();
LoadTournament(host, osu);
var storage = osu.Dependencies.Get<Storage>();
Assert.That(storage.GetFullPath("."), Is.EqualTo(Path.Combine(host.Storage.GetFullPath("."), "tournaments", "default")));
}
finally
{
host.Exit();
}
}
}
public class TestTournament : TournamentGameBase
{
[BackgroundDependencyLoader]
private void load()
{
Ruleset.Value = new RulesetInfo(); // not available
}
}
}
}
| |
Add an ad-hoc way to provide dependency to children | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// A <see cref="Container"/> which providing ad-hoc dependencies to the child drawables.
/// <para>
/// To provide a dependency, specify the dependency type to <see cref="Types"/>, then specify the dependency value to either <see cref="Values"/> or <see cref="Container{Drawable}.Children"/>.
/// For each type specified in <see cref="Types"/>, the first value compatible with the type is selected and provided to the children.
/// </para>
/// </summary>
/// <remarks>
/// The <see cref="Types"/> and values of the dependencies must be set while this <see cref="DependencyProvidingContainer"/> is not loaded.
/// </remarks>
public class DependencyProvidingContainer : Container
{
/// <summary>
/// The types of the dependencies provided to the children.
/// </summary>
// TODO: should be an init-only property when C# 9
public Type[] Types { get; set; } = Array.Empty<Type>();
/// <summary>
/// The dependency values provided to the children.
/// </summary>
public object[] Values { get; set; } = Array.Empty<object>();
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencyContainer = new DependencyContainer(base.CreateChildDependencies(parent));
foreach (var type in Types)
{
object value = Values.FirstOrDefault(v => type.IsInstanceOfType(v)) ??
Children.FirstOrDefault(d => type.IsInstanceOfType(d)) ??
throw new InvalidOperationException($"The type {type} is specified in this {nameof(DependencyProvidingContainer)}, but no corresponding value is provided.");
dependencyContainer.CacheAs(type, value);
}
return dependencyContainer;
}
}
}
| |
Add tests for new extensionmethods | using Contentful.Core.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Contentful.Core.Tests.Extensions
{
public class JTokenExtensionsTests
{
[Fact]
public void JTokenIsNullShouldReturnTrueForNullValue()
{
//Arrange
JToken token = null;
//Act
var res = token.IsNull();
//Assert
Assert.True(res);
}
[Fact]
public void JTokenIsNullShouldReturnTrueForNullType()
{
//Arrange
string json = @"
{
'test': null
}";
//Act
var jObject = JObject.Parse(json);
var res = jObject["test"].IsNull();
//Assert
Assert.True(res);
}
[Theory]
[InlineData(null, 0)]
[InlineData(13, 13)]
[InlineData(896, 896)]
[InlineData(-345, -345)]
public void ParsingIntValuesShouldYieldCorrectResult(int? val, int exptected)
{
//Arrange
var token = new JObject(new JProperty("val", val))["val"];
//Act
var res = token.ToInt();
//Assert
Assert.Equal(exptected, res);
}
[Theory]
[InlineData(null, null)]
[InlineData(13, 13)]
[InlineData(896, 896)]
[InlineData(-345, -345)]
public void ParsingNullableIntValuesShouldYieldCorrectResult(int? val, int? exptected)
{
//Arrange
var token = new JObject(new JProperty("val", val))["val"];
//Act
var res = token.ToNullableInt();
//Assert
Assert.Equal(exptected, res);
}
}
}
| |
Add collection to array Newtonsoft.Json based JSON converter | using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Marten.Util
{
/// <summary>
/// Serialize collection type property to JSON array using a custom Newtonsoft.Json JsonConverter
/// Note that without using custom `JsonConverter`, `Newtonsoft.Json` stores it as $type and $value.
/// Or you may need to resort to `Newtonsoft.Json.TypeNameHandling.None` which has its own side-effects
/// </summary>
/// <typeparam name="T">Type of the collection</typeparam>
public class CollectionToArrayJsonConverter<T> : JsonConverter
{
private readonly List<Type> _types = new List<Type>
{
typeof(ICollection<T>),
typeof(IReadOnlyCollection<T>),
typeof(IEnumerable<T>),
typeof(T[])
};
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var o = value as IEnumerable<T>;
serializer.Serialize(writer, o?.ToArray());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<List<T>>(reader);
}
public override bool CanConvert(Type objectType)
{
return _types.Contains(objectType);
}
}
} | |
Fix visibility of internal extensions type | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Net.Sockets
{
public static class IPAddressExtensions
{
public static IPAddress Snapshot(this IPAddress original)
{
switch (original.AddressFamily)
{
case AddressFamily.InterNetwork:
return new IPAddress(original.GetAddressBytes());
case AddressFamily.InterNetworkV6:
return new IPAddress(original.GetAddressBytes(), (uint)original.ScopeId);
}
throw new InternalException();
}
public static long GetAddress(this IPAddress thisObj)
{
byte[] addressBytes = thisObj.GetAddressBytes();
Debug.Assert(addressBytes.Length == 4);
return (long)BitConverter.ToInt32(addressBytes, 0);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Net.Sockets
{
internal static class IPAddressExtensions
{
public static IPAddress Snapshot(this IPAddress original)
{
switch (original.AddressFamily)
{
case AddressFamily.InterNetwork:
return new IPAddress(original.GetAddressBytes());
case AddressFamily.InterNetworkV6:
return new IPAddress(original.GetAddressBytes(), (uint)original.ScopeId);
}
throw new InternalException();
}
public static long GetAddress(this IPAddress thisObj)
{
byte[] addressBytes = thisObj.GetAddressBytes();
Debug.Assert(addressBytes.Length == 4);
return (long)BitConverter.ToInt32(addressBytes, 0);
}
}
}
|
Add Chat View - omitted before | <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Michelangelo Web Chat</title>
<link href='http://fonts.googleapis.com/css?family=Yesteryear' rel='stylesheet' type='text/css'/>
<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/http-requester.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="~/Scripts/class.js"></script>
<script src="~/Scripts/ui.js"></script>
<script src="~/Scripts/persister.js"></script>
<script src="~/Scripts/controller.js"></script>
<link href="~/Content/style.css" rel="stylesheet" />
</head>
<body>
<div id="wrapper">
<header>
<h1>Michelangelo Web Chat</h1>
</header>
<div id="content">
</div>
</div>
</body>
</html>
| |
Add test for temporary directory | using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Meziantou.Framework.Tests
{
public class TemporaryDirectoryTests
{
[Fact]
public void CreateInParallel()
{
const int Iterations = 100;
var dirs = new TemporaryDirectory[Iterations];
Parallel.For(0, Iterations, new ParallelOptions { MaxDegreeOfParallelism = 50 }, i =>
{
dirs[i] = TemporaryDirectory.Create();
});
try
{
Assert.Equal(Iterations, dirs.DistinctBy(dir => dir.FullPath).Count());
foreach (var dir in dirs)
{
Assert.All(dirs, dir => Assert.True(Directory.Exists(dir.FullPath)));
}
}
finally
{
foreach (var item in dirs)
{
item?.Dispose();
}
}
}
}
}
| |
Add helper class used to deserialize JSON. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace WundergroundClient.Autocomplete
{
[DataContract]
internal class RawAutocompleteResult
{
[DataMember] internal RawResult[] RESULTS;
}
[DataContract]
internal class RawResult
{
[DataMember] internal String name;
[DataMember] internal String type;
[DataMember] internal String l;
// Hurricane Fields
[DataMember] internal String date;
[DataMember] internal String strmnum;
[DataMember] internal String basin;
[DataMember] internal String damage;
[DataMember] internal String start_epoch;
[DataMember] internal String end_epoch;
[DataMember] internal String sw_lat;
[DataMember] internal String sw_lon;
[DataMember] internal String ne_lat;
[DataMember] internal String ne_lon;
[DataMember] internal String maxcat;
// City Fields
[DataMember] internal String c;
[DataMember] internal String zmw;
[DataMember] internal String tz;
[DataMember] internal String tzs;
[DataMember] internal String ll;
[DataMember] internal String lat;
[DataMember] internal String lon;
}
} | |
Add the interface for the map manager | using System;
using System.Collections.Generic;
namespace FierceGalaxyInterface.MapModule
{
/// <summary>
/// The MapManager load/save the map from/to the disk
/// </summary>
public interface IMapManager
{
IList<String> MapsName { get; }
IReadOnlyMap LoadMap(String mapName);
void SaveMap(IReadOnlyMap map);
}
}
| |
Add stress test of EventHandler | using System;
#if NUNIT
using NUnit.Framework;
using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using TestMethodAttribute = NUnit.Framework.TestCaseAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using Ooui;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Tests
{
[TestClass]
public class EventTargetStressTests
{
[TestMethod]
public void LotsOfThreads ()
{
var input = new Input ();
Parallel.ForEach (Enumerable.Range (0, 100), _ => StressTestInput (input));
}
void StressTestInput (Input input)
{
var div = new Div (input);
var changeCount = 0;
var clickCount = 0;
void Input_Change (object sender, TargetEventArgs e)
{
changeCount++;
}
void Div_MessageSent (Message m)
{
if (m.Key == "click")
clickCount++;
}
input.Change += Input_Change;
div.MessageSent += Div_MessageSent;
var sw = new Stopwatch ();
sw.Start ();
while (sw.ElapsedMilliseconds < 1000) {
var t = sw.Elapsed.ToString ();
input.Receive (Message.Event (input.Id, "change", t));
var b = new Button ("Click");
input.AppendChild (b);
b.Send (Message.Event (b.Id, "click"));
input.RemoveChild (b);
}
input.Change -= Input_Change;
div.RemoveChild (input);
div.MessageSent -= Div_MessageSent;
Assert.IsTrue (changeCount > 0);
Assert.IsTrue (clickCount > 0);
}
}
}
| |
Add file missing in build | using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
namespace NUnit.VisualStudio.TestAdapter.Tests
{
class FakeTestExecutionRecorder : ITestExecutionRecorder
{
#region Constructor
public FakeTestExecutionRecorder()
{
RecordResultCalls = 0;
SendMessageCalls = 0;
LastMessageLevel = (LastMessageLevel) - 1;
LastMessage = null;
LastResult = null;
}
#endregion
#region Properties
public int RecordResultCalls { get; private set; }
public int SendMessageCalls { get; private set; }
public TestResult LastResult { get; private set; }
public TestMessageLevel LastMessageLevel { get; private set; }
public string LastMessage { get; private set; }
#endregion
#region ITestExecutionRecorder
public void RecordStart(TestCase testCase)
{
throw new NotImplementedException();
}
public void RecordResult(TestResult testResult)
{
RecordResultCalls++;
LastResult = testResult;
}
public void RecordEnd(TestCase testCase, TestOutcome outcome)
{
throw new NotImplementedException();
}
public void RecordAttachments(IList<AttachmentSet> attachmentSets)
{
throw new NotImplementedException();
}
#endregion
#region IMessageLogger
public void SendMessage(TestMessageLevel testMessageLevel, string message)
{
SendMessageCalls++;
LastMessageLevel = testMessageLevel;
LastMessage = message;
}
#endregion
}
}
| |
Add Test to check GaugeLogMetrics log number of Rejections correctly | using System;
using Hudl.Mjolnir.Events;
using Hudl.Mjolnir.External;
using Moq;
using Xunit;
namespace Hudl.Mjolnir.Tests.Events
{
public class GaugeLogMetricsTests
{
[Fact]
public void RejectionsLoggedInGaugeCorrectly()
{
var mockLogFactory = new Mock<IMjolnirLogFactory>();
var mockLogger = new Mock<IMjolnirLog<GaugeLogMetrics>>();
mockLogFactory.Setup(i => i.CreateLog<GaugeLogMetrics>()).Returns(mockLogger.Object);
var gaugeLogMetrics = new GaugeLogMetrics(mockLogFactory.Object);
Func<string, int, bool> logMessageCheck = (s, i) =>
{
var containsRejections = s.Contains("BulkheadRejections") && s.Contains($"Rejections={i}");
return containsRejections;
};
gaugeLogMetrics.RejectedByBulkhead("test", "test-command");
gaugeLogMetrics.RejectedByBulkhead("test", "test-command");
gaugeLogMetrics.RejectedByBulkhead("test", "test-command");
gaugeLogMetrics.BulkheadGauge("test", "test", 2, 0);
gaugeLogMetrics.RejectedByBulkhead("test", "test-command");
gaugeLogMetrics.BulkheadGauge("test", "test", 2, 0);
mockLogger.Verify(i => i.Debug(It.Is<string>(s => logMessageCheck(s, 3))), Times.Once);
mockLogger.Verify(i => i.Debug(It.Is<string>(s => logMessageCheck(s, 1))), Times.Once);
}
}
} | |
Fix typo in the documentation | using System;
using SampSharp.GameMode.World;
namespace SampSharp.GameMode.SAMP.Commands
{
/// <summary>
/// A Permission checker is used to check if a player
/// is allowed to use a specific command.
///
/// Every class that implement this interface
/// should create parameter-less constructor or let
/// the compiler create one
/// </summary>
public interface IPermissionChecker
{
/// <summary>
/// The message that the user should see when
/// he doesn't have the permission to use the command.
///
/// If null the default SA-MP message will be used.
/// </summary>
string Message { get; }
/// <summary>
/// Called when a user tries to use a command
/// that require permission.
/// </summary>
/// <param name="player">The player that has tried to execute the command</param>
/// <returns>Return true if the player passed as argument is allowed to use the command, False otherwise.</returns>
bool Check(GtaPlayer player);
}
} | using System;
using SampSharp.GameMode.World;
namespace SampSharp.GameMode.SAMP.Commands
{
/// <summary>
/// A Permission checker is used to check if a player
/// is allowed to use a specific command.
///
/// Every class that implement this interface
/// should have a parameter-less constructor or let
/// the compiler create one
/// </summary>
public interface IPermissionChecker
{
/// <summary>
/// The message that the user should see when
/// he doesn't have the permission to use the command.
///
/// If null the default SA-MP message will be used.
/// </summary>
string Message { get; }
/// <summary>
/// Called when a user tries to use a command
/// that require permission.
/// </summary>
/// <param name="player">The player that has tried to execute the command</param>
/// <returns>Return true if the player passed as argument is allowed to use the command, False otherwise.</returns>
bool Check(GtaPlayer player);
}
}
|
Add gestione eccezioni servizi esterni | using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Models.Classi.Condivise
{
public class LogException
{
public DateTime DataOraEsecuzione { get; set; }
public string Servizio { get; set; }
public string Content { get; set; }
public string Response { get; set; }
public string CodComando { get; set; }
public string IdOperatore { get; set; }
}
}
| |
Add missing test coverage over UnableToGenerateValueException | using System;
using Xunit;
namespace Peddler {
public class UnableToGenerateValueExceptionTests {
[Fact]
public void WithDefaults() {
// Act
var exception = Throw<UnableToGenerateValueException>(
() => { throw new UnableToGenerateValueException(); }
);
// Assert
Assert.Equal("Value does not fall within the expected range.", exception.Message);
Assert.Null(exception.ParamName);
Assert.Null(exception.InnerException);
}
[Fact]
public void WithMessage() {
// Arrange
var message = Guid.NewGuid().ToString();
// Act
var exception = Throw<UnableToGenerateValueException>(
() => { throw new UnableToGenerateValueException(message); }
);
Assert.Equal(message, exception.Message);
Assert.Null(exception.ParamName);
Assert.Null(exception.InnerException);
}
[Fact]
public void WithMessageAndParamName() {
// Arrange
var message = Guid.NewGuid().ToString();
var paramName = Guid.NewGuid().ToString();
// Act
var exception = Throw<UnableToGenerateValueException>(
() => { throw new UnableToGenerateValueException(message, paramName); }
);
// Assert
Assert.Equal(message + GetParameterNameSuffix(paramName), exception.Message);
Assert.Equal(paramName, exception.ParamName);
Assert.Null(exception.InnerException);
}
[Fact]
public void WithMessageAndInnerException() {
// Arrange
var message = Guid.NewGuid().ToString();
var inner = new Exception();
// Act
var exception = Throw<UnableToGenerateValueException>(
() => { throw new UnableToGenerateValueException(message, inner); }
);
// Assert
Assert.Equal(message, exception.Message);
Assert.Null(exception.ParamName);
Assert.Equal(inner, exception.InnerException);
}
[Fact]
public void WithMessageAndParamNameAndInnerException() {
// Arrange
var message = Guid.NewGuid().ToString();
var paramName = Guid.NewGuid().ToString();
var inner = new Exception();
// Act
var exception = Throw<UnableToGenerateValueException>(
() => { throw new UnableToGenerateValueException(message, paramName, inner); }
);
// Assert
Assert.Equal(message + GetParameterNameSuffix(paramName), exception.Message);
Assert.Equal(paramName, exception.ParamName);
Assert.Equal(inner, exception.InnerException);
}
private static T Throw<T>(Action action) where T : Exception {
return (T)Record.Exception(action);
}
private static string GetParameterNameSuffix(String paramName) {
if (paramName == null) {
throw new ArgumentNullException(nameof(paramName));
}
return Environment.NewLine + $"Parameter name: {paramName}";
}
}
}
| |
Implement KTH API data fetcher | using Newtonsoft.Json;
using Org.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Schedutalk.Logic.KTHPlaces
{
class KTHPlacesDataFetcher
{
const string APIKEY = "NZfvZYDhIqDrPZvsnkY0Ocb5qJPlQNwh1BsVEH5H";
HttpRequestor httpRequestor;
public RoomDataContract getRoomData(string placeName)
{
httpRequestor = new HttpRequestor();
string recivedData = httpRequestor.getJSONAsString(getRoomExistRequestMessage, placeName);
RoomExistsDataContract roomExistsDataContract = JsonConvert.DeserializeObject<RoomExistsDataContract>(recivedData);
bool roomExists = roomExistsDataContract.Exists;
if (roomExists)
{
recivedData = httpRequestor.getJSONAsString(getRoomDataRequestMessage, placeName);
RoomDataContract roomDataContract =
JsonConvert.DeserializeObject<RoomDataContract>(recivedData);
return roomDataContract;
}
return null;
}
public HttpRequestMessage getRoomExistRequestMessage(string room)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, @"https://www.kth.se/api/places/v3/room/exists/" + room + "?api_key=" + APIKEY);
return request;
}
public HttpRequestMessage getRoomDataRequestMessage(string room)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, @"https://www.kth.se/api/places/v3/room/name/" + room + "?api_key=" + APIKEY);
return request;
}
}
} | |
Add tests for restoring the aggregate from events | using FluentAssertions;
using NetCoreCqrsEsSample.Domain.Models;
using Xunit;
namespace NetCoreCqrsEsSample.Tests.Domain
{
public class AggregateTests
{
[Fact]
public void Should_load_aggregate_from_events_correctly()
{
// arrange
var counter = new Counter();
var newCounter = new Counter();
// act
counter.Increment();
counter.Increment();
counter.Decrement();
counter.Increment();
newCounter.LoadFromHistory(counter.GetUncommittedChanges());
// assert
counter.Value.Should().Be(2);
newCounter.Value.Should().Be(2);
}
}
} | |
Add failing test case due to div by zero | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Tests.Beatmaps;
using osuTK;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Tests.Editor
{
[TestFixture]
public class TestSliderScaling : TestSceneOsuEditor
{
private OsuPlayfield playfield;
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(Ruleset.Value, false);
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("get playfield", () => playfield = Editor.ChildrenOfType<OsuPlayfield>().First());
AddStep("seek to first timing point", () => EditorClock.Seek(Beatmap.Value.Beatmap.ControlPointInfo.TimingPoints.First().Time));
}
[Test]
public void TestScalingLinearSlider()
{
Slider slider = null;
AddStep("Add slider", () =>
{
slider = new Slider { StartTime = EditorClock.CurrentTime, Position = new Vector2(300) };
PathControlPoint[] points =
{
new PathControlPoint(new Vector2(0), PathType.Linear),
new PathControlPoint(new Vector2(100, 0)),
};
slider.Path = new SliderPath(points);
EditorBeatmap.Add(slider);
});
AddAssert("ensure object placed", () => EditorBeatmap.HitObjects.Count == 1);
moveMouse(new Vector2(300));
AddStep("select slider", () => InputManager.Click(MouseButton.Left));
double distanceBefore = 0;
AddStep("store distance", () => distanceBefore = slider.Path.Distance);
AddStep("move mouse to handle", () => InputManager.MoveMouseTo(Editor.ChildrenOfType<SelectionBoxDragHandle>().Skip(1).First()));
AddStep("begin drag", () => InputManager.PressButton(MouseButton.Left));
moveMouse(new Vector2(300, 300));
AddStep("end drag", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("slider length shrunk", () => slider.Path.Distance < distanceBefore);
}
private void moveMouse(Vector2 pos) =>
AddStep($"move mouse to {pos}", () => InputManager.MoveMouseTo(playfield.ToScreenSpace(pos)));
}
}
| |
Add visual and assertive test coverage | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Utils;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneColourInterpolation : FrameworkTestScene
{
[Test]
public void TestColourInterpolatesInLinearSpace()
{
FillFlowContainer lines = null;
AddStep("load interpolated colours", () => Child = lines = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.X,
Height = 50f,
ChildrenEnumerable = Enumerable.Range(0, 750).Select(i => new Box
{
Width = 1f,
RelativeSizeAxes = Axes.Y,
Colour = Interpolation.ValueAt(i, Color4.Blue, Color4.Red, 0, 750),
}),
});
AddAssert("interpolation in linear space", () => lines.Children[lines.Children.Count / 2].Colour.AverageColour.Linear == new Color4(0.5f, 0f, 0.5f, 1f));
}
}
}
| |
Create List.Head() and List.Tail() extension methods | using System.Collections.Generic;
using System.Linq;
namespace squirrel
{
public static class ExtensionMethods
{
public static T Head<T>(this List<T> list)
{
return list[0];
}
public static List<T> Tail<T>(this List<T> list)
{
return list.Skip(1).ToList();
}
}
}
| |
Add in-process DB ORM test | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.Services.Department;
using DataAccessExamples.Core.Services.Employee;
using DataAccessExamples.Core.ViewModels;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Dsl;
namespace DataAccessExamples.Core.Tests
{
public class DbOrmTest
{
private readonly Fixture fixture = new Fixture();
private TestDatabase testDatabase;
[TestFixtureSetUp]
public void BeforeAll()
{
testDatabase = new TestDatabase();
}
[TestFixtureTearDown]
public void AfterAll()
{
testDatabase.Dispose();
}
[Test]
public void ListRecentHires_ReturnsEmployeesInLastWeek()
{
var department = new Department { Code = "Code", Name = "Department Name" };
using (var context = new EmployeesContext(testDatabase.CreateConnection(), true))
{
context.Departments.Add(department);
context.Employees.Add(EmployeeWithDepartmentAndHireDate(department, DateTime.Now.AddDays(-6)));
context.Employees.Add(EmployeeWithDepartmentAndHireDate(department, DateTime.Now.AddDays(-1)));
context.Employees.Add(EmployeeWithDepartmentAndHireDate(department, DateTime.Now.AddDays(-8)));
context.SaveChanges();
}
List<Employee> result;
using (var context = new EmployeesContext(testDatabase.CreateConnection(), true))
{
var service = new EagerOrmEmployeeService(context);
result = service.ListRecentHires().Employees.ToList();
}
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result.All(e => e.HireDate > DateTime.Now.AddDays(-7)));
Assert.That(result.All(e => e.PrimaryDepartment.Code == department.Code));
}
private Employee EmployeeWithDepartmentAndHireDate(Department department, DateTime hireDate)
{
Employee employee = fixture.Build<Employee>()
.With(e => e.HireDate, hireDate)
.With(e => e.DateOfBirth, DateTime.Now.AddYears(-30))
.Without(e => e.DepartmentEmployees)
.Without(e => e.DepartmentManagers)
.Without(e => e.Positions)
.Without(e => e.Salaries)
.Create();
DepartmentEmployee departmentEmployee = new DepartmentEmployee
{
Department = department,
Employee = employee,
FromDate = hireDate,
ToDate = DateTime.Now.AddYears(10)
};
employee.DepartmentEmployees.Add(departmentEmployee);
return employee;
}
}
}
| |
Add test scene for beatmapset online status pill 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 System;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Tests.Visual.UserInterface;
using osuTK;
namespace osu.Game.Tests.Visual.Beatmaps
{
public class TestSceneBeatmapSetOnlineStatusPill : ThemeComparisonTestScene
{
protected override Drawable CreateContent() => new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
ChildrenEnumerable = Enum.GetValues(typeof(BeatmapSetOnlineStatus)).Cast<BeatmapSetOnlineStatus>().Select(status => new BeatmapSetOnlineStatusPill
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Status = status
})
};
}
}
| |
Add default ignored request provider which discovers instances | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
namespace Glimpse.Agent.Web.Options
{
public class DefaultIgnoredRequestProvider : IIgnoredRequestProvider
{
private readonly ITypeService _typeService;
public DefaultIgnoredRequestProvider(ITypeService typeService)
{
}
public IEnumerable<IIgnoredRequestPolicy> Policies
{
get { return _typeService.Resolve<IIgnoredRequestPolicy>().ToArray(); }
}
}
} | |
Add report with basic metadata | using KenticoInspector.Core;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace KenticoInspector.Reports.ContentTreeConsistencyAnalysis
{
class Report : IReport
{
public string Codename => "Content-Tree-Consistency-Analysis";
public IList<Version> CompatibleVersions => new List<Version> {
new Version("10.0"),
new Version("11.0"),
new Version("12.0")
};
public IList<Version> IncompatibleVersions => new List<Version>();
public string LongDescription => @"
<p>Checks that CMS_Tree and CMS_Document tables are without any consistency issues.</p>
";
public string Name => "Content Tree Consistency Analysis";
public string ShortDescription => "Performs consistency analysis for content items in the content tree";
public IList<string> Tags => new List<string>()
{
ReportTags.Health,
ReportTags.Consistency
};
public ReportResults GetResults(Guid InstanceGuid)
{
throw new NotImplementedException();
}
}
}
| |
Add test for init-only properties. | using Xunit;
#if NET5_0
namespace Autofac.Test.Core
{
public class PropertyInjectionInitOnlyTests
{
public class HasInitOnlyProperties
{
public string InjectedString { get; init; }
}
[Fact]
public void CanInjectInitOnlyProperties()
{
var builder = new ContainerBuilder();
builder.RegisterType<HasInitOnlyProperties>().PropertiesAutowired();
builder.Register(ctxt => "hello world");
var container = builder.Build();
var instance = container.Resolve<HasInitOnlyProperties>();
Assert.Equal("hello world", instance.InjectedString);
}
}
}
#endif
| |
Remove the ActiveIssue(5555) tag for OSX | // 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.Net.Sockets;
using System.Net.Tests;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public class CertificateValidationRemoteServer
{
[ActiveIssue(5555, PlatformID.OSX)]
[Fact]
public async Task CertificateValidationRemoteServer_EndToEnd_Ok()
{
using (var client = new TcpClient(AddressFamily.InterNetwork))
{
await client.ConnectAsync(HttpTestServers.Host, 443);
using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null))
{
await sslStream.AuthenticateAsClientAsync(HttpTestServers.Host);
}
}
}
private bool RemoteHttpsCertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Assert.Equal(SslPolicyErrors.None, sslPolicyErrors);
return true;
}
}
}
| // 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.Net.Sockets;
using System.Net.Tests;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public class CertificateValidationRemoteServer
{
[Fact]
public async Task CertificateValidationRemoteServer_EndToEnd_Ok()
{
using (var client = new TcpClient(AddressFamily.InterNetwork))
{
await client.ConnectAsync(HttpTestServers.Host, 443);
using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null))
{
await sslStream.AuthenticateAsClientAsync(HttpTestServers.Host);
}
}
}
private bool RemoteHttpsCertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Assert.Equal(SslPolicyErrors.None, sslPolicyErrors);
return true;
}
}
}
|
Create a class to parse the alis configuration node. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace Nohros.Configuration
{
internal class ProviderAliasesNode
{
public static ICollection<string> Parse(XmlElement element) {
List<string> aliases = new List<string>(element.ChildNodes.Count);
foreach (XmlNode node in element.ChildNodes) {
if (node.NodeType == XmlNodeType.Element &&
Strings.AreEquals(node.Name, Strings.kAliasNodeName)) {
string name = AbstractConfigurationNode
.GetAttributeValue((XmlElement) node, Strings.kNameAttribute);
aliases.Add(name);
}
}
return aliases;
}
}
}
| |
Add tests for sqlite check constraints. | using System;
using NUnit.Framework;
using Moq;
using SJP.Schematic.Core;
namespace SJP.Schematic.Sqlite.Tests
{
[TestFixture]
internal class SqliteCheckConstraintTests
{
[Test]
public void Ctor_GivenNullTable_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(null, "test_check", "test_check"));
}
[Test]
public void Ctor_GivenNullName_ThrowsArgumentNullException()
{
var table = Mock.Of<IRelationalDatabaseTable>();
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(table, null, "test_check"));
}
[Test]
public void Ctor_GivenNullLocalName_ThrowsArgumentNullException()
{
var table = Mock.Of<IRelationalDatabaseTable>();
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(table, new SchemaIdentifier("test_schema"), "test_check"));
}
[Test]
public void Ctor_GivenNullDefinition_ThrowsArgumentNullException()
{
var table = Mock.Of<IRelationalDatabaseTable>();
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(table, "test_check", null));
}
[Test]
public void Ctor_GivenEmptyDefinition_ThrowsArgumentNullException()
{
var table = Mock.Of<IRelationalDatabaseTable>();
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(table, "test_check", string.Empty));
}
[Test]
public void Ctor_GivenWhiteSpaceDefinition_ThrowsArgumentNullException()
{
var table = Mock.Of<IRelationalDatabaseTable>();
Assert.Throws<ArgumentNullException>(() => new SqliteCheckConstraint(table, "test_check", " "));
}
[Test]
public void Table_PropertyGet_EqualsCtorArg()
{
Identifier tableName = "test_table";
var table = new Mock<IRelationalDatabaseTable>();
table.Setup(t => t.Name).Returns(tableName);
var tableArg = table.Object;
var check = new SqliteCheckConstraint(tableArg, "test_check", "test_check");
Assert.Multiple(() =>
{
Assert.AreEqual(tableName, check.Table.Name);
Assert.AreSame(tableArg, check.Table);
});
}
[Test]
public void Name_PropertyGet_EqualsCtorArg()
{
Identifier checkName = "test_check";
var table = Mock.Of<IRelationalDatabaseTable>();
var check = new SqliteCheckConstraint(table, checkName, "test_check");
Assert.AreEqual(checkName, check.Name);
}
[Test]
public void Definition_PropertyGet_EqualsCtorArg()
{
const string checkDefinition = "test_check_definition";
var table = Mock.Of<IRelationalDatabaseTable>();
var check = new SqliteCheckConstraint(table, "test_check", checkDefinition);
Assert.AreEqual(checkDefinition, check.Definition);
}
[Test]
public void IsEnabled_PropertyGet_ReturnsTrue()
{
var table = Mock.Of<IRelationalDatabaseTable>();
var check = new SqliteCheckConstraint(table, "test_check", "test_check_definition");
Assert.IsTrue(check.IsEnabled);
}
}
}
| |
Add acceptance tests for feature prerequisites | using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.AcceptanceTesting;
using NServiceBus.AcceptanceTests.EndpointTemplates;
using NServiceBus.Features;
using NServiceBus.Settings;
using NUnit.Framework;
[TestFixture]
class When_notifications_are_misconfigured
{
[Test]
public async Task Should_not_activate_when_both_audits_and_notifications_are_sent_to_the_same_address()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<TestEndpoint>(b => b.CustomConfig(config =>
{
config.AuditProcessedMessagesTo("audit");
config.RetrySuccessNotifications().SendRetrySuccessNotificationsTo("audit");
}))
.Done(c => c.EndpointsStarted)
.Run();
Assert.IsNotNull(context.FeatureActive, "FeatureActive");
Assert.IsFalse(context.FeatureActive.Value, "Feature is active");
}
[Test]
public async Task Should_not_activate_when_notification_address_is_whitespace()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<TestEndpoint>(b => b.CustomConfig(config =>
{
config.RetrySuccessNotifications().SendRetrySuccessNotificationsTo(" ");
}))
.Done(c => c.EndpointsStarted)
.Run();
Assert.IsNotNull(context.FeatureActive, "FeatureActive");
Assert.IsFalse(context.FeatureActive.Value, "Feature is active");
}
[Test]
public async Task Should_not_activate_when_notification_address_is_null()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<TestEndpoint>(b => b.CustomConfig(config =>
{
config.RetrySuccessNotifications().SendRetrySuccessNotificationsTo(null);
}))
.Done(c => c.EndpointsStarted)
.Run();
Assert.IsNotNull(context.FeatureActive, "FeatureActive");
Assert.IsFalse(context.FeatureActive.Value, "Feature is active");
}
class Context : ScenarioContext
{
public bool? FeatureActive { get; set; }
}
class TestEndpoint : EndpointConfigurationBuilder
{
public TestEndpoint()
{
EndpointSetup<DefaultServer>();
}
public class ExtractFeature : Feature
{
public ExtractFeature()
{
EnableByDefault();
}
protected override void Setup(FeatureConfigurationContext context)
{
context.RegisterStartupTask(b => new Startuptask(b.Build<Context>(), b.Build<ReadOnlySettings>()));
}
public class Startuptask : FeatureStartupTask
{
readonly Context context;
readonly ReadOnlySettings settings;
public Startuptask(Context context, ReadOnlySettings settings)
{
this.context = context;
this.settings = settings;
}
protected override Task OnStart(IMessageSession session)
{
context.FeatureActive = settings.IsFeatureActive(typeof(RetrySuccessNotification));
return Task.CompletedTask;
}
protected override Task OnStop(IMessageSession session)
{
return Task.CompletedTask;
}
}
}
}
} | |
Add a interface for the NTP time module | using System;
namespace FierceGalaxyInterface.TimeModule
{
public interface NetworkTime
{
/// <summary>
/// Return the time from a default NTP server
/// </summary>
DateTime GetNetworkTime();
/// <summary>
/// Return the time from the given NTP server
/// </summary>
DateTime GetNetworkTime(string serverURL);
}
}
| |
Add temporary workaround to load annotations | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
// Temporary workaround for RIDER-13547
[ShellComponent]
public class TempAnnotationsLoader : IExternalAnnotationsFileProvider
{
private readonly OneToSetMap<string, FileSystemPath> myAnnotations;
public TempAnnotationsLoader()
{
myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
var annotationsPath = GetType().Assembly.GetPath().Directory / "Extensions" / "JetBrains.Unity" / "annotations";
var annotationFiles = annotationsPath.GetChildFiles();
foreach (var annotationFile in annotationFiles)
myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null)
{
if (assemblyName == null)
return myAnnotations.Values;
return myAnnotations[assemblyName.Name];
}
}
} | |
Add fixed ignored request provider to allow user full controll | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Agent.Web.Options
{
public class FixedIgnoredRequestProvider : IIgnoredRequestProvider
{
public FixedIgnoredRequestProvider()
: this(Enumerable.Empty<IIgnoredRequestPolicy>())
{
}
public FixedIgnoredRequestProvider(IEnumerable<IIgnoredRequestPolicy> controllerTypes)
{
Policies = new List<IIgnoredRequestPolicy>(controllerTypes);
}
public IList<IIgnoredRequestPolicy> Policies { get; }
IEnumerable<IIgnoredRequestPolicy> IIgnoredRequestProvider.Policies => Policies;
}
} | |
Add missing file to repository | // ***********************************************************************
// Copyright (c) 2010 Charlie Poole
//
// 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 NUnit.Framework.Api
{
public interface ISetRunState
{
RunState GetRunState();
string GetReason();
}
}
| |
Create Soccer Lobby ball factory/manager | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SceneJect.Common;
using Sirenix.OdinInspector;
using Sirenix.Serialization;
using UnityEngine;
namespace Booma.Proxy
{
/// <summary>
/// Simple manager that manages the spawning and despawning the the lobby soccer ball.
/// </summary>
[Injectee]
public sealed class SoccerLobbyBallFactory : SerializedMonoBehaviour
{
[Inject]
private IBeatsEventQueueRegisterable BeatEventQueue { get; }
[Tooltip("The soccer ball prefab.")]
[SerializeField]
private GameObject SoccerrBallPrefab;
[ReadOnly]
private GameObject CurrentTrackedBall;
[Required]
[PropertyTooltip("The spawn point strategy.")]
[OdinSerialize]
private ISpawnPointStrategy SpawnStrategy { get; set; }
private void Start()
{
//In the soccer lobby the client expects that
//the ball will be summoned every beat.
//it also expects that the ball we be unsummoned
//15/10 centibeats before a new one spawns
//On the next beat we want to register a repeating ball spawning
BeatEventQueue.RegisterOnNextBeat(() =>
{
//Spawn the ball
SpawnBall();
//Every 1 beat we should spawn the ball
BeatEventQueue.RegisterRepeating(SpawnBall, Beat.Beats(1));
//Add a despawn event right before we respawn the ball
BeatEventQueue.RegisterRepeating(DespawnBall, Beat.CentiBeats(90));
});
}
private void SpawnBall()
{
Transform trans = SpawnStrategy.GetSpawnpoint();
if(trans == null)
throw new InvalidOperationException($"Cannot spawn a ball from the {nameof(SoccerLobbyBallFactory)} from a null transform. Initialize the {nameof(ISpawnPointStrategy)} field.");
//Just spawn the ball for now
GameObject.Instantiate(SoccerrBallPrefab, trans.position, trans.rotation);
}
private void DespawnBall()
{
if(CurrentTrackedBall == null)
return;
Destroy(CurrentTrackedBall);
}
}
}
| |
Add release manager command to show "lagging" packages | // 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.
using Google.Cloud.Tools.Common;
using System;
using System.Linq;
namespace Google.Cloud.Tools.ReleaseManager
{
/// <summary>
/// Command to show packages whose last release was a pre-release, but which represent a GA
/// API (and should therefore be considered for a GA release).
/// </summary>
public class ShowLaggingCommand : CommandBase
{
public ShowLaggingCommand() : base("show-lagging", "Shows pre-release packages where a GA should be considered")
{
}
protected override void ExecuteImpl(string[] args)
{
var catalog = ApiCatalog.Load();
var lagging = catalog.Apis.Where(api => api.CanHaveGaRelease && api.StructuredVersion.Prerelease is string);
Console.WriteLine($"Lagging packages:");
foreach (var api in lagging)
{
Console.WriteLine($"{api.Id} ({api.Version})");
}
}
}
}
| |
Add default provider which uses reflection | using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class DefaultRequestAuthorizerProvider : IRequestAuthorizerProvider
{
private readonly ITypeService _typeService;
public DefaultRequestAuthorizerProvider(ITypeService typeService)
{
_typeService = typeService;
}
public IEnumerable<IRequestAuthorizer> Authorizers
{
get { return _typeService.Resolve<IRequestAuthorizer>().ToArray(); }
}
}
} | |
Create polygon out of selectet lines and arcs | //-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 2014-04-24
// Autor support@easylogix.de
// www.pcb-investigator.com
// SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html
// SDK http://www.pcb-investigator.com/en/sdk-participate
// Create polygon out of selectet lines and arcs.
//-----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
public void Execute(IPCBIWindow parent)
{
IStep step = parent.GetCurrentStep();
IFilter filter = new IFilter(parent);
IODBLayer layerPolygons = filter.CreateEmptyODBLayer("polygons_n", step.Name);
bool polyStart = true;
List<IODBObject> listOfSelection = step.GetSelectedElements();
PCBI.MathUtils.IPolyClass poly = new PCBI.MathUtils.IPolyClass();
foreach (IODBObject obj in listOfSelection)
{
IObjectSpecificsD os = obj.GetSpecificsD();
if (os.GetType() == typeof(IArcSpecificsD))
{
IArcSpecificsD aEdge = (IArcSpecificsD)os;
if (polyStart)
{
polyStart = false;
}
poly.AddEdge(aEdge.Start, aEdge.End, aEdge.Center, aEdge.ClockWise);
}
else if (os.GetType() == typeof(ILineSpecificsD))
{
ILineSpecificsD aEdge = (ILineSpecificsD)os;
if (polyStart)
{
polyStart = false;
}
poly.AddEdge(aEdge.Start, aEdge.End);
}
}
if (poly.GetSubPolygons().Count > 0)
{
foreach (PCBI.MathUtils.IPolyClass polyC in poly.GetSubPolygons())
{
if (polyC.GetBounds().Width > 0.001 && polyC.GetBounds().Height > 0.001)
{
IODBObject surfaceFromPoly = polyC.GetSurfaceFromPolygon(layerPolygons);
}
}
layerPolygons.EnableLayer(true);
}
else
{
IODBObject suf = poly.GetSurfaceFromPolygon(layerPolygons);
layerPolygons.EnableLayer(true);
}
parent.UpdateView();
IMatrix matrix = parent.GetMatrix();
matrix.UpdateDataAndList();
}
}
} | |
Add test coverage of score importing | // 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.Screens;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;
namespace osu.Game.Tests.Visual.Gameplay
{
[HeadlessTest] // Importing rulesets doesn't work in interactive flows.
public class TestScenePlayerLocalScoreImport : PlayerTestScene
{
private Ruleset? customRuleset;
protected override bool ImportBeatmapToDatabase => true;
protected override Ruleset CreatePlayerRuleset() => customRuleset ?? new OsuRuleset();
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new TestPlayer(false);
protected override bool HasCustomSteps => true;
protected override bool AllowFail => false;
[Test]
public void TestScoreStoredLocally()
{
AddStep("set no custom ruleset", () => customRuleset = null);
CreateTest();
AddUntilStep("wait for track to start running", () => Beatmap.Value.Track.IsRunning);
AddStep("seek to completion", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.Objects.Last().GetEndTime()));
AddUntilStep("results displayed", () => Player.GetChildScreen() is ResultsScreen);
AddUntilStep("score in database", () => Realm.Run(r => r.Find<ScoreInfo>(Player.Score.ScoreInfo.ID) != null));
}
[Test]
public void TestScoreStoredLocallyCustomRuleset()
{
Ruleset createCustomRuleset() => new OsuRuleset
{
RulesetInfo =
{
Name = "custom",
ShortName = "custom",
OnlineID = -1
}
};
AddStep("import custom ruleset", () => Realm.Write(r => r.Add(createCustomRuleset().RulesetInfo)));
AddStep("set custom ruleset", () => customRuleset = createCustomRuleset());
CreateTest();
AddUntilStep("wait for track to start running", () => Beatmap.Value.Track.IsRunning);
AddStep("seek to completion", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.Objects.Last().GetEndTime()));
AddUntilStep("results displayed", () => Player.GetChildScreen() is ResultsScreen);
AddUntilStep("score in database", () => Realm.Run(r => r.All<ScoreInfo>().Count() == 1));
}
}
}
| |
Create User Module Ninject Commit | using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using NeedDotNet.Server.Domain.Entities;
using NeedDotNet.Web.Infrastructure;
using NeedDotNet.Web.Services;
using Ninject.Modules;
using Ninject.Web.Common;
namespace NeedDotNet.Web.NinjectResolution
{
internal class UserIdentityModule : NinjectModule
{
public override void Load()
{
Kernel
.Bind<UserManager<User, long>>()
.To<UserManager>()
.InRequestScope();
Kernel
.Bind<UserStore<User, Role, long, UserLogin, UserRole, UserClaim>>()
.To<UserStore>()
.InRequestScope();
}
}
} | |
Check emptyness of an XDocument | using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace GranitXMLEditor
{
public static class XDocumentExtension
{
public static bool IsEmpty(this XDocument element)
{
return element.Elements().Count() == 0;
}
public static DataTable ToDataTable(this XDocument element)
{
DataSet ds = new DataSet();
string rawXml = element.ToString();
ds.ReadXml(new StringReader(rawXml));
return ds.Tables[0];
}
public static DataTable ToDataTable(this IEnumerable<XElement> elements)
{
return ToDataTable(new XDocument("Root", elements));
}
}
}
| |
Allow scenario class to take properties | 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)
{
var packages = await RestoreAndBuildPackages(scenarioName);
return packages.Single();
}
public static async Task<IReadOnlyCollection<IPackage>> RestoreAndBuildPackages(string scenarioName)
{
var projectFullPath = Assets.GetScenarioSolutionPath(scenarioName);
var projectDirectory = Path.GetDirectoryName(projectFullPath);
await NuGetHelper.RestorePackagesAsync(projectDirectory);
var result = await MSBuild.RebuildAsync(projectFullPath);
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, 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);
}
}
} |
Add failing test showing the issue of DHO lifetime | // 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.Testing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Gameplay
{
[HeadlessTest]
public class TestSceneDrawableHitObject : OsuTestScene
{
[Test]
public void TestEntryLifetime()
{
TestDrawableHitObject dho = null;
var initialHitObject = new HitObject
{
StartTime = 1000
};
var entry = new TestLifetimeEntry(new HitObject
{
StartTime = 2000
});
AddStep("Create DHO", () => Child = dho = new TestDrawableHitObject(initialHitObject));
AddAssert("Correct initial lifetime", () => dho.LifetimeStart == initialHitObject.StartTime - TestDrawableHitObject.INITIAL_LIFETIME_OFFSET);
AddStep("Apply entry", () => dho.Apply(entry));
AddAssert("Correct initial lifetime", () => dho.LifetimeStart == entry.HitObject.StartTime - TestLifetimeEntry.INITIAL_LIFETIME_OFFSET);
AddStep("Set lifetime", () => dho.LifetimeEnd = 3000);
AddAssert("Entry lifetime is updated", () => entry.LifetimeEnd == 3000);
}
private class TestDrawableHitObject : DrawableHitObject
{
public const double INITIAL_LIFETIME_OFFSET = 100;
protected override double InitialLifetimeOffset => INITIAL_LIFETIME_OFFSET;
public TestDrawableHitObject(HitObject hitObject)
: base(hitObject)
{
}
}
private class TestLifetimeEntry : HitObjectLifetimeEntry
{
public const double INITIAL_LIFETIME_OFFSET = 200;
protected override double InitialLifetimeOffset => INITIAL_LIFETIME_OFFSET;
public TestLifetimeEntry(HitObject hitObject)
: base(hitObject)
{
}
}
}
}
| |
Create tests for grouped filters | using SqlKata.Compilers;
using SqlKata.Tests.Infrastructure;
using Xunit;
namespace SqlKata.Tests
{
public class WhereTests : TestSupport
{
[Fact]
public void GroupedWhereFilters()
{
var q = new Query("Table1")
.Where(q => q.Or().Where("Column1", 10).Or().Where("Column2", 20))
.Where("Column3", 30);
var c = Compile(q);
Assert.Equal(@"SELECT * FROM ""Table1"" WHERE (""Column1"" = 10 OR ""Column2"" = 20) AND ""Column3"" = 30", c[EngineCodes.PostgreSql]);
}
[Fact]
public void GroupedHavingFilters()
{
var q = new Query("Table1")
.Having(q => q.Or().HavingRaw("SUM([Column1]) = ?", 10).Or().HavingRaw("SUM([Column2]) = ?", 20))
.HavingRaw("SUM([Column3]) = ?", 30);
var c = Compile(q);
Assert.Equal(@"SELECT * FROM ""Table1"" HAVING (SUM(""Column1"") = 10 OR SUM(""Column2"") = 20) AND SUM(""Column3"") = 30", c[EngineCodes.PostgreSql]);
}
}
}
| |
Add base class for all realtime multiplayer classes | // 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 JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Game.Online.RealtimeMultiplayer;
namespace osu.Game.Screens.Multi.RealtimeMultiplayer
{
public abstract class RealtimeRoomComposite : MultiplayerComposite
{
[CanBeNull]
protected MultiplayerRoom Room => Client.Room;
[Resolved]
protected StatefulMultiplayerClient Client { get; private set; }
protected override void LoadComplete()
{
base.LoadComplete();
Client.RoomChanged += OnRoomChanged;
OnRoomChanged();
}
protected virtual void OnRoomChanged()
{
}
protected override void Dispose(bool isDisposing)
{
if (Client != null)
Client.RoomChanged -= OnRoomChanged;
base.Dispose(isDisposing);
}
}
}
| |
Remove NumPages, Total, and LastPageUri from ListBase | using System;
using System.Collections.Generic;
namespace Twilio
{
/// <summary>
/// Base class for list resource data
/// </summary>
public class TwilioListBase : TwilioBase
{
/// <summary>
/// The current page number. Zero-indexed, so the first page is 0.
/// </summary>
public int Page { get; set; }
/// <summary>
/// The total number of pages.
/// </summary>
public int NumPages { get; set; }
/// <summary>
/// How many items are in each page
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// The total number of items in the list.
/// </summary>
public int Total { get; set; }
/// <summary>
/// The position in the overall list of the first item in this page.
/// </summary>
public int Start { get; set; }
/// <summary>
/// The position in the overall list of the last item in this page.
/// </summary>
public int End { get; set; }
/// <summary>
/// The URI for the first page of this list.
/// </summary>
public Uri FirstPageUri { get; set; }
/// <summary>
/// The URI for the next page of this list.
/// </summary>
public Uri NextPageUri { get; set; }
/// <summary>
/// The URI for the previous page of this list.
/// </summary>
public Uri PreviousPageUri { get; set; }
/// <summary>
/// The URI for the last page of this list.
/// </summary>
public Uri LastPageUri { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace Twilio
{
/// <summary>
/// Base class for list resource data
/// </summary>
public class TwilioListBase : TwilioBase
{
/// <summary>
/// The current page number. Zero-indexed, so the first page is 0.
/// </summary>
public int Page { get; set; }
/// <summary>
/// How many items are in each page
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// The position in the overall list of the first item in this page.
/// </summary>
public int Start { get; set; }
/// <summary>
/// The position in the overall list of the last item in this page.
/// </summary>
public int End { get; set; }
/// <summary>
/// The URI for the first page of this list.
/// </summary>
public Uri FirstPageUri { get; set; }
/// <summary>
/// The URI for the next page of this list.
/// </summary>
public Uri NextPageUri { get; set; }
/// <summary>
/// The URI for the previous page of this list.
/// </summary>
public Uri PreviousPageUri { get; set; }
}
} |
Add missing enum for wood. | namespace Decent.Minecraft.Client
{
public enum Orientation : ushort
{
UpDown = 0x0,
EastWest = 0x4,
NorthSouth = 0x8,
None = 0xC
}
}
| |
Add some test coverage for Ensure | using System;
using Burr.Helpers;
using FluentAssertions;
using Xunit;
using Xunit.Extensions;
namespace Burr.Tests.Helpers
{
public class EnsureTests
{
public class TheArgumentNotNullMethod
{
[Fact]
public void ThrowsForNullArgument()
{
var res = Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull(null, "arg"));
res.ParamName.Should().Be("arg");
}
[Fact]
public void DoesNotThrowForValidArgument()
{
Assert.DoesNotThrow(() => Ensure.ArgumentNotNull(new object(), "arg"));
}
}
public class TheArgumentNotNullOrEmptyStringMethod
{
[Fact]
public void ThrowsForNullArgument()
{
var res = Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNullOrEmptyString(null, "arg"));
res.ParamName.Should().Be("arg");
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void ThrowsForEmptyOrBlank(string data)
{
var res = Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNullOrEmptyString(data, "arg"));
res.ParamName.Should().Be("arg");
}
[Fact]
public void DoesNotThrowForValidArgument()
{
Assert.DoesNotThrow(() => Ensure.ArgumentNotNullOrEmptyString("a", "arg"));
}
}
}
}
| |
Add an infraction search command | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Modix.Data.Models;
using Modix.Data.Models.Moderation;
using Modix.Services.Moderation;
using Serilog;
using Tababular;
namespace Modix.Modules
{
public class InfractionModule : ModuleBase
{
private readonly IModerationService _moderationService;
public InfractionModule(IModerationService moderationService)
{
_moderationService = moderationService;
}
[Command("search"), Summary("Search infractions for a user")]
public async Task SearchInfractionsByUserId(ulong userId)
{
var user = Context.User as SocketGuildUser;
// TODO: We shouldn't need to do this once claims are working
if (!IsStaff(user) && !IsOperator(user))
{
await ReplyAsync($"I'm sorry, @{user.Nickname}, I'm afraid I can't do that.");
return;
}
try
{
var notes = await _moderationService.SearchInfractionsAsync(
new InfractionSearchCriteria
{
SubjectId = userId
},
new[]
{
new SortingCriteria { PropertyName = "CreateAction.Created", Direction = SortDirection.Descending }
});
var sb = new StringBuilder();
var hints = new Hints { MaxTableWidth = 100 };
var formatter = new TableFormatter(hints);
var formattedNotes = notes.Select(note => new
{
Id = note.Id,
User = note.Subject.Username,
RecordedBy = note.CreateAction.CreatedBy,
Message = note.Reason,
Date = note.CreateAction.Created.ToString("yyyy-MM-ddTHH:mm:ss")
}).ToList();
var text = formatter.FormatObjects(formattedNotes);
sb.Append(Format.Code(text));
if (sb.ToString().Length <= 2000)
{
await ReplyAsync(sb.ToString());
return;
}
var formattedNoteIds = notes.Select(note => new
{
NoteId = note.Id
});
var noteIds = formatter.FormatObjects(formattedNoteIds);
sb.Clear();
sb.AppendLine("Notes exceed the character limit. Search for an Id below to retrieve note details");
sb.Append(Format.Code(noteIds));
await ReplyAsync(sb.ToString());
}
catch (Exception e)
{
Log.Error(e, $"NoteModule SearchNotesByUserId failed with the following userId: {userId}");
await ReplyAsync("Error occurred and search could not be complete");
}
}
private static bool IsOperator(SocketGuildUser user)
{
return user != null && user.Roles.Any(x => string.Equals("Operator", x.Name, StringComparison.Ordinal));
}
private static bool IsStaff(SocketGuildUser user)
{
return user != null && user.Roles.Any(
x => string.Equals("Staff", x.Name, StringComparison.Ordinal) ||
string.Equals("Moderator", x.Name, StringComparison.Ordinal) ||
string.Equals("Administrator", x.Name, StringComparison.Ordinal));
}
}
}
| |
Add swuber icon to gmaps marker and switch views to satelite |
@{
ViewBag.Title = "UserDashBoard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>UserDashBoard</h2>
<fieldset>
@if (Session["NNumber"] != null) {
<text>
Welcome @Session["NNumber"].ToString()
@Session["FirstName"].ToString()
@Session["LastName"].ToString() </text>
} </fieldset>
<h2>@Html.ActionLink("(walker)Find a Ride", "Walker", "CurrentCustomer")</h2>
<h2>@Html.ActionLink("(driver)Find a Parking Spot", "Driver", "CurrentCustomer")</h2>
<h2><a href="\GMaps.html">map</a></h2>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp = {
center: new google.maps.LatLng(30.266120, -81.507199),
zoom: 15,
mapTypeId: 'satellite',
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyByFLWZ-dFP4JATVY-_RN0sUSvIWXEynOE&callback=myMap"></script>
| |
Add partial class for retry settings (compatibility) | // 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.Scheduler.V1
{
// This is a partial class introduced for backward compatibility with earlier versions.
public partial class CloudSchedulerSettings
{
/// <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 integration tests for Empiria Oracle Data Handler and Empiria ORM | /* Empiria Extensions ****************************************************************************************
* *
* Module : Oracle Data Handler Component : Test Helpers *
* Assembly : Empiria.Data.Oracle.Tests.dll Pattern : Unit tests *
* Type : OracleORMTests License : Please read LICENSE.txt file *
* *
* Summary : Integration tests for Empiria Oracle Data Handler with Empiria ORM Framework. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using Xunit;
using Empiria.ORM;
using Empiria.Reflection;
namespace Empiria.Data.Handlers.Tests {
/// <summary>Integration tests for Empiria Oracle Data Handler with Empiria ORM Framework.</summary>
public class OracleORMTests {
#region Facts
[Fact]
public void Should_Fill_Object_Structure() {
var dataOperation = DataOperation.Parse("getUserSession", TestingConstants.SESSION_TOKEN);
var rules = DataMappingRules.Parse(typeof(SessionTest));
var oracleMethods = new OracleMethods();
var dataRow = oracleMethods.GetDataRow(dataOperation);
SessionTest session = ObjectFactory.CreateObject<SessionTest>();
rules.DataBind(session, dataRow);
Assert.NotNull(session);
Assert.Equal(long.Parse("123456789012345678"), session.Id);
Assert.Equal(TestingConstants.SESSION_TOKEN, session.SessionToken);
Assert.Equal(3600, session.ExpiresIn);
Assert.NotNull(session.ExtData);
Assert.Equal(string.Empty, session.ExtData);
Assert.Equal(new DateTime(2021, 03, 28), session.StartTime);
}
#endregion Facts
} // class OracleORMTests
internal class SessionTest {
[DataField("SessionId")]
public long Id {
get; private set;
}
[DataField("SessionToken")]
public string SessionToken {
get; private set;
}
[DataField("ExpiresIn")]
public int ExpiresIn {
get; private set;
}
[DataField("SessionExtData")]
public string ExtData {
get; private set;
}
[DataField("StartTime")]
public DateTime StartTime {
get; private set;
}
} // SessionTest
} // namespace Empiria.Data.Handlers.Tests
| |
Move extensions to appropriate project | using System;
namespace Grobid.PdfToXml
{
public static class Extensions
{
// Same rules as pdftoxml.
// Max difference in primary font sizes on two lines in the same
// block. Delta1 is used when examining new lines above and below the
// current block.
private const double maxBlockFontSizeDelta1 = 0.05;
// Max distance between baselines of two lines within a block, as a
// fraction of the font size.
private const double maxLineSpacingDelta = 1.5;
public static bool IsSameBlock(this TextBlock prevTextBlock, TextBlock currTextBlock)
{
bool isSimilarLineHeight = currTextBlock.Y + currTextBlock.Height >= prevTextBlock.Y;
bool isSimilarFontSize = Math.Abs(currTextBlock.TokenBlocks[0].FontSize - prevTextBlock.TokenBlocks[0].FontSize) <
(currTextBlock.TokenBlocks[0].FontSize * Extensions.maxBlockFontSizeDelta1);
bool isMinimalSpacing = (currTextBlock.Y - prevTextBlock.Y) < (prevTextBlock.TokenBlocks[0].FontSize * Extensions.maxLineSpacingDelta);
return (isSimilarLineHeight && isSimilarFontSize && isMinimalSpacing);
}
}
} | |
Add some sample console output | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationSample
{
class Program
{
static void Main(string[] args)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Changeset: " + VersionInfo.Changeset);
Console.WriteLine("Changeset (short): " + VersionInfo.ChangesetShort);
Console.WriteLine("Dirty Build: " + VersionInfo.DirtyBuild);
Console.ReadKey();
}
}
}
|
Add test scene for hitcircles and combo changes | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Rulesets.Osu.Objects;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneHitCircleComboChange : TestSceneHitCircle
{
private readonly Bindable<int> comboIndex = new Bindable<int>();
protected override void LoadComplete()
{
base.LoadComplete();
Scheduler.AddDelayed(() => comboIndex.Value++, 250, true);
}
protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
{
circle.ComboIndexBindable.BindTo(comboIndex);
circle.IndexInCurrentComboBindable.BindTo(comboIndex);
return base.CreateDrawableHitCircle(circle, auto);
}
}
}
| |
Add basic multiplayer gameplay test coverage | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Game.Screens.OnlinePlay.Multiplayer;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestMultiplayerGameplay : MultiplayerTestScene
{
[Test]
public void TestBasic()
{
AddStep("load screen", () =>
LoadScreen(new MultiplayerPlayer(Client.CurrentMatchPlayingItem.Value, Client.Room?.Users.Select(u => u.UserID).ToArray())));
}
}
}
| |
Add Storage function unit 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_storage_unit_test]
using CloudNative.CloudEvents;
using Google.Cloud.Functions.Invoker.Testing;
using Google.Events;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace HelloWorld.Tests
{
public class HelloGcsUnitTest
{
[Fact]
public async Task FileNameIsLogged()
{
// Prepare the inputs
var cloudEvent = new CloudEvent(StorageObjectData.FinalizedCloudEventType, new Uri("//storage.googleapis.com"));
var data = new StorageObjectData { Name = "new-file.txt" };
CloudEventConverters.PopulateCloudEvent(cloudEvent, data);
var logger = new MemoryLogger<HelloGcs.Function>();
// Execute the function
var function = new HelloGcs.Function(logger);
await function.HandleAsync(cloudEvent, data, CancellationToken.None);
// Check the log results
var logEntry = Assert.Single(logger.ListLogEntries());
Assert.Equal("File new-file.txt uploaded", logEntry.Message);
Assert.Equal(LogLevel.Information, logEntry.Level);
}
}
}
// [END functions_storage_unit_test]
| |
Add entry point. Technically not really needed, but fixes a ReSharper warning. | using System;
namespace HelloCoreClrApp.Test
{
public static class Program
{
// Entry point for the application.
public static void Main(string[] args)
{
Console.WriteLine("Please use 'dotnet test' or 'dotnet xunit' to run unit tests.");
}
}
} | |
Add missing file (to b7f3a06 and later) | //
// UniversityPortalConfig.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// 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 R7.University.Components
{
public class UniversityPortalConfig
{
public EmployeePhotoConfig EmployeePhoto { get; set; }
public BarcodeConfig Barcode { get; set; }
}
public class EmployeePhotoConfig
{
public string DefaultPath { get; set; }
public string SquareSuffix { get; set; }
public int DefaultWidth { get; set; }
public int SquareDefaultWidth { get; set; }
}
public class BarcodeConfig
{
public int DefaultWidth { get; set; }
}
}
| |
Implement show-version command referred to in PROCESSES.md | // 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.
using Google.Cloud.Tools.Common;
using System;
namespace Google.Cloud.Tools.ReleaseManager
{
public sealed class ShowVersionCommand : CommandBase
{
public ShowVersionCommand()
: base("show-version", "Show the current version (in apis.json) of the specified package", "id")
{
}
protected override void ExecuteImpl(string[] args)
{
string id = args[0];
var catalog = ApiCatalog.Load();
var api = catalog[id];
Console.WriteLine($"Current version of {id} in the API catalog: {api.Version}");
}
}
}
| |
TEST Transaction: no DB connection if not needed, possible to pass DB connection. | //
// Copyright (c) 2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Data;
using Sooda;
using Sooda.UnitTests.BaseObjects;
using NUnit.Framework;
namespace Sooda.UnitTests.TestCases
{
[TestFixture]
public class TransactionTest
{
[Test]
public void LazyDbConnection()
{
using (new SoodaTransaction())
{
}
}
[Test]
public void PassDbConnection()
{
using (SoodaDataSource sds = _DatabaseSchema.GetSchema().GetDataSourceInfo("default").CreateDataSource())
{
sds.Open();
// sds.ExecuteNonQuery(sql, params);
using (IDataReader r = sds.ExecuteRawQuery("select count(*) from contact"))
{
bool b = r.Read();
Assert.IsTrue(b);
int c = r.GetInt32(0);
Assert.AreEqual(7, c);
}
using (SoodaTransaction tran = new SoodaTransaction())
{
tran.RegisterDataSource(sds);
int c = Contact.GetList(true).Count;
Assert.AreEqual(7, c);
}
}
}
}
}
| |
Test that the container can resolve Test that the container can resolve the engine root object Having this test would have saved some time recently | using System;
using NuKeeper.Configuration;
using NuKeeper.Engine;
using NUnit.Framework;
namespace NuKeeper.Tests
{
[TestFixture]
public class ContainerRegistrationTests
{
[Test]
public void RootCanBeResolved()
{
var container = ContainerRegistration.Init(MakeValidSettings());
var engine = container.GetInstance<GithubEngine>();
Assert.That(engine, Is.Not.Null);
}
private static Settings MakeValidSettings()
{
var org = new OrganisationModeSettings
{
GithubApiBase = new Uri("https://github.com/NuKeeperDotNet"),
GithubToken = "abc123"
};
return new Settings(org);
}
}
}
| |
Add default implementation for RequestProfilers provider | using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Agent.Web
{
public class DefaultRequestProfilerProvider : IRequestProfilerProvider
{
private readonly ITypeService _typeService;
public DefaultRequestProfilerProvider(ITypeService typeService)
{
_typeService = typeService;
}
public IEnumerable<IRequestProfiler> Profilers
{
get { return _typeService.Resolve<IRequestProfiler>().ToArray(); }
}
}
} | |
Add failing test for assertion of concurrent calls | namespace FakeItEasy.Tests
{
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
public class ConcurrentCallTests
{
private readonly ITestOutputHelper output;
public ConcurrentCallTests(ITestOutputHelper output)
{
this.output = output;
}
public interface ITestInterface
{
int MyMethod();
}
[Fact]
public void Concurrent_calls_are_correctly_recorded()
{
for (int i = 0; i < 100; i++)
{
try
{
ITestInterface fake = A.Fake<ITestInterface>();
int count = 0;
A.CallTo(() => fake.MyMethod()).ReturnsLazily(p => Interlocked.Increment(ref count));
Task<int>[] tasks =
{
Task.Run(() => fake.MyMethod()),
Task.Run(() => fake.MyMethod()),
};
int[] result = Task.WhenAll(tasks).Result;
result.Should().BeEquivalentTo(1, 2);
A.CallTo(() => fake.MyMethod()).MustHaveHappenedTwiceExactly();
}
catch
{
this.output.WriteLine($"Failed at iteration {i}");
throw;
}
}
}
}
}
| |
Add tests for the ValidatorFixtureAttribute | using NUnit.Framework;
using System;
using System.Reflection;
namespace NValidate.Tests
{
[TestFixture]
public class ValidatorFixtureAttributeTest
{
[ValidatorFixture("WithAttribute")]
class ClassWithAttribute { }
class ClassWithoutAttribute { }
[Test]
public void Name()
{
var attribute = new ValidatorFixtureAttribute("The Attribute");
Assert.That(attribute.Name, Is.EqualTo("The Attribute"));
}
[Test]
public void HasAttribute()
{
Assert.That(ValidatorFixtureAttribute.HasAttribute(typeof(ClassWithAttribute).GetTypeInfo()), Is.True);
Assert.That(ValidatorFixtureAttribute.HasAttribute(typeof(ClassWithoutAttribute).GetTypeInfo()), Is.False);
}
}
}
| |
Include DTO pretty printer extensions | using System;
using System.Text;
namespace CIAPI
{
///<summary>
/// Useful logging and debugging extensions
///</summary>
public static class PrettyPrinterExtensions
{
///<summary>
/// Create string showing values of all public properties for object
///</summary>
///<param name="dto"></param>
///<returns></returns>
public static string ToStringWithValues(this object dto)
{
var sb = new StringBuilder();
foreach (var propertyInfo in dto.GetType().GetProperties())
{
var formattedValue = "";
switch (propertyInfo.PropertyType.Name)
{
case "System.DateTime":
formattedValue = ((DateTime)propertyInfo.GetValue(dto, null)).ToString("u");
break;
default:
formattedValue = propertyInfo.GetValue(dto, null).ToString();
break;
}
sb.AppendFormat("\t{0}={1}", propertyInfo.Name, formattedValue);
}
return string.Format("{0}: \n{1}", dto.GetType().Name, sb);
}
}
}
| |
Add new tests for Choose Function | using System;
using System.IO;
using EPPlusTest.FormulaParsing.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeOpenXml;
using OfficeOpenXml.FormulaParsing;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using OfficeOpenXml.FormulaParsing.Exceptions;
namespace EPPlusTest.FormulaParsing.Excel.Functions.RefAndLookup
{
[TestClass]
public class ChooseTests
{
private ParsingContext _parsingContext;
private ExcelPackage _package;
private ExcelWorksheet _worksheet;
[TestInitialize]
public void Initialize()
{
_parsingContext = ParsingContext.Create();
_package = new ExcelPackage(new MemoryStream());
_worksheet = _package.Workbook.Worksheets.Add("test");
}
[TestCleanup]
public void Cleanup()
{
_package.Dispose();
}
[TestMethod]
public void ChooseSingleValue()
{
fillChooseOptions();
_worksheet.Cells["B1"].Formula = "CHOOSE(4, A1, A2, A3, A4, A5)";
_worksheet.Calculate();
Assert.AreEqual("5", _worksheet.Cells["B1"].Value);
}
[TestMethod]
public void ChooseSingleFormula()
{
fillChooseOptions();
_worksheet.Cells["B1"].Formula = "CHOOSE(6, A1, A2, A3, A4, A5, A6)";
_worksheet.Calculate();
Assert.AreEqual("12", _worksheet.Cells["B1"].Value);
}
[TestMethod]
public void ChooseMultipleValues()
{
fillChooseOptions();
_worksheet.Cells["B1"].Formula = "SUM(CHOOSE({1,3,4}, A1, A2, A3, A4, A5))";
_worksheet.Calculate();
Assert.AreEqual(9D, _worksheet.Cells["B1"].Value);
}
[TestMethod]
public void ChooseValueAndFormula()
{
fillChooseOptions();
_worksheet.Cells["B1"].Formula = "SUM(CHOOSE({2,6}, A1, A2, A3, A4, A5, A6))";
_worksheet.Calculate();
Assert.AreEqual(14D, _worksheet.Cells["B1"].Value);
}
private void fillChooseOptions()
{
_worksheet.Cells["A1"].Value = 1d;
_worksheet.Cells["A2"].Value = 2d;
_worksheet.Cells["A3"].Value = 3d;
_worksheet.Cells["A4"].Value = 5d;
_worksheet.Cells["A5"].Value = 7d;
_worksheet.Cells["A6"].Formula = "A4 + A5";
}
}
}
| |
Add a benchmark case for affects render. | using Avalonia.Controls;
using Avalonia.Media;
using BenchmarkDotNet.Attributes;
namespace Avalonia.Benchmarks.Visuals;
[MemoryDiagnoser]
public class VisualAffectsRenderBenchmarks
{
private readonly TestVisual _target;
private readonly IPen _pen;
public VisualAffectsRenderBenchmarks()
{
_target = new TestVisual();
_pen = new Pen(Brushes.Black);
}
[Benchmark]
public void SetPropertyThatAffectsRender()
{
_target.Pen = _pen;
_target.Pen = null;
}
private class TestVisual : Visual
{
/// <summary>
/// Defines the <see cref="Pen"/> property.
/// </summary>
public static readonly StyledProperty<IPen> PenProperty =
AvaloniaProperty.Register<Border, IPen>(nameof(Pen));
public IPen Pen
{
get { return GetValue(PenProperty); }
set { SetValue(PenProperty, value); }
}
static TestVisual()
{
AffectsRender<TestVisual>(PenProperty);
}
}
}
| |
Add tests for anonymous object rendering. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionToCodeLib;
using Xunit;
namespace ExpressionToCodeTest
{
public class AnonymousObjectFormattingTest
{
[Fact]
public void AnonymousObjectsRenderAsCode()
{
Assert.Equal("\nnew {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", }));
}
[Fact]
public void AnonymousObjectsInArray()
{
Assert.Equal("new[] {\nnew {\n Val = 3,\n}, \nnew {\n Val = 42,\n}}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } }));
}
[Fact]
public void EnumerableInAnonymousObject()
{
Assert.Equal("\nnew {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) }));
}
[Fact]
public void EnumInAnonymousObject()
{
Assert.Equal("\nnew {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A}));
}
}
}
| |
Change SafePipeHandle to use IntPtr.Zero instead of new IntPtr(0) | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafePipeHandle : SafeHandle
{
protected override bool ReleaseHandle()
{
return Interop.mincore.CloseHandle(handle);
}
public override bool IsInvalid
{
[SecurityCritical]
get { return handle == new IntPtr(0) || handle == new IntPtr(-1); }
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafePipeHandle : SafeHandle
{
protected override bool ReleaseHandle()
{
return Interop.mincore.CloseHandle(handle);
}
public override bool IsInvalid
{
[SecurityCritical]
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
}
}
|
Allow for types with no namespaces | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace FluentMigrator.Runner
{
/// <summary>
/// Advanced searching and filtration of types collections.
/// </summary>
static class TypeFinder
{
/// <summary>
/// Searches for types located in the specifying namespace and optionally in its nested namespaces.
/// </summary>
/// <param name="types">Source types collection to search in.</param>
/// <param name="namespace">Namespace to search types in. Set to null or empty string to search in all namespaces.</param>
/// <param name="loadNestedNamespaces">Set to true to search for types located in nested namespaces of <paramref name="namespace"/>.
/// This parameter is ignored if <paramref name="namespace"/> is null or empty string.
/// </param>
/// <returns>Collection of types matching specified criteria.</returns>
public static IEnumerable<Type> FilterByNamespace(this IEnumerable<Type> types, string @namespace, bool loadNestedNamespaces)
{
if (!string.IsNullOrEmpty(@namespace))
{
Func<Type, bool> shouldInclude = t => t.Namespace == @namespace;
if (loadNestedNamespaces)
{
string matchNested = @namespace + ".";
shouldInclude = t => t.Namespace == @namespace || t.Namespace.StartsWith(matchNested);
}
return types.Where(shouldInclude);
}
else
return types;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace FluentMigrator.Runner
{
/// <summary>
/// Advanced searching and filtration of types collections.
/// </summary>
static class TypeFinder
{
/// <summary>
/// Searches for types located in the specifying namespace and optionally in its nested namespaces.
/// </summary>
/// <param name="types">Source types collection to search in.</param>
/// <param name="namespace">Namespace to search types in. Set to null or empty string to search in all namespaces.</param>
/// <param name="loadNestedNamespaces">Set to true to search for types located in nested namespaces of <paramref name="namespace"/>.
/// This parameter is ignored if <paramref name="namespace"/> is null or empty string.
/// </param>
/// <returns>Collection of types matching specified criteria.</returns>
public static IEnumerable<Type> FilterByNamespace(this IEnumerable<Type> types, string @namespace, bool loadNestedNamespaces)
{
if (!string.IsNullOrEmpty(@namespace))
{
Func<Type, bool> shouldInclude = t => t.Namespace == @namespace;
if (loadNestedNamespaces)
{
string matchNested = @namespace + ".";
shouldInclude = t => t.Namespace != null && (t.Namespace == @namespace || t.Namespace.StartsWith(matchNested));
}
return types.Where(shouldInclude);
}
else
return types;
}
}
}
|
Add windowing subsystem hookup for reflection UsePlatformDetect. | using Avalonia.MonoMac;
using Avalonia.Platform;
[assembly: ExportWindowingSubsystem(OperatingSystemType.OSX, 1, "MonoMac", typeof(MonoMacPlatform), nameof(MonoMacPlatform.Initialize))]
| |
Add unit tests for DefaultSwaggerTagCatalog | using FakeItEasy;
using Nancy.Swagger.Services;
using Swagger.ObjectModel;
using System.Collections.Generic;
using Xunit;
namespace Nancy.Swagger.Tests.Services
{
public class DefaultSwaggerTagCatalogTest
{
private DefaultSwaggerTagCatalog _defaultSwaggerTagCatalog;
public DefaultSwaggerTagCatalogTest()
{
var swaggerTagProvider = A.Fake<IEnumerable<ISwaggerTagProvider>>();
_defaultSwaggerTagCatalog = new DefaultSwaggerTagCatalog(swaggerTagProvider);
}
[Fact]
public void Add_Single_Tag_Should_Succeed()
{
var tag = new Tag() { Name = "tag" };
_defaultSwaggerTagCatalog.AddTag(tag);
Assert.Contains(tag, _defaultSwaggerTagCatalog);
}
[Fact]
public void Add_Multi_Tags_With_Same_Name_Should_Be_Single()
{
var tag1 = new Tag() { Name = "tag" };
var tag2 = new Tag() { Name = "tag" };
_defaultSwaggerTagCatalog.AddTag(tag1);
_defaultSwaggerTagCatalog.AddTag(tag2);
Assert.Single(_defaultSwaggerTagCatalog);
}
[Fact]
public void Add_Multi_Tags_With_Different_Name_Should_Not_Be_Single()
{
var tag1 = new Tag() { Name = "tag1" };
var tag2 = new Tag() { Name = "tag2" };
_defaultSwaggerTagCatalog.AddTag(tag1);
_defaultSwaggerTagCatalog.AddTag(tag2);
Assert.Equal(2, _defaultSwaggerTagCatalog.Count);
}
}
}
| |
Add new [LinkerSafe] attribute - which tells the linker (when enabled) that an assembly is safe to link (even if Link All is not used) | //
// Copyright 2013 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.Foundation {
[AttributeUsage (AttributeTargets.Assembly)]
public sealed class LinkerSafeAttribute : Attribute {
public LinkerSafeAttribute ()
{
}
}
} | |
Add an instant progress bar extension method | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DarkUI.Extensions
{
// https://stackoverflow.com/questions/6071626/progressbar-is-slow-in-windows-forms
public static class ExtensionMethods
{
/// <summary>
/// Sets the progress bar value, without using 'Windows Aero' animation.
/// This is to work around a known WinForms issue where the progress bar
/// is slow to update.
/// </summary>
public static void SetProgressNoAnimation(this ProgressBar pb, int value)
{
// To get around the progressive animation, we need to move the
// progress bar backwards.
if (value == pb.Maximum)
{
// Special case as value can't be set greater than Maximum.
pb.Maximum = value + 1; // Temporarily Increase Maximum
pb.Value = value + 1; // Move past
pb.Maximum = value; // Reset maximum
}
else
{
pb.Value = value + 1; // Move past
}
pb.Value = value; // Move to correct value
}
}
}
| |
Add unit tests for the SqliteAnchorBuilder class | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Openchain.Ledger;
using Xunit;
namespace Openchain.Sqlite.Tests
{
public class SqliteAnchorBuilderTests
{
private readonly SqliteAnchorBuilder anchorBuilder;
public SqliteAnchorBuilderTests()
{
this.anchorBuilder = new SqliteAnchorBuilder(":memory:");
this.anchorBuilder.EnsureTables().Wait();
}
[Fact]
public async Task CreateAnchor_OneTransaction()
{
ByteString hash = await AddRecord("key1");
LedgerAnchor anchor = await this.anchorBuilder.CreateAnchor();
Assert.Equal(1, anchor.TransactionCount);
Assert.Equal(hash, anchor.Position);
Assert.Equal(CombineHashes(new ByteString(new byte[32]), hash), anchor.FullStoreHash);
}
private async Task<ByteString> AddRecord(string key)
{
Mutation mutation = new Mutation(
ByteString.Empty,
new Record[] { new Record(new ByteString(Encoding.UTF8.GetBytes(key)), ByteString.Empty, ByteString.Empty) },
ByteString.Empty);
Transaction transaction = new Transaction(
new ByteString(MessageSerializer.SerializeMutation(mutation)),
new DateTime(),
ByteString.Empty);
await anchorBuilder.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(transaction)) });
return new ByteString(MessageSerializer.ComputeHash(MessageSerializer.SerializeTransaction(transaction)));
}
private static ByteString CombineHashes(ByteString left, ByteString right)
{
using (SHA256 sha = SHA256.Create())
return new ByteString(sha.ComputeHash(sha.ComputeHash(left.ToByteArray().Concat(right.ToByteArray()).ToArray())));
}
}
}
| |
Convert a binary to decimal value | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryToDecimal
{
class Program
{
static void Main(string[] args)
{
//Problem
//Convert a binary n to its decimal value
//Solution
//Create an integer array to store each bit value (101110)
//Loop through the array and if the bit == 1, then calculate 2 to the power of the location in the array
int[] binary = {1,0,1,1};
int result = ConvertToDecimal(binary);
if(result==0)
{
Console.WriteLine("A valid binary number was not provided");
}
else
{
Console.WriteLine("The decimal equivalent is {0}", result);
}
Console.Read();
}
private static int ConvertToDecimal(int[] binary)
{
int decValue = 0;
if(binary.Length == 0)
{
return 0;
}
for (int i = 0; i <= binary.Length - 1; i++)
{
if (binary[i] == 1)
{
decValue += Convert.ToInt16(Math.Pow(2, i));
}
else if(binary[i] > 1)
{
return 0;
}
}
return decValue;
}
}
}
| |
Add tests for Sha256 class | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Algorithms
{
public static class Sha256Tests
{
public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
[Fact]
public static void HashEmpty()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = a.Hash(ReadOnlySpan<byte>.Empty);
Assert.Equal(a.DefaultHashSize, actual.Length);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(16)]
[InlineData(17)]
[InlineData(23)]
[InlineData(31)]
[InlineData(32)]
public static void HashEmptyWithSize(int hashSize)
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize);
var actual = a.Hash(ReadOnlySpan<byte>.Empty, hashSize);
Assert.Equal(hashSize, actual.Length);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(16)]
[InlineData(17)]
[InlineData(23)]
[InlineData(31)]
[InlineData(32)]
public static void HashEmptyWithSpan(int hashSize)
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize);
var actual = new byte[hashSize];
a.Hash(ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
}
}
| |
Add very simple stacking test | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
using Decoder = osu.Game.Beatmaps.Formats.Decoder;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class StackingTest
{
[Test]
public void TestStacking()
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(beatmap_data)))
using (var reader = new StreamReader(stream))
{
var beatmap = Decoder.GetDecoder<Beatmap>(reader).Decode(reader);
var converted = new TestWorkingBeatmap(beatmap).GetPlayableBeatmap(new OsuRuleset().RulesetInfo);
var objects = converted.HitObjects.ToList();
// The last hitobject triggers the stacking
for (int i = 0; i < objects.Count - 1; i++)
Assert.AreEqual(0, ((OsuHitObject)objects[i]).StackHeight);
}
}
private const string beatmap_data = @"
osu file format v14
[General]
StackLeniency: 0.2
[Difficulty]
ApproachRate:9.2
SliderMultiplier:1
SliderTickRate:0.5
[TimingPoints]
217871,6400,4,2,1,20,1,0
217871,-800,4,2,1,20,0,0
218071,-787.5,4,2,1,20,0,0
218271,-775,4,2,1,20,0,0
218471,-762.5,4,2,1,20,0,0
218671,-750,4,2,1,20,0,0
240271,-10,4,2,0,5,0,0
[HitObjects]
311,185,217871,6,0,L|318:158,1,25
311,185,218071,2,0,L|335:170,1,25
311,185,218271,2,0,L|338:192,1,25
311,185,218471,2,0,L|325:209,1,25
311,185,218671,2,0,L|304:212,1,25
311,185,240271,5,0,0:0:0:0:
";
}
}
| |
Change wording on first shiney collect | using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ItemSpawn : MonoBehaviour
{
public string Guid;
public static List<string> CollectedList = new List<string>();
public GameObject Shiney;
public CollectableType ShineyType;
private GuiCanvas _guiCanvas;
// Use this for initialization
void Start ()
{
_guiCanvas = GuiCanvas.Instance;
GetComponent<MeshRenderer>().enabled = false;
if (!CollectedList.Contains(Guid))
{
SpawnCollectable();
}
}
private void SpawnCollectable()
{
var go = Instantiate(Shiney, transform.position, Quaternion.identity) as GameObject;
var collectable = go.GetComponent<Collectable>();
if (collectable != null)
{
collectable.MyType = ShineyType;
}
go.GetComponent<Collectable>().SetCallback(() =>
{
CollectedList.Add(Guid);
if (ShineyType == CollectableType.Good && !State.Instance.
FirstShinyCollected)
{
var lines = new List<Line>
{
new Line("", "Wow! A shining coin! I should find a safe place to stash this.")
};
StartCoroutine(ShowText(lines));
State.Instance.FirstShinyCollected = true;
}
});
}
public IEnumerator ShowText(List<Line> lines)
{
FindObjectOfType<Player>().DisableControl();
yield return StartCoroutine(DialogService.Instance.DisplayLines(lines));
FindObjectOfType<Player>().EnableControl();
}
} | using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ItemSpawn : MonoBehaviour
{
public string Guid;
public static List<string> CollectedList = new List<string>();
public GameObject Shiney;
public CollectableType ShineyType;
private GuiCanvas _guiCanvas;
// Use this for initialization
void Start ()
{
_guiCanvas = GuiCanvas.Instance;
GetComponent<MeshRenderer>().enabled = false;
if (!CollectedList.Contains(Guid))
{
SpawnCollectable();
}
}
private void SpawnCollectable()
{
var go = Instantiate(Shiney, transform.position, Quaternion.identity) as GameObject;
var collectable = go.GetComponent<Collectable>();
if (collectable != null)
{
collectable.MyType = ShineyType;
}
go.GetComponent<Collectable>().SetCallback(() =>
{
CollectedList.Add(Guid);
if (ShineyType == CollectableType.Good && !State.Instance.
FirstShinyCollected)
{
var lines = new List<Line>
{
new Line("", "Wow! A shining treasure! I should find a safe place to stash this.")
};
StartCoroutine(ShowText(lines));
State.Instance.FirstShinyCollected = true;
}
});
}
public IEnumerator ShowText(List<Line> lines)
{
FindObjectOfType<Player>().DisableControl();
yield return StartCoroutine(DialogService.Instance.DisplayLines(lines));
FindObjectOfType<Player>().EnableControl();
}
} |
Add test coverage of beat snapping hit circles | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Tests.Beatmaps;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Tests.Editor
{
[TestFixture]
public class TestSceneObjectBeatSnap : TestSceneOsuEditor
{
private OsuPlayfield playfield;
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(Ruleset.Value, false);
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("get playfield", () => playfield = Editor.ChildrenOfType<OsuPlayfield>().First());
}
[Test]
public void TestBeatSnapHitCircle()
{
double firstTimingPointTime() => Beatmap.Value.Beatmap.ControlPointInfo.TimingPoints.First().Time;
AddStep("seek some milliseconds forward", () => EditorClock.Seek(firstTimingPointTime() + 10));
AddStep("move mouse to centre", () => InputManager.MoveMouseTo(playfield.ScreenSpaceDrawQuad.Centre));
AddStep("enter placement mode", () => InputManager.Key(Key.Number2));
AddStep("place first object", () => InputManager.Click(MouseButton.Left));
AddAssert("ensure object snapped back to correct time", () => EditorBeatmap.HitObjects.First().StartTime == firstTimingPointTime());
}
}
}
| |
Add a test for projection collection | using Sakuno.Collections;
using System.Collections.ObjectModel;
using Xunit;
namespace Sakuno.Base.Tests
{
public static class ProjectionCollectionTests
{
[Fact]
public static void SimpleProjection()
{
var source = new ObservableCollection<int>();
var projection = new ProjectionCollection<int, int>(source, r => r * 2);
source.Add(1);
source.Add(2);
source.Add(3);
source.Add(4);
source.Add(5);
source.Remove(3);
source.Insert(1, 6);
source.Insert(2, 10);
Assert.Equal(projection.Count, source.Count);
using (var projectionEnumerator = projection.GetEnumerator())
using (var sourceEnumerator = source.GetEnumerator())
{
while (projectionEnumerator.MoveNext() && sourceEnumerator.MoveNext())
Assert.Equal(sourceEnumerator.Current * 2, projectionEnumerator.Current);
}
source.Clear();
Assert.Empty(projection);
projection.Dispose();
}
}
}
| |
Add test coverage for song select footer area | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Screens.Select;
namespace osu.Game.Tests.Visual.SongSelect
{
public class TestSceneSongSelectFooter : OsuManualInputManagerTestScene
{
public TestSceneSongSelectFooter()
{
AddStep("Create footer", () =>
{
Footer footer;
AddRange(new Drawable[]
{
footer = new Footer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
});
footer.AddButton(new FooterButtonMods(), null);
footer.AddButton(new FooterButtonRandom
{
NextRandom = () => { },
PreviousRandom = () => { },
}, null);
footer.AddButton(new FooterButtonOptions(), null);
});
}
}
}
| |
Fix startup error - setup root view controller | using UIKit;
using Foundation;
namespace MonoCatalog
{
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application is ready to run
//
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
return true;
}
}
}
| using UIKit;
using Foundation;
namespace MonoCatalog
{
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application is ready to run
//
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
window.RootViewController = navigationController.TopViewController;
window.MakeKeyAndVisible ();
return true;
}
}
}
|
Add sample code in place of Hangman | using System;
public class Hangman {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
| |
Add ${aspnet-traceidentifier} (ASP.NET Core only) | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog.LayoutRenderers;
namespace NLog.Web.LayoutRenderers
{
/// <summary>
/// Print the TraceIdentifier
/// </summary>
/// <remarks>.NET Core Only</remarks>
[LayoutRenderer("aspnet-traceidentifier")]
public class AspNetTraceIdentifierLayoutRenderer : AspNetLayoutRendererBase
{
/// <inheritdoc />
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
builder.Append(context.TraceIdentifier);
}
}
}
| |
Add HTML control so you can add raw html to your layouts | using WootzJs.Web;
namespace WootzJs.Mvc.Mvc.Views
{
public class Html : Control
{
private string html;
public Html(string html)
{
this.html = html;
}
protected override Element CreateNode()
{
var result = Browser.Document.CreateElement("span");
result.InnerHtml = html;
return result;
}
}
} | |
Add tests for wrapping routine provider for Oracle. | using System;
using NUnit.Framework;
using Moq;
using SJP.Schematic.Core;
using System.Data;
namespace SJP.Schematic.Oracle.Tests
{
[TestFixture]
internal static class OracleDatabaseRoutineProviderTests
{
[Test]
public static void Ctor_GivenNullConnection_ThrowsArgNullException()
{
var identifierDefaults = Mock.Of<IIdentifierDefaults>();
var identifierResolver = Mock.Of<IIdentifierResolutionStrategy>();
Assert.Throws<ArgumentNullException>(() => new OracleDatabaseRoutineProvider(null, identifierDefaults, identifierResolver));
}
[Test]
public static void Ctor_GivenNullIdentifierDefaults_ThrowsArgNullException()
{
var connection = Mock.Of<IDbConnection>();
var identifierResolver = Mock.Of<IIdentifierResolutionStrategy>();
Assert.Throws<ArgumentNullException>(() => new OracleDatabaseRoutineProvider(connection, null, identifierResolver));
}
[Test]
public static void Ctor_GivenNullIdentifierResolver_ThrowsArgNullException()
{
var connection = Mock.Of<IDbConnection>();
var identifierDefaults = Mock.Of<IIdentifierDefaults>();
Assert.Throws<ArgumentNullException>(() => new OracleDatabaseRoutineProvider(connection, identifierDefaults, null));
}
[Test]
public static void GetRoutine_GivenNullRoutineName_ThrowsArgNullException()
{
var connection = Mock.Of<IDbConnection>();
var identifierDefaults = Mock.Of<IIdentifierDefaults>();
var identifierResolver = Mock.Of<IIdentifierResolutionStrategy>();
var routineProvider = new OracleDatabaseRoutineProvider(connection, identifierDefaults, identifierResolver);
Assert.Throws<ArgumentNullException>(() => routineProvider.GetRoutine(null));
}
}
}
| |
Add extra checks around the trusting of the value in the file. By default we wont pull over anything invalid and log out when something is wroung. | using System;
using System.Configuration;
using System.IO;
using ZocMonLib;
namespace ZocMonLib
{
public class RecordReduceStatusSourceProviderFile : RecordReduceStatusSourceProvider
{
private readonly ISystemLogger _logger;
private readonly string _reducingStatusTxt = ConfigurationManager.AppSettings["ZocMonIsReducingFilePath"];
public RecordReduceStatusSourceProviderFile(ISettings settings)
{
_logger = settings.LoggerProvider.CreateLogger(typeof(RecordReduceStatusSourceProviderFile));
}
public override string ReadValue()
{
var status = SeedValue();
try
{
if (File.Exists(_reducingStatusTxt))
{
using (TextReader reader = new StreamReader(_reducingStatusTxt))
status = reader.ReadLine();
}
}
catch (Exception e)
{
_logger.Fatal("Something went wrong Reading from " + _reducingStatusTxt, e);
}
return status;
}
public override void WriteValue(string value)
{
try
{
if (!File.Exists(_reducingStatusTxt))
File.Create(_reducingStatusTxt).Dispose();
using (TextWriter writer = new StreamWriter(_reducingStatusTxt))
writer.WriteLine(value);
}
catch (Exception e)
{
_logger.Fatal("Something went wrong Reading from " + _reducingStatusTxt, e);
}
}
}
} | using System;
using System.Configuration;
using System.IO;
using ZocMonLib;
namespace ZocMonLib
{
public class RecordReduceStatusSourceProviderFile : RecordReduceStatusSourceProvider
{
private readonly ISystemLogger _logger;
private readonly string _reducingStatusTxt = ConfigurationManager.AppSettings["ZocMonIsReducingFilePath"];
public RecordReduceStatusSourceProviderFile(ISettings settings)
{
_logger = settings.LoggerProvider.CreateLogger(typeof(RecordReduceStatusSourceProviderFile));
}
public override string ReadValue()
{
var status = SeedValue();
try
{
if (File.Exists(_reducingStatusTxt))
{
using (TextReader reader = new StreamReader(_reducingStatusTxt))
{
var temp = reader.ReadLine();
if (IsValid(temp))
status = temp;
else
_logger.Fatal(String.Format("Value in {0} is invalid: {1} - sould be 1 or 0", _reducingStatusTxt, temp));
}
}
}
catch (Exception e)
{
_logger.Fatal("Something went wrong Reading from " + _reducingStatusTxt, e);
}
return status;
}
public override void WriteValue(string value)
{
try
{
if (!File.Exists(_reducingStatusTxt))
File.Create(_reducingStatusTxt).Dispose();
using (TextWriter writer = new StreamWriter(_reducingStatusTxt))
writer.WriteLine(value);
}
catch (Exception e)
{
_logger.Fatal("Something went wrong Reading from " + _reducingStatusTxt, e);
}
}
}
} |
Add missing project installer file | namespace Fr.Lakitrid.DomoCore
{
partial class ProjectInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DomoCorePInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.DomoCoreInstaller = new System.ServiceProcess.ServiceInstaller();
//
// DomoCorePInstaller
//
this.DomoCorePInstaller.Password = null;
this.DomoCorePInstaller.Username = null;
//
// DomoCoreInstaller
//
this.DomoCoreInstaller.ServiceName = "DomoCoreService";
this.DomoCoreInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.DomoCorePInstaller,
this.DomoCoreInstaller});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller DomoCorePInstaller;
private System.ServiceProcess.ServiceInstaller DomoCoreInstaller;
}
} | |
Add a logout IT class | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json;
using Stormpath.SDK.Account;
using Stormpath.SDK.Client;
using Stormpath.SDK.Resource;
using Xunit;
namespace Stormpath.Owin.IntegrationTest
{
public class LogoutRouteShould
{
[Fact]
public async Task DeleteCookiesProperly()
{
// Arrange
var fixture = new OwinTestFixture();
var server = Helpers.CreateServer(fixture);
using (var cleanup = new AutoCleanup(fixture.Client))
{
// Create a user
var application = await fixture.Client.GetApplicationAsync(fixture.ApplicationHref);
var email = $"its-{fixture.TestKey}@example.com";
var account = await application.CreateAccountAsync(
nameof(DeleteCookiesProperly),
nameof(LogoutRouteShould),
email,
"Changeme123!!");
cleanup.MarkForDeletion(account);
// Get a token
var payload = new Dictionary<string, string>
{
["grant_type"] = "password",
["username"] = email,
["password"] = "Changeme123!!"
};
var tokenResponse = await server.PostAsync("/oauth/token", new FormUrlEncodedContent(payload));
tokenResponse.EnsureSuccessStatusCode();
var tokenResponseContent = JsonConvert.DeserializeObject<Dictionary<string, string>>(await tokenResponse.Content.ReadAsStringAsync());
var accessToken = tokenResponseContent["access_token"];
var refreshToken = tokenResponseContent["refresh_token"];
// Create a logout request
var logoutRequest = new HttpRequestMessage(HttpMethod.Post, "/logout");
logoutRequest.Headers.Add("Cookie", $"access_token={accessToken}");
logoutRequest.Headers.Add("Cookie", $"refresh_token={refreshToken}");
logoutRequest.Content = new FormUrlEncodedContent(new KeyValuePair<string, string>[0]);
// Act
var logoutResponse = await server.SendAsync(logoutRequest);
logoutResponse.EnsureSuccessStatusCode();
// Assert
var setCookieHeaders = logoutResponse.Headers.GetValues("Set-Cookie").ToArray();
setCookieHeaders.Length.Should().Be(2);
setCookieHeaders.Should().Contain("access_token=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT; HttpOnly");
setCookieHeaders.Should().Contain("refresh_token=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT; HttpOnly");
}
}
}
}
| |
Use correct assembly to retrieve ProdInfo | using System;
using System.Reflection;
namespace NMaier.SimpleDlna.Utilities
{
public static class ProductInformation
{
public static string Company
{
get
{
var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
public static string Copyright
{
get
{
var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public static string ProductVersion
{
get
{
var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion;
}
}
public static string Title
{
get
{
var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0) {
var titleAttribute = (AssemblyTitleAttribute)attributes[0];
if (!string.IsNullOrWhiteSpace(titleAttribute.Title)) {
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
}
}
| using System;
using System.Reflection;
namespace NMaier.SimpleDlna.Utilities
{
public static class ProductInformation
{
public static string Company
{
get
{
var attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
public static string Copyright
{
get
{
var attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public static string ProductVersion
{
get
{
var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
if (attributes.Length == 0) {
return string.Empty;
}
return ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion;
}
}
public static string Title
{
get
{
var attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0) {
var titleAttribute = (AssemblyTitleAttribute)attributes[0];
if (!string.IsNullOrWhiteSpace(titleAttribute.Title)) {
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
}
}
|
Add proper error handling for IO errors. | namespace dotless.Core
{
using System.IO.Compression;
using System.Web;
using configuration;
using Microsoft.Practices.ServiceLocation;
public class LessCssHttpHandler : IHttpHandler
{
public IServiceLocator Container { get; set; }
public DotlessConfiguration Config { get; set; }
public LessCssHttpHandler()
{
Config = new WebConfigConfigurationLoader().GetConfiguration();
Container = new ContainerFactory().GetContainer(Config);
}
public void ProcessRequest(HttpContext context)
{
string acceptEncoding = (context.Request.Headers["Accept-Encoding"] ?? "").ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
context.Response.AppendHeader("Content-Encoding", "gzip");
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
context.Response.AppendHeader("Content-Encoding", "deflate");
context.Response.Filter = new DeflateStream(context.Response.Filter,
CompressionMode.Compress);
}
var handler = Container.GetInstance<HandlerImpl>();
handler.Execute();
}
public bool IsReusable
{
get { return true; }
}
}
} | namespace dotless.Core
{
using System.IO.Compression;
using System.Web;
using configuration;
using Microsoft.Practices.ServiceLocation;
public class LessCssHttpHandler : IHttpHandler
{
public IServiceLocator Container { get; set; }
public DotlessConfiguration Config { get; set; }
public LessCssHttpHandler()
{
Config = new WebConfigConfigurationLoader().GetConfiguration();
Container = new ContainerFactory().GetContainer(Config);
}
public void ProcessRequest(HttpContext context)
{
try {
string acceptEncoding = (context.Request.Headers["Accept-Encoding"] ?? "").ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
context.Response.AppendHeader("Content-Encoding", "gzip");
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
context.Response.AppendHeader("Content-Encoding", "deflate");
context.Response.Filter = new DeflateStream(context.Response.Filter,
CompressionMode.Compress);
}
var handler = Container.GetInstance<HandlerImpl>();
handler.Execute();
} catch (System.IO.FileNotFoundException ex){
context.Response.StatusCode = 404;
context.Response.Write("/* File Not Found while parsing: "+ex.Message+" */");
context.Response.End();
} catch (System.IO.IOException ex){
context.Response.StatusCode = 500;
context.Response.Write("/* Error in less parsing: "+ex.Message+" */");
context.Response.End();
}
}
public bool IsReusable
{
get { return true; }
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.