doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
aba7cdce-758b-406e-8b16-d3836ce5be6b | {
"language": "C#"
} | ```c#
// 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.Input.Bindings;
using osu.Framework.Input.States;
using osuTK.Input;
using KeyboardState = osu.Framework.Input.States.KeyboardState;
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationTest
{
[Test]
public void TestKeyCombinationDisplayTrueOrder()
{
var keyCombination1 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
var keyCombination2 = new KeyCombination(InputKey.R, InputKey.Shift, InputKey.Control);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
[Test]
public void TestKeyCombinationFromKeyboardStateDisplayTrueOrder()
{
var keyboardState = new KeyboardState();
keyboardState.Keys.Add(Key.R);
keyboardState.Keys.Add(Key.LShift);
keyboardState.Keys.Add(Key.LControl);
var keyCombination1 = KeyCombination.FromInputState(new InputState(keyboard: keyboardState));
var keyCombination2 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
}
}
```
Make tests actually test the string output | ```c#
// 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.Input.Bindings;
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationTest
{
private static readonly object[][] key_combination_display_test_cases =
{
new object[] { new KeyCombination(InputKey.Alt, InputKey.F4), "Alt-F4" },
new object[] { new KeyCombination(InputKey.D, InputKey.Control), "Ctrl-D" },
new object[] { new KeyCombination(InputKey.Shift, InputKey.F, InputKey.Control), "Ctrl-Shift-F" },
new object[] { new KeyCombination(InputKey.Alt, InputKey.Control, InputKey.Super, InputKey.Shift), "Ctrl-Alt-Shift-Win" }
};
[TestCaseSource(nameof(key_combination_display_test_cases))]
public void TestKeyCombinationDisplayOrder(KeyCombination keyCombination, string expectedRepresentation)
=> Assert.That(keyCombination.ReadableString(), Is.EqualTo(expectedRepresentation));
}
}
``` |
d7f08b6f-af7f-442e-a140-7271bcb1a930 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperPostRepository : DapperRepositoryBase, IPostRepository
{
public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
{
}
public void Create(Post post)
{
throw new NotImplementedException();
}
public void AddDetails(int postId, PostDetails details)
{
throw new NotImplementedException();
}
public bool Delete(int postId)
{
throw new NotImplementedException();
}
public bool DeleteDetails(int detailsId)
{
throw new NotImplementedException();
}
public List<Post> GetPostsForUser(int userId)
{
throw new NotImplementedException();
}
public Post Get(int id)
{
throw new NotImplementedException();
}
public PostDetails GetDetails(int postId, int sequence)
{
throw new NotImplementedException();
}
public bool Update(Post post)
{
throw new NotImplementedException();
}
public bool UpdateDetails(PostDetails details)
{
throw new NotImplementedException();
}
}
}
```
Add basic Get for a post | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperPostRepository : DapperRepositoryBase, IPostRepository
{
public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
{
}
public void Create(Post post)
{
throw new NotImplementedException();
}
public void AddDetails(int postId, PostDetails details)
{
throw new NotImplementedException();
}
public bool Delete(int postId)
{
throw new NotImplementedException();
}
public bool DeleteDetails(int detailsId)
{
throw new NotImplementedException();
}
public List<Post> GetPostsForUser(int userId)
{
throw new NotImplementedException();
}
public Post Get(int id)
{
const string sql = "SELECT * FROM [Posts] WHERE [Id] = @postId";
var post = Fetch(c => c.Query<Post>(sql, new { postId = id })).SingleOrDefault();
return post;
}
public PostDetails GetDetails(int postId, int sequence)
{
throw new NotImplementedException();
}
public bool Update(Post post)
{
throw new NotImplementedException();
}
public bool UpdateDetails(PostDetails details)
{
throw new NotImplementedException();
}
}
}
``` |
7188364b-6c71-4c34-bda5-f4a169ecf87d | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;
namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
[TestFixture]
public class ErrorConditionTests
{
[Test]
public void Should_fail_with_input_parameter_exception_if_xml_error_returned()
{
// -- Deliberate error response
Console.WriteLine("Trying artist/details without artistId parameter...");
var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please());
Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing));
Assert.That(apiXmlException.Message, Is.EqualTo("Missing parameter artistId"));
}
[Test]
public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised()
{
// -- Deliberate unauthorized response
Console.WriteLine("Trying user/locker without any credentials...");
var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please());
Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token"));
}
}
}```
Make inputexception message tests more robust | ```c#
using System;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;
namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
[TestFixture]
public class ErrorConditionTests
{
[Test]
public void Should_fail_with_input_parameter_exception_if_xml_error_returned()
{
// -- Deliberate error response
Console.WriteLine("Trying artist/details without artistId parameter...");
var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please());
Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing));
Assert.That(apiXmlException.Message, Is.StringStarting("Missing parameter artistId"));
}
[Test]
public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised()
{
// -- Deliberate unauthorized response
Console.WriteLine("Trying user/locker without any credentials...");
var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please());
Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token"));
}
}
}``` |
134ed92e-4eda-4c2d-a0b9-eee81ccdfb9e | {
"language": "C#"
} | ```c#
using System.IO;
namespace NuGet.Extensions.Tests.TestData
{
public class Isolation
{
public static DirectoryInfo GetIsolatedTestSolutionDir()
{
var solutionDir = new DirectoryInfo(Path.GetRandomFileName());
CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
return solutionDir;
}
public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
{
var packageSource = new DirectoryInfo(Path.GetRandomFileName());
CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
return packageSource;
}
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
if (!target.Exists) target.Create();
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
}
}```
Create temp directories in temp folder | ```c#
using System.IO;
namespace NuGet.Extensions.Tests.TestData
{
public class Isolation
{
public static DirectoryInfo GetIsolatedTestSolutionDir()
{
var solutionDir = new DirectoryInfo(GetRandomTempDirectoryPath());
CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
return solutionDir;
}
private static string GetRandomTempDirectoryPath()
{
return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
{
var packageSource = new DirectoryInfo(GetRandomTempDirectoryPath());
CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
return packageSource;
}
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
if (!target.Exists) target.Create();
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
}
}``` |
83751c3a-bef9-4aaf-92db-7a944c905418 | {
"language": "C#"
} | ```c#
// Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(object inputEvent, ILambdaContext context)
{
context.Logger.Log($"inputEvent: {inputEvent}");
return "Hello World!";
}
}
}
```
Add RemainingTime and env vars to dotnetcore2.0 example | ```c#
// Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using System;
using System.Collections;
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(object inputEvent, ILambdaContext context)
{
context.Logger.Log($"inputEvent: {inputEvent}");
LambdaLogger.Log($"RemainingTime: {context.RemainingTime}");
foreach (DictionaryEntry kv in Environment.GetEnvironmentVariables())
{
context.Logger.Log($"{kv.Key}={kv.Value}");
}
return "Hello World!";
}
}
}
``` |
b1ad7865-2fc1-4a97-bfee-403479b655c8 | {
"language": "C#"
} | ```c#
using System.Linq;
using GitVersion;
using GitVersionTask;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Shouldly;
[TestFixture]
public class GetVersionTaskTests
{
[Test]
public void OutputsShouldMatchVariableProvider()
{
var taskProperties = typeof(GetVersion)
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any())
.Select(p => p.Name);
var variablesProperties = typeof(VersionVariables)
.GetProperties()
.Select(p => p.Name)
.Except(new[] { "AvailableVariables", "Item" });
taskProperties.ShouldBe(variablesProperties, ignoreOrder: true);
}
}
```
Use the AvailableVariables property instead of doing GetProperties() everywhere. | ```c#
using System.Linq;
using GitVersion;
using GitVersionTask;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Shouldly;
[TestFixture]
public class GetVersionTaskTests
{
[Test]
public void OutputsShouldMatchVariableProvider()
{
var taskProperties = typeof(GetVersion)
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any())
.Select(p => p.Name);
var variablesProperties = VersionVariables.AvailableVariables;
taskProperties.ShouldBe(variablesProperties, ignoreOrder: true);
}
}
``` |
f1a9a521-bcc9-43a2-9df9-690566853cf6 | {
"language": "C#"
} | ```c#
using System;
namespace WundergroundClient.Autocomplete
{
enum ResultFilter
{
CitiesOnly,
HurricanesOnly,
CitiesAndHurricanes
}
class AutocompleteRequest
{
private String _searchString;
private ResultFilter _filter = ResultFilter.CitiesOnly;
private String _countryCode = null;
public AutocompleteRequest(String searchString)
{
_searchString = searchString;
}
public AutocompleteRequest(String query, ResultFilter filter)
{
_searchString = query;
_filter = filter;
}
public AutocompleteRequest(String searchString, ResultFilter filter, string countryCode)
{
_searchString = searchString;
_filter = filter;
_countryCode = countryCode;
}
//public async Task<String> ExecuteAsync()
//{
//}
}
}
```
Add comments to constructors, use constructor chaining. | ```c#
using System;
namespace WundergroundClient.Autocomplete
{
enum ResultFilter
{
CitiesOnly,
HurricanesOnly,
CitiesAndHurricanes
}
class AutocompleteRequest
{
private const String BaseUrl = "http://autocomplete.wunderground.com/";
private readonly String _searchString;
private readonly ResultFilter _filter;
private readonly String _countryCode;
/// <summary>
/// Creates a request to search for cities.
/// </summary>
/// <param name="city">The full or partial name of a city to look for.</param>
public AutocompleteRequest(String city) : this(city, ResultFilter.CitiesOnly, null)
{
}
/// <summary>
/// Creates a general query for cities, hurricanes, or both.
/// </summary>
/// <param name="query">The full or partial name to be looked up.</param>
/// <param name="filter">The types of results that are expected.</param>
public AutocompleteRequest(String query, ResultFilter filter) : this(query, filter, null)
{
}
/// <summary>
/// Creates a query for cities, hurricanes, or both,
/// restricted to a particular country.
///
/// Note: Wunderground does not use the standard ISO country codes.
/// See http://www.wunderground.com/weather/api/d/docs?d=resources/country-to-iso-matching
/// </summary>
/// <param name="query">The full or partial name to be looked up.</param>
/// <param name="filter">The types of results that are expected.</param>
/// <param name="countryCode">The Wunderground country code to restrict results to.</param>
public AutocompleteRequest(String query, ResultFilter filter, String countryCode)
{
_searchString = query;
_filter = filter;
_countryCode = countryCode;
}
//public async Task<String> ExecuteAsync()
//{
//}
}
}
``` |
07c9ef69-5f66-4d16-8b08-dda83dbcad71 | {
"language": "C#"
} | ```c#
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.Domain.Systems;
namespace OpenStardriveServer.HostedServices;
public class ServerInitializationService : BackgroundService
{
private readonly IRegisterSystemsCommand registerSystemsCommand;
private readonly ISqliteDatabaseInitializer sqliteDatabaseInitializer;
private readonly ILogger<ServerInitializationService> logger;
public ServerInitializationService(IRegisterSystemsCommand registerSystemsCommand,
ISqliteDatabaseInitializer sqliteDatabaseInitializer,
ILogger<ServerInitializationService> logger)
{
this.sqliteDatabaseInitializer = sqliteDatabaseInitializer;
this.logger = logger;
this.registerSystemsCommand = registerSystemsCommand;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Registering systems...");
registerSystemsCommand.Register();
logger.LogInformation("Initializing database...");
await sqliteDatabaseInitializer.Initialize();
logger.LogInformation("Server ready");
}
}```
Initialize the server with a report-state command | ```c#
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenStardriveServer.Domain;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.Domain.Systems;
namespace OpenStardriveServer.HostedServices;
public class ServerInitializationService : BackgroundService
{
private readonly IRegisterSystemsCommand registerSystemsCommand;
private readonly ISqliteDatabaseInitializer sqliteDatabaseInitializer;
private readonly ILogger<ServerInitializationService> logger;
private readonly ICommandRepository commandRepository;
public ServerInitializationService(IRegisterSystemsCommand registerSystemsCommand,
ISqliteDatabaseInitializer sqliteDatabaseInitializer,
ILogger<ServerInitializationService> logger,
ICommandRepository commandRepository)
{
this.sqliteDatabaseInitializer = sqliteDatabaseInitializer;
this.logger = logger;
this.commandRepository = commandRepository;
this.registerSystemsCommand = registerSystemsCommand;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Registering systems...");
registerSystemsCommand.Register();
logger.LogInformation("Initializing database...");
await sqliteDatabaseInitializer.Initialize();
await commandRepository.Save(new Command { Type = "report-state" });
logger.LogInformation("Server ready");
}
}``` |
9f75e698-504c-40f4-afaa-325e73ebbd6e | {
"language": "C#"
} | ```c#
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Google.Cloud.Translation.V2.Tests
{
public class CodeHealthTest
{
// TODO: Remove the autogenerated type exemptions when we depend on the package instead.
[Fact]
public void PrivateFields()
{
CodeHealthTester.AssertAllFieldsPrivate(typeof(TranslationClient), GetExemptedTypes());
}
[Fact]
public void SealedClasses()
{
CodeHealthTester.AssertClassesAreSealedOrAbstract(typeof(TranslationClient), GetExemptedTypes());
}
private static IEnumerable<Type> GetExemptedTypes() =>
typeof(TranslationClient).GetTypeInfo().Assembly.DefinedTypes
.Where(t => t.Namespace.StartsWith("Google.Apis."))
.Select(t => t.AsType())
.ToList();
}
}
```
Clean up Translation code health test | ```c#
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using Xunit;
namespace Google.Cloud.Translation.V2.Tests
{
public class CodeHealthTest
{
[Fact]
public void PrivateFields()
{
CodeHealthTester.AssertAllFieldsPrivate(typeof(TranslationClient));
}
[Fact]
public void SealedClasses()
{
CodeHealthTester.AssertClassesAreSealedOrAbstract(typeof(TranslationClient));
}
}
}
``` |
629fb80d-2dd5-438c-9038-13fd194fa72c | {
"language": "C#"
} | ```c#
@{ViewBag.Title = "Home";}
<div class="jumbotron">
<h1>CasperJS Testing!</h1>
<p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p>
<p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
<div class="row">
<div class="col-xs-1 imgbg">
<img src="~/Content/casperjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS.
<a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs
</div>
<div class="col-xs-1 imgbg">
<img src="~/Content/phantomjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
<a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
</div>
</div>
```
Remove second build step from TC, thanks to Sean | ```c#
@{ViewBag.Title = "Home";}
<div class="jumbotron">
<h1>CasperJS Testing!!!</h1>
<p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p>
<p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
<div class="row">
<div class="col-xs-1 imgbg">
<img src="~/Content/casperjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS.
<a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs
</div>
<div class="col-xs-1 imgbg">
<img src="~/Content/phantomjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
<a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
</div>
</div>
``` |
5ed783c5-6540-451e-a51d-9e655e0c440c | {
"language": "C#"
} | ```c#
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Console.WriteLine(type.IsClass && type.IsPublic && type.BaseType != typeof (MulticastDelegate));
Console.WriteLine(!(type.IsAbstract && type.IsSealed));
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
```
Remove some spurious Console.WriteLine() calls from a test. | ```c#
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
``` |
5e3fd3e1-c41f-4917-8da5-6cb0b573b119 | {
"language": "C#"
} | ```c#
using DarkSky.Models;
using DarkSky.Services;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
using WeatherLink.Models;
namespace WeatherLink.Services
{
/// <summary>
/// A service to get a Dark Sky forecast for a latitude and longitude.
/// </summary>
public class HourlyAndMinutelyDarkSkyService : IDarkSkyService
{
private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters() { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } };
private readonly DarkSkyService _darkSkyService;
/// <summary>
/// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data.
/// </summary>
/// <param name="optionsAccessor"></param>
public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor)
{
_darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey);
}
/// <summary>
/// Make a request to get forecast data.
/// </summary>
/// <param name="latitude">Latitude to request data for in decimal degrees.</param>
/// <param name="longitude">Longitude to request data for in decimal degrees.</param>
/// <returns>A DarkSkyResponse with the API headers and data.</returns>
public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude)
{
return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters);
}
}
}```
Fix warning about empty constructor | ```c#
using DarkSky.Models;
using DarkSky.Services;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
using WeatherLink.Models;
namespace WeatherLink.Services
{
/// <summary>
/// A service to get a Dark Sky forecast for a latitude and longitude.
/// </summary>
public class HourlyAndMinutelyDarkSkyService : IDarkSkyService
{
private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } };
private readonly DarkSkyService _darkSkyService;
/// <summary>
/// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data.
/// </summary>
/// <param name="optionsAccessor"></param>
public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor)
{
_darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey);
}
/// <summary>
/// Make a request to get forecast data.
/// </summary>
/// <param name="latitude">Latitude to request data for in decimal degrees.</param>
/// <param name="longitude">Longitude to request data for in decimal degrees.</param>
/// <returns>A DarkSkyResponse with the API headers and data.</returns>
public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude)
{
return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters);
}
}
}``` |
64ee5821-4b9b-47a4-8b46-9a5157d62dd6 | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
double num = 0.0;
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
string[] array = timeString.Split(':');
foreach (string s in array)
{
double num2;
if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out num2))
{
num = num * 60.0 + num2;
}
else
{
throw new Exception();
}
}
if (factor * num > 864000)
throw new Exception();
return new TimeSpan((long)(factor * num * 10000000));
}
}
}
```
Rewrite of the Time Parsing code | ```c#
using System;
using System.Linq;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
var seconds = timeString
.Split(':')
.Select(x => Double.Parse(x, NumberStyles.Float, CultureInfo.InvariantCulture))
.Aggregate(0.0, (a, b) => 60 * a + b);
return TimeSpan.FromSeconds(factor * seconds);
}
}
}
``` |
ecd2a6ee-2c68-4656-8bbe-f0ae44250021 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 200),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
```
Increase editor verify settings width to give more breathing space | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 225),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
``` |
d4f52b63-5bf0-44bf-aa8e-70126cce13d0 | {
"language": "C#"
} | ```c#
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
```
Set compatibility version to 2.2 in hello world sample project | ```c#
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddFluentActions()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
``` |
465241b9-60fc-4f1f-977d-ffaca1b5780e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StreamDeckSharp
{
/// <summary>
/// </summary>
/// <remarks>
/// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation.
/// This extension class adds some commonly used functions to make things simpler.
/// </remarks>
public static class StreamDeckExtensions
{
public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap)
{
deck.SetKeyBitmap(keyId, bitmap.rawBitmapData);
}
public static void ClearKey(this IStreamDeck deck, int keyId)
{
deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black);
}
public static void ClearKeys(this IStreamDeck deck)
{
for (int i = 0; i < StreamDeckHID.numOfKeys; i++)
deck.SetKeyBitmap(i, StreamDeckKeyBitmap.Black);
}
}
}
```
Add extension method to set bitmap for all keys (+Xml documentation) | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StreamDeckSharp
{
/// <summary>
/// </summary>
/// <remarks>
/// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation.
/// This extension class adds some commonly used functions to make things simpler.
/// </remarks>
public static class StreamDeckExtensions
{
/// <summary>
/// Sets a background image for a given key
/// </summary>
/// <param name="deck"></param>
/// <param name="keyId"></param>
/// <param name="bitmap"></param>
public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap)
{
deck.SetKeyBitmap(keyId, bitmap.rawBitmapData);
}
/// <summary>
/// Sets a background image for all keys
/// </summary>
/// <param name="deck"></param>
/// <param name="bitmap"></param>
public static void SetKeyBitmap(this IStreamDeck deck, StreamDeckKeyBitmap bitmap)
{
for (int i = 0; i < StreamDeckHID.numOfKeys; i++)
deck.SetKeyBitmap(i, bitmap.rawBitmapData);
}
/// <summary>
/// Sets background to black for a given key
/// </summary>
/// <param name="deck"></param>
/// <param name="keyId"></param>
public static void ClearKey(this IStreamDeck deck, int keyId)
{
deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black);
}
/// <summary>
/// Sets background to black for all given keys
/// </summary>
/// <param name="deck"></param>
public static void ClearKeys(this IStreamDeck deck)
{
deck.SetKeyBitmap(StreamDeckKeyBitmap.Black);
}
}
}
``` |
d2faf55d-3b0d-469d-a2bd-0e98be4c871b | {
"language": "C#"
} | ```c#
using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
```
Fix ReturnsDefaultRepresenationCurrentCulture test for all cultures | ```c#
using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
``` |
0248858c-d974-42f1-890a-e96608981b99 | {
"language": "C#"
} | ```c#
namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
var parser = new CssParser(source, configuration);
parser.Parse(new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
});
}
}
}
```
Use CssParser front-end as intended | ```c#
namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
static readonly CssParserOptions options = new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
};
static readonly CssParser parser = new CssParser(options, configuration);
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
parser.ParseStylesheet(source);
}
}
}
``` |
6fe80e49-e0bc-46e6-843f-417faf15a618 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
```
Add some more properties to hover info. | ```c#
using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
public string parameter;
public string propagatedType;
public string staticType;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
``` |
0f4a1142-bf8e-423e-a1b7-493e736cf9c4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select(item =>
new string(item.PadRight(9).Reverse().ToArray())))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
```
Implement the second overload of Select | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, int, TResult> transform)
{
int index = 0;
foreach (TSource item in inputSequence)
yield return transform(item, index++);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select((item, index) =>
new { index, item }))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
``` |
e31fad45-f5b7-4cb2-b03e-921cf4ebda1d | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
DataTable table = doQuery(sql);
foreach(DataRow row in table.Rows)
{
TableRow trow = new TableRow();
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].ColumnName == "customer") continue;
if (table.Columns[i].ColumnName == "id") continue;
TableCell cell = new TableCell();
cell.Text = row[i].ToString();
trow.Cells.Add(cell);
}
TableEquipments.Rows.Add(trow);
}
}
}
```
Update sql commands and use the new method | ```c#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
fillTable(sql, ref TableEquipments);
}
}
``` |
4873ec8c-c657-451e-a40c-889d680c3976 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
[SetUp()]
public void SetUp()
{
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(new Act("Act 1",actor,null ));
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{new Act("Act 1",actor,null ),new Act("Act 2", actor,null)});
}
[Test()]
public void GetPossibleActionsFromScene()
{
//arrange
//act
actor.Act(scene.Object);
var actions = actor.AllActions;
//assert
Assert.AreNotEqual(0, actions.Count);
}
}
}
```
Fix tests - all green | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
private Mock<IAct> act;
[SetUp()]
public void SetUp()
{
act = new Mock<IAct>();
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(act.Object);
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{act.Object});
}
[Test()]
public void ActOnScene()
{
//arrange
//act
actor.Act(scene.Object);
//assert
act.Verify(m => m.Do(scene.Object));
}
}
}
``` |
6dc370dd-95eb-4b25-832b-799e8f497817 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
using TeleBot.API.Enums;
namespace TeleBot.API.Extensions
{
public class ParseModeEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var enumString = (string)reader.Value;
return Enum.Parse(typeof(ParseMode), enumString, true);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!value.Equals(ParseMode.Default))
{
var type = (ParseMode)value;
writer.WriteValue(type.ToString());
}
else return;
}
}
}
```
Remove unnecessary else statement. Remove unnecessary return statement. | ```c#
using System;
using Newtonsoft.Json;
using TeleBot.API.Enums;
namespace TeleBot.API.Extensions
{
public class ParseModeEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var enumString = (string)reader.Value;
return Enum.Parse(typeof(ParseMode), enumString, true);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!value.Equals(ParseMode.Default))
{
var type = (ParseMode)value;
writer.WriteValue(type.ToString());
}
}
}
}
``` |
028b63b0-ad25-46e2-ab48-df77b021edb2 | {
"language": "C#"
} | ```c#
using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void Edit(ApplicationUser entity);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
```
Revert "Added edit method into UserRepository" | ```c#
using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
``` |
40f417dd-d0bf-469a-a3d3-bf1b5560d38b | {
"language": "C#"
} | ```c#
// Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index("IX_HangfireServer_Heartbeat")]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
}```
Remove heartbeat server property index name | ```c#
// Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
}``` |
8efe1fea-65f7-4647-9bbb-0953dbfa5c26 | {
"language": "C#"
} | ```c#
using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid id)
{
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
}```
Handle null id for Cars/Details action | ```c#
using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
}``` |
10f22612-69af-4284-8e7a-51c8848c47d2 | {
"language": "C#"
} | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Data;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TextBlockTests
{
[Fact]
public void DefaultBindingMode_Should_Be_OneWay()
{
Assert.Equal(
BindingMode.OneWay,
TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode);
}
}
}
```
Add test that default value of TextBlock.Text property is empty string. | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Data;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TextBlockTests
{
[Fact]
public void DefaultBindingMode_Should_Be_OneWay()
{
Assert.Equal(
BindingMode.OneWay,
TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode);
}
[Fact]
public void Default_Text_Value_Should_Be_EmptyString()
{
var textBlock = new TextBlock();
Assert.Equal(
"",
textBlock.Text);
}
}
}
``` |
5744da11-131f-4fb0-b160-c72e2fc9cf26 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
using UltimaRX.Proxy.InjectionApi;
namespace Infusion.Desktop
{
internal static class InterProcessCommunication
{
private static readonly EventWaitHandle MessageSentEvent = new EventWaitHandle(false, EventResetMode.ManualReset,
"Infusion.Desktop.CommandMessageSent");
public static void StartReceiving()
{
var receivingThread = new Thread(ReceivingLoop);
receivingThread.Start();
}
private static void ReceivingLoop(object data)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
while (true)
{
MessageSentEvent.WaitOne();
string command;
using (var stream = messageFile.CreateViewStream())
{
using (var reader = new StreamReader(stream))
{
command = reader.ReadLine();
}
}
if (!string.IsNullOrEmpty(command))
{
if (command.StartsWith(","))
Injection.CommandHandler.Invoke(command);
else
Injection.CommandHandler.Invoke("," + command);
}
}
}
public static void SendCommand(string command)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
using (var stream = messageFile.CreateViewStream())
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(command);
writer.Flush();
}
}
MessageSentEvent.Set();
MessageSentEvent.Reset();
}
}
}```
Use background thread, otherwise process is not terminated after closing application window. | ```c#
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
using UltimaRX.Proxy.InjectionApi;
namespace Infusion.Desktop
{
internal static class InterProcessCommunication
{
private static readonly EventWaitHandle MessageSentEvent = new EventWaitHandle(false, EventResetMode.ManualReset,
"Infusion.Desktop.CommandMessageSent");
public static void StartReceiving()
{
var receivingThread = new Thread(ReceivingLoop);
receivingThread.IsBackground = true;
receivingThread.Start();
}
private static void ReceivingLoop(object data)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
while (true)
{
MessageSentEvent.WaitOne();
string command;
using (var stream = messageFile.CreateViewStream())
{
using (var reader = new StreamReader(stream))
{
command = reader.ReadLine();
}
}
if (!string.IsNullOrEmpty(command))
{
if (command.StartsWith(","))
Injection.CommandHandler.Invoke(command);
else
Injection.CommandHandler.Invoke("," + command);
}
}
}
public static void SendCommand(string command)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
using (var stream = messageFile.CreateViewStream())
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(command);
writer.Flush();
}
}
MessageSentEvent.Set();
MessageSentEvent.Reset();
}
}
}``` |
76036146-643e-4afa-ac71-2331a2e59e0f | {
"language": "C#"
} | ```c#
using Xunit;
using System.IO;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
convertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
Assert.Empty(result.Warnings);
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> convertToHtml(string name) {
return new DocumentConverter().ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
```
Add test for reading files with UTF-8 BOM | ```c#
using Xunit;
using System.IO;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
ConvertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
[Fact]
public void CanReadFilesWithUtf8Bom() {
assertSuccessfulConversion(
ConvertToHtml("utf8-bom.docx"),
"<p>This XML has a byte order mark.</p>");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
Assert.Empty(result.Warnings);
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> ConvertToHtml(string name) {
return new DocumentConverter().ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
``` |
1cbcda55-0e28-477e-82dd-cca62572d670 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using MyApplication.dependencies;
using System.Collections.Generic;
namespace MyApplication
{
public class PersonService
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonService"/> class.
/// </summary>
public PersonService()
{
AgeGroupMap = new Dictionary<int,AgeGroup>();
AgeGroupMap[14] = AgeGroup.Child;
AgeGroupMap[18] = AgeGroup.Teen;
AgeGroupMap[25] = AgeGroup.YoungAdult;
AgeGroupMap[75] = AgeGroup.Adult;
AgeGroupMap[999] = AgeGroup.Retired;
}
public Dictionary<int, AgeGroup> AgeGroupMap { get; set; }
/// <summary>
/// Gets the age group for a particular customer.
/// </summary>
/// <param name="customer">The customer to calculate the AgeGroup of.</param>
/// <returns>The correct age group for the customer</returns>
/// <exception cref="System.ApplicationException">If the customer is invalid</exception>
public AgeGroup GetAgeGroup(Person customer)
{
if (!customer.IsValid())
{
throw new ApplicationException("customer is invalid");
}
// Calculate age
DateTime zeroTime = new DateTime(1, 1, 1);
int age = (zeroTime + (DateTime.Today - customer.DOB)).Year;
// Return the correct age group
return AgeGroupMap.OrderBy(x => x.Key).First(x => x.Key < age).Value;
}
}
}```
Make initial task easier given the number of refactorings needed. | ```c#
using System;
using System.Linq;
using MyApplication.dependencies;
using System.Collections.Generic;
namespace MyApplication
{
public class PersonService
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonService"/> class.
/// </summary>
public PersonService()
{
AgeGroupMap = new Dictionary<int,AgeGroup>();
AgeGroupMap[14] = AgeGroup.Child;
AgeGroupMap[18] = AgeGroup.Teen;
AgeGroupMap[25] = AgeGroup.YoungAdult;
AgeGroupMap[75] = AgeGroup.Adult;
AgeGroupMap[999] = AgeGroup.Retired;
}
public Dictionary<int, AgeGroup> AgeGroupMap { get; set; }
/// <summary>
/// Gets the age group for a particular customer.
/// </summary>
/// <param name="customer">The customer to calculate the AgeGroup of.</param>
/// <returns>The correct age group for the customer</returns>
/// <exception cref="System.ApplicationException">If the customer is invalid</exception>
public AgeGroup GetAgeGroup(Person customer)
{
if (!customer.IsValid())
{
throw new ApplicationException("customer is invalid");
}
// Calculate age
DateTime zeroTime = new DateTime(1, 1, 1);
int age = (zeroTime + (DateTime.Today - customer.DOB)).Year;
// Return the correct age group
var viableBuckets = AgeGroupMap.Where(x => x.Key >= age);
return AgeGroupMap[viableBuckets.Min(x => x.Key)];
}
}
}``` |
8a253581-4a42-4c9b-8132-6e08550bd94a | {
"language": "C#"
} | ```c#
using ONIT.VismaNetApi.Models;
using System.Threading.Tasks;
namespace ONIT.VismaNetApi.Lib.Data
{
public class JournalTransactionData : BaseCrudDataClass<JournalTransaction>
{
public JournalTransactionData(VismaNetAuthorization auth) : base(auth)
{
ApiControllerUri = VismaNetControllers.JournalTransaction;
}
public async Task AddAttachment(JournalTransaction journalTransaction, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, journalTransaction.GetIdentificator(), data, filename);
}
public async Task AddAttachment(JournalTransaction journalTransaction, int lineNumber, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, $"{journalTransaction.GetIdentificator()}/{lineNumber}", data, filename);
}
}
}```
Add release action to journal transaction | ```c#
using ONIT.VismaNetApi.Models;
using System.Threading.Tasks;
namespace ONIT.VismaNetApi.Lib.Data
{
public class JournalTransactionData : BaseCrudDataClass<JournalTransaction>
{
public JournalTransactionData(VismaNetAuthorization auth) : base(auth)
{
ApiControllerUri = VismaNetControllers.JournalTransaction;
}
public async Task AddAttachment(JournalTransaction journalTransaction, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, journalTransaction.GetIdentificator(), data, filename);
}
public async Task AddAttachment(JournalTransaction journalTransaction, int lineNumber, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, $"{journalTransaction.GetIdentificator()}/{lineNumber}", data, filename);
}
public async Task<VismaActionResult> Release(JournalTransaction transaction)
{
return await VismaNetApiHelper.Action(Authorization, ApiControllerUri, transaction.GetIdentificator(), "release");
}
}
}``` |
e2d44b84-a9e4-4b8e-88fd-a3acb7d78acf | {
"language": "C#"
} | ```c#
using Alensia.Core.Actor;
using Alensia.Core.Camera;
using Alensia.Tests.Actor;
using NUnit.Framework;
namespace Alensia.Tests.Camera
{
[TestFixture, Description("Test suite for ThirdPersonCamera class.")]
public class ThirdPersonCameraTest : BaseOrbitingCameraTest<ThirdPersonCamera, IHumanoid>
{
protected override ThirdPersonCamera CreateCamera(UnityEngine.Camera camera)
{
var cam = new ThirdPersonCamera(camera);
cam.RotationalConstraints.Up = 90;
cam.RotationalConstraints.Down = 90;
cam.RotationalConstraints.Side = 180;
cam.WallAvoidanceSettings.AvoidWalls = false;
cam.Initialize(Actor);
return cam;
}
protected override IHumanoid CreateActor()
{
return new DummyHumanoid();
}
}
}```
Add test cases for wall avoidance settings | ```c#
using Alensia.Core.Actor;
using Alensia.Core.Camera;
using Alensia.Tests.Actor;
using NUnit.Framework;
using UnityEngine;
namespace Alensia.Tests.Camera
{
[TestFixture, Description("Test suite for ThirdPersonCamera class.")]
public class ThirdPersonCameraTest : BaseOrbitingCameraTest<ThirdPersonCamera, IHumanoid>
{
private GameObject _obstacle;
[TearDown]
public override void TearDown()
{
base.TearDown();
if (_obstacle == null) return;
Object.Destroy(_obstacle);
_obstacle = null;
}
protected override ThirdPersonCamera CreateCamera(UnityEngine.Camera camera)
{
var cam = new ThirdPersonCamera(camera);
cam.RotationalConstraints.Up = 90;
cam.RotationalConstraints.Down = 90;
cam.RotationalConstraints.Side = 180;
cam.WallAvoidanceSettings.AvoidWalls = false;
cam.Initialize(Actor);
return cam;
}
protected override IHumanoid CreateActor()
{
return new DummyHumanoid();
}
[Test, Description("It should adjust camera position according to obstacles when AvoidWalls is true.")]
[TestCase(0, 0, 10, 1, 4)]
[TestCase(0, 0, 2, 1, 2)]
[TestCase(0, 0, 10, 2, 3)]
[TestCase(45, 0, 10, 1, 10)]
[TestCase(0, 45, 10, 1, 10)]
public void ShouldAdjustCameraPositionAccordingToObstacles(
float heading,
float elevation,
float distance,
float proximity,
float actual)
{
var transform = Actor.Transform;
_obstacle = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
_obstacle.transform.position = transform.position + new Vector3(0, 1, -5);
Camera.WallAvoidanceSettings.AvoidWalls = true;
Camera.WallAvoidanceSettings.MinimumDistance = proximity;
Camera.Heading = heading;
Camera.Elevation = elevation;
Camera.Distance = distance;
Expect(
ActualDistance,
Is.EqualTo(actual).Within(Tolerance),
"Unexpected camera distance.");
}
}
}``` |
bd70a0a1-5e53-431c-8c8b-3c6f4a2850d1 | {
"language": "C#"
} | ```c#
@model MarkdownPage
<section class="body">
<div class="row">
<div class="large-9 columns">
<h1>@Model.Title</h1>
@Model.Content
</div>
<div class="large-3 columns">
<div class="section-container accordian">
@foreach (var category in Model.Bundle.Categories)
{
<section>
<p class="title" data-section-title>@category.Title</p>
<div class="content" data-section-content>
<ul class="side-nav">
@foreach (var page in category.Pages)
{
<li><a href="@page.Id">@page.Title</a></li>
}
</ul>
</div>
</section>
}
@if (Model.Bundle.Name != "developer")
{
<footer>Version @Model.Bundle.Name</footer>
}
</div>
</div>
</div>
</section>
```
Fix the viewbag title, used for the page title | ```c#
@model MarkdownPage
@{ ViewBag.Title = Model.Title; }
<section class="body">
<div class="row">
<div class="large-9 columns">
<h1>@Model.Title</h1>
@Model.Content
</div>
<div class="large-3 columns">
<div class="section-container accordian">
@foreach (var category in Model.Bundle.Categories)
{
<section>
<p class="title" data-section-title>@category.Title</p>
<div class="content" data-section-content>
<ul class="side-nav">
@foreach (var page in category.Pages)
{
<li><a href="@page.Id">@page.Title</a></li>
}
</ul>
</div>
</section>
}
@if (Model.Bundle.Name != "developer")
{
<footer>Version @Model.Bundle.Name</footer>
}
</div>
</div>
</div>
</section>
``` |
6bebe9bd-16bf-4d03-8601-c1244aa31f5c | {
"language": "C#"
} | ```c#
using TicketTimer.Core.Infrastructure;
namespace TicketTimer.Core.Services
{
// TODO this should have a better name
public class WorkItemServiceImpl : WorkItemService
{
private readonly WorkItemStore _workItemStore;
private readonly DateProvider _dateProvider;
public WorkItemServiceImpl(WorkItemStore workItemStore, DateProvider dateProvider)
{
_workItemStore = workItemStore;
_dateProvider = dateProvider;
}
public void StartWorkItem(string ticketNumber)
{
StartWorkItem(ticketNumber, string.Empty);
}
public void StartWorkItem(string ticketNumber, string comment)
{
var workItem = new WorkItem(ticketNumber)
{
Comment = comment,
Started = _dateProvider.Now
};
_workItemStore.Add(workItem);
}
public void StopWorkItem()
{
throw new System.NotImplementedException();
}
}
}```
Save work items after starting. | ```c#
using TicketTimer.Core.Infrastructure;
namespace TicketTimer.Core.Services
{
// TODO this should have a better name
public class WorkItemServiceImpl : WorkItemService
{
private readonly WorkItemStore _workItemStore;
private readonly DateProvider _dateProvider;
public WorkItemServiceImpl(WorkItemStore workItemStore, DateProvider dateProvider)
{
_workItemStore = workItemStore;
_dateProvider = dateProvider;
}
public void StartWorkItem(string ticketNumber)
{
StartWorkItem(ticketNumber, string.Empty);
}
public void StartWorkItem(string ticketNumber, string comment)
{
var workItem = new WorkItem(ticketNumber)
{
Comment = comment,
Started = _dateProvider.Now
};
_workItemStore.Add(workItem);
_workItemStore.Save();
}
public void StopWorkItem()
{
throw new System.NotImplementedException();
}
}
}``` |
897decec-a4d3-4d78-85df-1c3493155c7d | {
"language": "C#"
} | ```c#
// Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Undisposed;
namespace UndisposedExe
{
class MainClass
{
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Undisposed.exe [-o outputfile] assemblyname");
}
public static void Main(string[] args)
{
if (args.Length < 1)
{
Usage();
return;
}
string inputFile = args[args.Length - 1];
string outputFile;
if (args.Length >= 3)
{
if (args[0] == "-o" || args[0] == "--output")
{
outputFile = args[1];
}
else
{
Usage();
return;
}
}
else
outputFile = inputFile;
var def = Mono.Cecil.ModuleDefinition.ReadModule(inputFile);
var moduleWeaver = new ModuleWeaver();
moduleWeaver.ModuleDefinition = def;
moduleWeaver.Execute();
def.Write(outputFile);
}
}
}
```
Allow standalone program to process multiple files at once | ```c#
// Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Undisposed;
namespace UndisposedExe
{
class MainClass
{
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Undisposed.exe [-o outputfile] assemblyname");
}
private static void ProcessFile(string inputFile, string outputFile)
{
Console.WriteLine("Processing {0} -> {1}", inputFile, outputFile);
var def = Mono.Cecil.ModuleDefinition.ReadModule(inputFile);
var moduleWeaver = new ModuleWeaver();
moduleWeaver.ModuleDefinition = def;
moduleWeaver.Execute();
def.Write(outputFile);
}
public static void Main(string[] args)
{
if (args.Length < 1)
{
Usage();
return;
}
string inputFile = args[args.Length - 1];
string outputFile = string.Empty;
bool isOutputFileSet = false;
if (args.Length >= 3)
{
if (args[0] == "-o" || args[0] == "--output")
{
outputFile = args[1];
isOutputFileSet = true;
}
else
{
Usage();
return;
}
}
if (!isOutputFileSet)
{
for (int i = 0; i < args.Length; i++)
{
inputFile = args[i];
ProcessFile(inputFile, inputFile);
}
}
else
ProcessFile(inputFile, outputFile);
}
}
}
``` |
e3924e0c-970f-4911-8517-c90ea7ae3155 | {
"language": "C#"
} | ```c#
using System.Web.Http.Controllers;
namespace System.Web.Http.ModelBinding
{
// Interface for model binding
public interface IModelBinder
{
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
}
}
```
Change comment to doc comment | ```c#
using System.Web.Http.Controllers;
namespace System.Web.Http.ModelBinding
{
/// <summary>
/// Interface for model binding.
/// </summary>
public interface IModelBinder
{
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
}
}
``` |
6bd8353c-2076-4085-a331-342d1eab7ece | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using RestImageResize.Security;
using RestImageResize.Utils;
namespace RestImageResize
{
/// <summary>
/// Provides configuration options.
/// </summary>
internal static class Config
{
private static class AppSettingKeys
{
private const string Prefix = "RestImageResize.";
// ReSharper disable MemberHidesStaticFromOuterClass
public const string DefaultTransform = Prefix + "DefautTransform";
public const string PrivateKeys = Prefix + "PrivateKeys";
// ReSharper restore MemberHidesStaticFromOuterClass
}
/// <summary>
/// Gets the default image transformation type.
/// </summary>
public static ImageTransform DefaultTransform
{
get { return ConfigUtils.ReadAppSetting(AppSettingKeys.DefaultTransform, ImageTransform.DownFit); }
}
public static IList<PrivateKey> PrivateKeys
{
get
{
var privateKeysString = ConfigUtils.ReadAppSetting<string>(AppSettingKeys.PrivateKeys);
var privateKeys = privateKeysString.Split('|')
.Select(val => new PrivateKey
{
Name = val.Split(':').First(),
Key = val.Split(':').Last()
})
.ToList();
return privateKeys;
}
}
}
}
```
Fix private keys config parsing | ```c#
using System.Collections.Generic;
using System.Linq;
using RestImageResize.Security;
using RestImageResize.Utils;
namespace RestImageResize
{
/// <summary>
/// Provides configuration options.
/// </summary>
internal static class Config
{
private static class AppSettingKeys
{
private const string Prefix = "RestImageResize.";
// ReSharper disable MemberHidesStaticFromOuterClass
public const string DefaultTransform = Prefix + "DefautTransform";
public const string PrivateKeys = Prefix + "PrivateKeys";
// ReSharper restore MemberHidesStaticFromOuterClass
}
/// <summary>
/// Gets the default image transformation type.
/// </summary>
public static ImageTransform DefaultTransform
{
get { return ConfigUtils.ReadAppSetting(AppSettingKeys.DefaultTransform, ImageTransform.DownFit); }
}
public static IList<PrivateKey> PrivateKeys
{
get
{
var privateKeysString = ConfigUtils.ReadAppSetting<string>(AppSettingKeys.PrivateKeys);
if (string.IsNullOrEmpty(privateKeysString))
{
return new List<PrivateKey>();
}
var privateKeys = privateKeysString.Split('|')
.Select(val => new PrivateKey
{
Name = val.Split(':').First(),
Key = val.Split(':').Last()
})
.ToList();
return privateKeys;
}
}
}
}
``` |
4a3151ab-7844-4af5-8977-0890a234511e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Tamarind.Cache
{
// TODO: NEEDS DOCUMENTATION.
public interface ICache<K, V>
{
V GetIfPresent(K key);
V Get(K key, Func<V> valueLoader);
ImmutableDictionary<K, V> GetAllPresent(IEnumerator<K> keys);
void Put(K key, V value);
void PutAll(Dictionary<K, V> xs);
void Invalidate(K key);
void InvlidateAll(IEnumerator<K> keys);
long Count { get; }
//CacheStats Stats { get; }
ConcurrentDictionary<K, V> ToDictionary();
void CleanUp();
}
}
```
Add link to Guava implementation of Cache. | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Tamarind.Cache
{
// Guava Reference: https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/cache/Cache.java
// TODO: NEEDS DOCUMENTATION.
public interface ICache<K, V>
{
V GetIfPresent(K key);
V Get(K key, Func<V> valueLoader);
ImmutableDictionary<K, V> GetAllPresent(IEnumerator<K> keys);
void Put(K key, V value);
void PutAll(Dictionary<K, V> xs);
void Invalidate(K key);
void InvlidateAll(IEnumerator<K> keys);
long Count { get; }
//CacheStats Stats { get; }
ConcurrentDictionary<K, V> ToDictionary();
void CleanUp();
}
}
``` |
84a5e164-2ae6-4b58-a24a-4ecde595e835 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace VendingMachineNew
{
public class TwilioAPI
{
static void Main(string[] args)
{
SendSms().Wait();
Console.Write("Press any key to continue.");
Console.ReadKey();
}
static async Task SendSms()
{
// Your Account SID from twilio.com/console
var accountSid = "AC745137d20b51ab66c4fd18de86d3831c";
// Your Auth Token from twilio.com/console
var authToken = "789153e001d240e55a499bf070e75dfe";
TwilioClient.Init(accountSid, authToken);
var message = await MessageResource.CreateAsync(
to: new PhoneNumber("+14148070975"),
from: new PhoneNumber("+14142693915"),
body: "The confirmation number will be here");
Console.WriteLine(message.Sid);
}
}
}```
Remove account and api key | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace VendingMachineNew
{
public class TwilioAPI
{
static void Main(string[] args)
{
SendSms().Wait();
Console.Write("Press any key to continue.");
Console.ReadKey();
}
static async Task SendSms()
{
// Your Account SID from twilio.com/console
var accountSid = "x";
// Your Auth Token from twilio.com/console
var authToken = "x";
TwilioClient.Init(accountSid, authToken);
var message = await MessageResource.CreateAsync(
to: new PhoneNumber("+14148070975"),
from: new PhoneNumber("+14142693915"),
body: "The confirmation number will be here");
Console.WriteLine(message.Sid);
}
}
}
``` |
06122fe1-ad4f-4f4c-9e15-0cfd029e0c31 | {
"language": "C#"
} | ```c#
using System.Reflection;
using Abp.Modules;
namespace Abp.TestBase
{
[DependsOn(typeof(AbpKernelModule))]
public class AbpTestBaseModule : AbpModule
{
public override void PreInitialize()
{
Configuration.EventBus.UseDefaultEventBus = false;
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
}```
Set Configuration.DefaultNameOrConnectionString for unit tests by default. | ```c#
using System.Reflection;
using Abp.Modules;
namespace Abp.TestBase
{
[DependsOn(typeof(AbpKernelModule))]
public class AbpTestBaseModule : AbpModule
{
public override void PreInitialize()
{
Configuration.EventBus.UseDefaultEventBus = false;
Configuration.DefaultNameOrConnectionString = "Default";
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
}``` |
97cd382d-9f8c-465a-be7e-c101493e7202 | {
"language": "C#"
} | ```c#
using System;
using System.Xml;
using Hacknet;
using Pathfinder.Util;
using Pathfinder.Util.XML;
namespace Pathfinder.Action
{
public abstract class DelayablePathfinderAction : PathfinderAction
{
[XMLStorage]
public string DelayHost;
[XMLStorage]
public string Delay;
private DelayableActionSystem delayHost;
private float delay = 0f;
public sealed override void Trigger(object os_obj)
{
if (delayHost == null && DelayHost != null)
{
var delayComp = Programs.getComputer(OS.currentInstance, DelayHost);
if (delayComp == null)
throw new FormatException($"{this.GetType().Name}: DelayHost could not be found");
delayHost = DelayableActionSystem.FindDelayableActionSystemOnComputer(delayComp);
}
if (delay <= 0f || delayHost == null)
{
Trigger((OS)os_obj);
return;
}
delayHost.AddAction(this, delay);
delay = 0f;
}
public abstract void Trigger(OS os);
public override void LoadFromXml(ElementInfo info)
{
base.LoadFromXml(info);
if (Delay != null && !float.TryParse(Delay, out delay))
throw new FormatException($"{this.GetType().Name}: Couldn't parse delay time!");
}
}
}
```
Fix DelayableAction delays persisting DAH serialization | ```c#
using System;
using System.Xml;
using Hacknet;
using Pathfinder.Util;
using Pathfinder.Util.XML;
namespace Pathfinder.Action
{
public abstract class DelayablePathfinderAction : PathfinderAction
{
[XMLStorage]
public string DelayHost;
[XMLStorage]
public string Delay;
private DelayableActionSystem delayHost;
private float delay = 0f;
public sealed override void Trigger(object os_obj)
{
if (delayHost == null && DelayHost != null)
{
var delayComp = Programs.getComputer(OS.currentInstance, DelayHost);
if (delayComp == null)
throw new FormatException($"{this.GetType().Name}: DelayHost could not be found");
delayHost = DelayableActionSystem.FindDelayableActionSystemOnComputer(delayComp);
}
if (delay <= 0f || delayHost == null)
{
Trigger((OS)os_obj);
return;
}
DelayHost = null;
Delay = null;
delayHost.AddAction(this, delay);
delay = 0f;
}
public abstract void Trigger(OS os);
public override void LoadFromXml(ElementInfo info)
{
base.LoadFromXml(info);
if (Delay != null && !float.TryParse(Delay, out delay))
throw new FormatException($"{this.GetType().Name}: Couldn't parse delay time!");
}
}
}
``` |
25ec3089-5032-4e12-a5bb-6d32c7afb558 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlsLibrary.BasicControls
{
public partial class TextWindow : Form
{
public TextWindow()
{
InitializeComponent();
}
static public void ShowModal(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.ShowDialog();
}
}
static public void Show(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.Show();
}
}
public new string Text { set { _textBox.Text = value; } }
}
}
```
Fix for shader preview window in material tool appearing and then just disappearing | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlsLibrary.BasicControls
{
public partial class TextWindow : Form
{
public TextWindow()
{
InitializeComponent();
}
static public void ShowModal(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.ShowDialog();
}
}
static public void Show(String text)
{
new TextWindow() { Text = text }.Show();
}
public new string Text { set { _textBox.Text = value; } }
}
}
``` |
e801339e-cdef-4bd3-8e96-cad467289f85 | {
"language": "C#"
} | ```c#
using System;
using Xunit;
using Branch.Clients.Json;
using System.Threading.Tasks;
using Branch.Clients.Http.Models;
using System.Collections.Generic;
namespace Branch.Tests.Clients.JsonTests
{
public class OptionTests
{
[Fact]
public void RespectOptions()
{
var options = new Options
{
Headers = new Dictionary<string, string>
{
{"X-Test-Header", "testing"},
{"Content-Type", "application/json"},
},
Timeout = TimeSpan.FromMilliseconds(2500),
};
var client = new JsonClient("https://example.com", options);
Assert.Equal(client.Client.Options.Timeout, options.Timeout);
Assert.Equal(client.Client.Options.Headers, options.Headers);
}
}
}
```
Remove test intead of fixing it 👍 | ```c#
using System;
using Xunit;
using Branch.Clients.Json;
using System.Threading.Tasks;
using Branch.Clients.Http.Models;
using System.Collections.Generic;
namespace Branch.Tests.Clients.JsonTests
{
public class OptionTests
{
[Fact]
public void RespectOptions()
{
var options = new Options
{
Timeout = TimeSpan.FromMilliseconds(2500),
};
var client = new JsonClient("https://example.com", options);
Assert.Equal(client.Client.Options.Timeout, options.Timeout);
}
}
}
``` |
05e44db0-c607-4d90-8215-f8c3926157c8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace KmlToGpxConverter
{
internal static class KmlReader
{
public const string FileExtension = "kml";
public static IList<GpsTimePoint> ReadFile(string filename)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2");
var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager);
var nodes = new List<GpsTimePoint>();
foreach (XmlNode element in list)
{
nodes.AddRange(GetGpsPoints(element.ChildNodes));
}
return nodes;
}
private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes)
{
var retVal = new List<GpsTimePoint>();
var e = nodes.GetEnumerator();
while (e.MoveNext())
{
var utcTimepoint = ((XmlNode)e.Current).InnerText;
if (!e.MoveNext()) break;
var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' });
if (t.Length != 3) break;
retVal.Add(new GpsTimePoint(t[0], t[1], t[2], utcTimepoint));
}
return retVal;
}
}
}
```
Handle elements without elevation data | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace KmlToGpxConverter
{
internal static class KmlReader
{
public const string FileExtension = "kml";
public static IList<GpsTimePoint> ReadFile(string filename)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2");
var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager);
var nodes = new List<GpsTimePoint>();
foreach (XmlNode element in list)
{
nodes.AddRange(GetGpsPoints(element.ChildNodes));
}
return nodes;
}
private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes)
{
var retVal = new List<GpsTimePoint>();
var e = nodes.GetEnumerator();
while (e.MoveNext())
{
var utcTimepoint = ((XmlNode)e.Current).InnerText;
if (!e.MoveNext()) break;
var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' });
if (t.Length < 2) continue;
retVal.Add(new GpsTimePoint(t[0], t[1], t.ElementAtOrDefault(2), utcTimepoint));
}
return retVal;
}
}
}
``` |
79e6a08e-ae27-487d-af8d-69e1d6588237 | {
"language": "C#"
} | ```c#
using NSubstitute;
using Xunit;
namespace Core.Shogi.Tests.BitVersion
{
public class BitboardShogiGameShould
{
[Fact]
public void IdentifyACheckMateState()
{
var blackPlayer = new Player(PlayerType.Black);
var whitePlayer = new Player(PlayerType.White);
var board = new NewBitboard(blackPlayer, whitePlayer);
var render = Substitute.For<IBoardRender>();
var shogi = new BitboardShogiGame(board, render);
blackPlayer.Move("7g7f");
whitePlayer.Move("6a7b");
blackPlayer.Move("8h3c");
whitePlayer.Move("4a4b");
blackPlayer.Move("3c4b");
whitePlayer.Move("5a6a");
var result = blackPlayer.Move("G*5b");
Assert.Equal(BoardResult.CheckMate, result);
}
}
public class NewBitboard : Board
{
public NewBitboard(Player blackPlayer, Player whitePlayer)
{
}
}
public class BitboardShogiGame
{
public BitboardShogiGame(Board board, IBoardRender render)
{
}
}
}```
Reset board at start of the game. | ```c#
using NSubstitute;
using Xunit;
namespace Core.Shogi.Tests.BitVersion
{
public class BitboardShogiGameShould
{
[Fact]
public void IdentifyACheckMateState()
{
var blackPlayer = new Player(PlayerType.Black);
var whitePlayer = new Player(PlayerType.White);
var board = new NewBitboard(blackPlayer, whitePlayer);
var render = Substitute.For<IBoardRender>();
var shogi = new BitboardShogiGame(board, render);
shogi.Start();
blackPlayer.Move("7g7f");
whitePlayer.Move("6a7b");
blackPlayer.Move("8h3c");
whitePlayer.Move("4a4b");
blackPlayer.Move("3c4b");
whitePlayer.Move("5a6a");
var result = blackPlayer.Move("G*5b");
Assert.Equal(BoardResult.CheckMate, result);
}
[Fact]
public void EnsureBoardIsResetAtStartOfGame()
{
var board = Substitute.For<IBoard>();
var render = Substitute.For<IBoardRender>();
var shogi = new BitboardShogiGame(board, render);
shogi.Start();
board.ReceivedWithAnyArgs(1).Reset();
}
}
public interface IBoard
{
void Reset();
}
public class NewBitboard : IBoard
{
public NewBitboard(Player blackPlayer, Player whitePlayer)
{
}
public void Reset()
{
}
}
public class BitboardShogiGame
{
private readonly IBoard _board;
public BitboardShogiGame(IBoard board, IBoardRender render)
{
_board = board;
}
public void Start()
{
_board.Reset();
}
}
}``` |
f7e59359-3f83-461b-a6b5-ce475c180347 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 225),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
```
Increase usable width slightly further | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 250),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
``` |
1c21ffbd-948c-4866-81fa-19141d4727e2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Pennyworth {
public static class DropHelper {
public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) {
Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
var files = data.Where(isFile);
var dirs = data
.Where(isDir)
.Select(fi => {
if (fi.FullName.EndsWith("bin", StringComparison.OrdinalIgnoreCase))
return new FileInfo(fi.Directory.FullName);
return fi;
})
.SelectMany(fi => Directory.EnumerateDirectories(fi.FullName, "bin", SearchOption.AllDirectories));
var firstAssemblies = dirs.Select(dir => Directory.EnumerateFiles(dir, "*.exe", SearchOption.AllDirectories)
.FirstOrDefault(path => !path.Contains("vshost")))
.Where(dir => !String.IsNullOrEmpty(dir));
return files.Select(fi => fi.FullName)
.Concat(firstAssemblies)
.Where(path => Path.HasExtension(path)
&& (path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)));
}
}
}
```
Use the shortest path if assemblies have the same file name | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Pennyworth {
public static class DropHelper {
public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) {
Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
var files = data.Where(isFile);
var dirs = data.Where(isDir);
var assembliesInDirs =
dirs.SelectMany(dir => Directory.EnumerateFiles(dir.FullName, "*.exe", SearchOption.AllDirectories)
.Where(path => !path.Contains("vshost")));
return files.Select(fi => fi.FullName).Concat(DiscardSimilarFiles(assembliesInDirs.ToList()));
}
private static IEnumerable<String> DiscardSimilarFiles(List<String> assemblies) {
var fileNames = assemblies.Select(Path.GetFileName).Distinct();
var namePathLookup = assemblies.ToLookup(Path.GetFileName);
foreach (var file in fileNames) {
var paths = namePathLookup[file].ToList();
if (paths.Any()) {
if (paths.Count > 1) {
paths.Sort(String.CompareOrdinal);
}
yield return paths.First();
}
}
}
}
}
``` |
fa3dc8fb-8cee-4f82-843e-2bd2596ea9b2 | {
"language": "C#"
} | ```c#
using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear,
Black,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
```
Make XHud MaskType cast-able to AndHud MaskType | ```c#
using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear = 2,
Black = 3,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
``` |
ccc332c1-7eaf-4567-bb9a-85d2b5bf79b1 | {
"language": "C#"
} | ```c#
using System;
using Autofac;
using WordList.Composition;
namespace WordList {
public class Program {
public static void Main(string[] args) {
var compositionRoot = CompositionRoot.Compose();
var wordListProgram = compositionRoot.Resolve<IWordListProgram>();
wordListProgram.Run();
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
}```
Make the code in the entrypoint even shorter. | ```c#
using System;
using Autofac;
using WordList.Composition;
namespace WordList {
public class Program {
public static void Main(string[] args) {
CompositionRoot.Compose().Resolve<IWordListProgram>().Run();
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
}``` |
74515fa9-9749-43c3-b1f2-8bf3f2cb75e3 | {
"language": "C#"
} | ```c#
using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
private const string EvolveConfigurationError = "Evolve configuration error: ";
public EvolveConfigurationException(string message) : base(EvolveConfigurationError + message) { }
public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + message, innerException) { }
}
}
```
Add FirstLetterToLower() to each exception message | ```c#
using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
private const string EvolveConfigurationError = "Evolve configuration error: ";
public EvolveConfigurationException(string message) : base(EvolveConfigurationError + FirstLetterToLower(message)) { }
public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + FirstLetterToLower(message), innerException) { }
private static string FirstLetterToLower(string str)
{
if (str == null)
{
return "";
}
if (str.Length > 1)
{
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
return str.ToLowerInvariant();
}
}
}
``` |
6348ee75-e441-41b6-8549-9e378186ebd0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public class ExecutionTreeNode
{
public readonly ExecutionTreeNode Parent;
public readonly ProgramLocation CreatedAt;
public readonly ExecutionState State; // Should this be a weak reference to allow GC?
public readonly int Depth;
private List<ExecutionTreeNode> Children;
public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt)
{
Debug.Assert(self != null, "self cannot be null!");
this.State = self;
if (parent == null)
this.Parent = null;
else
{
this.Parent = parent;
// Add this as a child of the parent
this.Parent.AddChild(this);
}
this.Depth = self.ExplicitBranchDepth;
this.CreatedAt = createdAt;
Children = new List<ExecutionTreeNode>(); // Should we lazily create this?
}
public ExecutionTreeNode GetChild(int index)
{
return Children[index];
}
public int ChildrenCount
{
get { return Children.Count; }
}
public void AddChild(ExecutionTreeNode node)
{
Debug.Assert(node != null, "Child cannot be null");
Children.Add(node);
}
public override string ToString()
{
return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth);
}
}
}
```
Add assertion to check for cycles in ExecutionTree | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public class ExecutionTreeNode
{
public readonly ExecutionTreeNode Parent;
public readonly ProgramLocation CreatedAt;
public readonly ExecutionState State; // Should this be a weak reference to allow GC?
public readonly int Depth;
private List<ExecutionTreeNode> Children;
public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt)
{
Debug.Assert(self != null, "self cannot be null!");
this.State = self;
if (parent == null)
this.Parent = null;
else
{
this.Parent = parent;
// Add this as a child of the parent
this.Parent.AddChild(this);
}
this.Depth = self.ExplicitBranchDepth;
this.CreatedAt = createdAt;
Children = new List<ExecutionTreeNode>(); // Should we lazily create this?
}
public ExecutionTreeNode GetChild(int index)
{
return Children[index];
}
public int ChildrenCount
{
get { return Children.Count; }
}
public void AddChild(ExecutionTreeNode node)
{
Debug.Assert(node != null, "Child cannot be null");
Debug.Assert(node != this, "Cannot have cycles");
Children.Add(node);
}
public override string ToString()
{
return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth);
}
}
}
``` |
943c8528-799e-49b3-ad1d-0e797ad457d7 | {
"language": "C#"
} | ```c#
namespace BracesValidator
{
using System.Collections.Generic;
public class BracesValidator
{
public bool Validate(string code)
{
char[] codeArray = code.ToCharArray();
List<char> openers = new List<char> { '{', '[', '(' };
List<char> closers = new List<char> { '}', ']', ')' };
Stack<char> parensStack = new Stack<char>();
int braceCounter = 0;
for (int i = 0; i < codeArray.Length; i++)
{
if(openers.Contains(codeArray[i])) {
parensStack.Push(codeArray[i]);
}
if(closers.Contains(codeArray[i])) {
var current = parensStack.Pop();
if(openers.IndexOf(current) != closers.IndexOf(codeArray[i])) {
return false;
}
}
}
return parensStack.Count == 0;
}
}
}
```
Use dictionary instead of lists | ```c#
namespace BracesValidator
{
using System.Collections.Generic;
public class BracesValidator
{
public bool Validate(string code)
{
char[] codeArray = code.ToCharArray();
Dictionary<char, char> openersClosersMap = new Dictionary<char, char>();
openersClosersMap.Add('{', '}');
openersClosersMap.Add('[', ']');
openersClosersMap.Add('(', ')');
Stack<char> parensStack = new Stack<char>();
int braceCounter = 0;
for (int i = 0; i < codeArray.Length; i++)
{
if(openersClosersMap.ContainsKey(codeArray[i])) {
parensStack.Push(codeArray[i]);
}
if(openersClosersMap.ContainsValue(codeArray[i])) {
var current = parensStack.Pop();
if(openersClosersMap[current] != codeArray[i]) {
return false;
}
}
}
return parensStack.Count == 0;
}
}
}
``` |
6bac64b9-ae0b-4291-868f-22c909338b18 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (IsEnabled(logLevel))
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
```
Remove warnings from Ably log to reduce noise. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (IsEnabled(logLevel))
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information && logLevel != LogLevel.Warning;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
``` |
18747930-2bf4-44e0-b668-26233f766eee | {
"language": "C#"
} | ```c#
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification. It is horrid, but gets the job done.
public static class BusG
{
static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.System.Iterate ();
return true;
}
static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.Session.Iterate ();
return true;
}
public static void Init ()
{
Init (Bus.System, SystemDispatch);
Init (Bus.Session, SessionDispatch);
}
public static void Init (Connection conn, IOFunc dispatchHandler)
{
IOChannel channel = new IOChannel ((int)conn.SocketHandle);
IO.AddWatch (channel, IOCondition.In, dispatchHandler);
}
//TODO: add public API to watch an arbitrary connection
}
}
```
Make sure we only ever initialize once | ```c#
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification. It is horrid, but gets the job done.
public static class BusG
{
static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.System.Iterate ();
return true;
}
static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.Session.Iterate ();
return true;
}
static bool initialized = false;
public static void Init ()
{
if (initialized)
return;
Init (Bus.System, SystemDispatch);
Init (Bus.Session, SessionDispatch);
initialized = true;
}
public static void Init (Connection conn, IOFunc dispatchHandler)
{
IOChannel channel = new IOChannel ((int)conn.SocketHandle);
IO.AddWatch (channel, IOCondition.In, dispatchHandler);
}
//TODO: add public API to watch an arbitrary connection
}
}
``` |
317066cc-125c-4ffb-b295-bdb2454a1f5e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using Android.Graphics;
namespace SignaturePad {
public class ClearingImageView : ImageView {
private Bitmap imageBitmap = null;
public ClearingImageView (Context context)
: base (context)
{
}
public ClearingImageView (Context context, IAttributeSet attrs)
: base (context, attrs)
{
}
public ClearingImageView (Context context, IAttributeSet attrs, int defStyle)
: base (context, attrs, defStyle)
{
}
public override void SetImageBitmap(Bitmap bm)
{
base.SetImageBitmap (bm);
if (imageBitmap != null)
{
imageBitmap.Recycle ();
}
imageBitmap = bm;
}
}
}
```
Call Dispose and the GC to avoid leaking memory. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using Android.Graphics;
namespace SignaturePad {
public class ClearingImageView : ImageView {
private Bitmap imageBitmap = null;
public ClearingImageView (Context context)
: base (context)
{
}
public ClearingImageView (Context context, IAttributeSet attrs)
: base (context, attrs)
{
}
public ClearingImageView (Context context, IAttributeSet attrs, int defStyle)
: base (context, attrs, defStyle)
{
}
public override void SetImageBitmap(Bitmap bm)
{
base.SetImageBitmap (bm);
if (imageBitmap != null)
{
imageBitmap.Recycle ();
imageBitmap.Dispose ();
}
imageBitmap = bm;
System.GC.Collect ();
}
}
}
``` |
a6c901a4-ecc6-4f4c-ab3d-fe084a1c9753 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.Tests")]
[assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")]```
Add parallelism to Tests project | ```c#
using NUnit.Framework;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.Tests")]
[assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")]
[assembly: LevelOfParallelism(4)]
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: Atata.Culture("en-us")]``` |
78bca0df-590e-4bf3-ac77-a2a56c8dd42c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HeadRaceTimingSite.Models;
using Microsoft.EntityFrameworkCore;
namespace HeadRaceTimingSite.Controllers
{
public class CrewController : BaseController
{
public CrewController(TimingSiteContext context) : base(context) { }
public async Task<IActionResult> Details(int? id)
{
Crew crew = await _context.Crews.Include(c => c.Competition)
.Include(c => c.Athletes)
.Include("Athletes.Athlete")
.Include("Awards.Award")
.SingleOrDefaultAsync(c => c.CrewId == id);
return View(crew);
}
}
}```
Fix crew to reference by BroeCrewId | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HeadRaceTimingSite.Models;
using Microsoft.EntityFrameworkCore;
namespace HeadRaceTimingSite.Controllers
{
public class CrewController : BaseController
{
public CrewController(TimingSiteContext context) : base(context) { }
public async Task<IActionResult> Details(int? id)
{
Crew crew = await _context.Crews.Include(c => c.Competition)
.Include(c => c.Athletes)
.Include("Athletes.Athlete")
.Include("Awards.Award")
.SingleOrDefaultAsync(c => c.BroeCrewId == id);
return View(crew);
}
}
}``` |
c0942ade-e102-44b8-84aa-4794aa72273e | {
"language": "C#"
} | ```c#
#pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null
#pragma warning disable xUnit1013 // Public method should be marked as test
using Xunit;
using MonoMod.RuntimeDetour;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using MonoMod.Utils;
using System.Reflection.Emit;
using System.Text;
namespace MonoMod.UnitTest {
[Collection("RuntimeDetour")]
public class DetourEmptyTest {
private bool DidNothing = true;
[Fact]
public void TestDetoursEmpty() {
// The following use cases are not meant to be usage examples.
// Please take a look at DetourTest and HookTest instead.
Assert.True(DidNothing);
using (Hook h = new Hook(
// .GetNativeStart() to enforce a native detour.
typeof(DetourEmptyTest).GetMethod("DoNothing"),
new Action<DetourEmptyTest>(self => {
DidNothing = false;
})
)) {
DoNothing();
Assert.False(DidNothing);
}
}
public void DoNothing() {
}
}
}
```
Mark the empty method detour test as NoInlining | ```c#
#pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null
#pragma warning disable xUnit1013 // Public method should be marked as test
using Xunit;
using MonoMod.RuntimeDetour;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using MonoMod.Utils;
using System.Reflection.Emit;
using System.Text;
namespace MonoMod.UnitTest {
[Collection("RuntimeDetour")]
public class DetourEmptyTest {
private bool DidNothing = true;
[Fact]
public void TestDetoursEmpty() {
// The following use cases are not meant to be usage examples.
// Please take a look at DetourTest and HookTest instead.
Assert.True(DidNothing);
using (Hook h = new Hook(
// .GetNativeStart() to enforce a native detour.
typeof(DetourEmptyTest).GetMethod("DoNothing"),
new Action<DetourEmptyTest>(self => {
DidNothing = false;
})
)) {
DoNothing();
Assert.False(DidNothing);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void DoNothing() {
}
}
}
``` |
05a7af5b-3fac-4267-bc59-3f2379104395 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
namespace JabbR.ContentProviders
{
public class UserVoiceContentProvider : CollapsibleContentProvider
{
private static readonly string _uservoiceAPIURL = "http://{0}/api/v1/oembed.json?url={1}";
protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request)
{
return FetchArticle(request.RequestUri).Then(article =>
{
return new ContentProviderResult()
{
Title = article.title,
Content = article.html
};
});
}
private static Task<dynamic> FetchArticle(Uri url)
{
return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri));
}
public override bool IsValidContent(Uri uri)
{
return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}```
Make user voice content provider work with https. | ```c#
using System;
using System.Threading.Tasks;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
namespace JabbR.ContentProviders
{
public class UserVoiceContentProvider : CollapsibleContentProvider
{
private static readonly string _uservoiceAPIURL = "https://{0}/api/v1/oembed.json?url={1}";
protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request)
{
return FetchArticle(request.RequestUri).Then(article =>
{
return new ContentProviderResult()
{
Title = article.title,
Content = article.html
};
});
}
private static Task<dynamic> FetchArticle(Uri url)
{
return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri));
}
public override bool IsValidContent(Uri uri)
{
return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}``` |
ce651d98-2976-4028-857b-67e3f5a7e76c | {
"language": "C#"
} | ```c#
// 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 osu.Framework.Localisation;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections
{
/// <summary>
/// A slider intended to show a "size" multiplier number, where 1x is 1.0.
/// </summary>
internal class SizeSlider<T> : OsuSliderBar<T>
where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", null);
}
}
```
Use explicit culture info rather than `null` | ```c#
// 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.Globalization;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections
{
/// <summary>
/// A slider intended to show a "size" multiplier number, where 1x is 1.0.
/// </summary>
internal class SizeSlider<T> : OsuSliderBar<T>
where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", NumberFormatInfo.CurrentInfo);
}
}
``` |
17def1e1-739c-4794-a750-70d171158d36 | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
namespace Docker.DotNet.X509
{
public class CertificateCredentials : Credentials
{
private readonly WebRequestHandler _handler;
public CertificateCredentials(X509Certificate2 clientCertificate)
{
_handler = new WebRequestHandler()
{
ClientCertificateOptions = ClientCertificateOption.Manual,
UseDefaultCredentials = false
};
_handler.ClientCertificates.Add(clientCertificate);
}
public override HttpMessageHandler Handler
{
get
{
return _handler;
}
}
public override bool IsTlsCredentials()
{
return true;
}
public override void Dispose()
{
_handler.Dispose();
}
}
}```
Make X509 work with ManagedHandler | ```c#
using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Net.Http.Client;
namespace Docker.DotNet.X509
{
public class CertificateCredentials : Credentials
{
private X509Certificate2 _certificate;
public CertificateCredentials(X509Certificate2 clientCertificate)
{
_certificate = clientCertificate;
}
public override HttpMessageHandler GetHandler(HttpMessageHandler innerHandler)
{
var handler = (ManagedHandler)innerHandler;
handler.ClientCertificates = new X509CertificateCollection
{
_certificate
};
handler.ServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
return handler;
}
public override bool IsTlsCredentials()
{
return true;
}
public override void Dispose()
{
}
}
}``` |
6c637e29-c81f-46fb-a3d3-a548db15fc72 | {
"language": "C#"
} | ```c#
using FluentMigrator;
namespace Azimuth.Migrations
{
[Migration(201409101200)]
public class Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable: Migration
{
public override void Up()
{
Delete.Table("Listened");
Alter.Table("Playlists").AddColumn("Listened").AsInt64().WithDefaultValue(0);
}
public override void Down()
{
Create.Table("UnauthorizedListeners")
.WithColumn("Id").AsInt64().NotNullable().Identity().PrimaryKey()
.WithColumn("PlaylistId").AsInt64().NotNullable().ForeignKey("Playlists", "PlaylistsId")
.WithColumn("Amount").AsInt64().NotNullable();
Delete.Column("Listened").FromTable("Playlists");
}
}
}
```
Rename listened table in migration | ```c#
using FluentMigrator;
namespace Azimuth.Migrations
{
[Migration(201409101200)]
public class Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable: Migration
{
public override void Up()
{
Delete.Table("Listened");
Alter.Table("Playlists").AddColumn("Listened").AsInt64().WithDefaultValue(0);
}
public override void Down()
{
Create.Table("Listened")
.WithColumn("Id").AsInt64().NotNullable().Identity().PrimaryKey()
.WithColumn("PlaylistId").AsInt64().NotNullable().ForeignKey("Playlists", "PlaylistsId")
.WithColumn("Amount").AsInt64().NotNullable();
Delete.Column("Listened").FromTable("Playlists");
}
}
}
``` |
9fd5484d-e1b9-4f30-864d-ae33140224b7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathParser.Tests
{
public class InfixLexicalAnalyzerTest
{
public void Expressao_binaria_simples_com_espacos()
{
//var analyzer = new InfixLexicalAnalyzer();
//analyzer.Analyze("2 + 2");
}
}
}
```
Include Fact attribute on test method | ```c#
using Xunit;
namespace MathParser.Tests
{
public class InfixLexicalAnalyzerTest
{
[Fact]
public void Expressao_binaria_simples_com_espacos()
{
//var analyzer = new InfixLexicalAnalyzer();
//analyzer.Analyze("2 + 2");
}
}
}
``` |
a1786c6d-da38-417d-ae94-48fa2b13fb4d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Synapse.RestClient.Transaction;
namespace Synapse.RestClient
{
using User;
using Node;
public class SynapseRestClientFactory
{
private SynapseApiCredentials _creds;
private string _baseUrl;
public SynapseRestClientFactory(SynapseApiCredentials credentials, string baseUrl)
{
this._creds = credentials;
this._baseUrl = baseUrl;
}
public ISynapseUserApiClient CreateUserClient()
{
return new SynapseUserApiClient(this._creds, this._baseUrl);
}
public ISynapseNodeApiClient CreateNodeClient()
{
return new SynapseNodeApiClient(this._creds, this._baseUrl);
}
public ISynapseTransactionApiClient CreateTransactionClient()
{
return new SynapseTransactionApiClient(this._creds, this._baseUrl);
}
}
}
```
Update servicepointmanager to use newer TLS | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Synapse.RestClient.Transaction;
namespace Synapse.RestClient
{
using User;
using Node;
using System.Net;
public class SynapseRestClientFactory
{
private SynapseApiCredentials _creds;
private string _baseUrl;
public SynapseRestClientFactory(SynapseApiCredentials credentials, string baseUrl)
{
this._creds = credentials;
this._baseUrl = baseUrl;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
public ISynapseUserApiClient CreateUserClient()
{
return new SynapseUserApiClient(this._creds, this._baseUrl);
}
public ISynapseNodeApiClient CreateNodeClient()
{
return new SynapseNodeApiClient(this._creds, this._baseUrl);
}
public ISynapseTransactionApiClient CreateTransactionClient()
{
return new SynapseTransactionApiClient(this._creds, this._baseUrl);
}
}
}
``` |
61c0de89-8866-4ca5-bf05-29b35521632d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bloom;
using Bloom.MiscUI;
using NUnit.Framework;
namespace BloomTests
{
[TestFixture]
#if __MonoCS__
[RequiresSTA]
#endif
public class ProblemReporterDialogTests
{
[TestFixtureSetUp]
public void FixtureSetup()
{
Browser.SetUpXulRunner();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
#if __MonoCS__
// Doing this in Windows works on dev machines but somehow freezes the TC test runner
Xpcom.Shutdown();
#endif
}
/// <summary>
/// This is just a smoke-test that will notify us if the SIL JIRA stops working with the API we're relying on.
/// It sends reports to https://jira.sil.org/browse/AUT
/// </summary>
[Test]
public void CanSubmitToSILJiraAutomatedTestProject()
{
using (var dlg = new ProblemReporterDialog(null, null))
{
dlg.SetupForUnitTest("AUT");
dlg.ShowDialog();
}
}
}
}```
Add missing "using geckofx" for mono build | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bloom;
using Bloom.MiscUI;
using NUnit.Framework;
#if __MonoCS__
using Gecko;
#endif
namespace BloomTests
{
[TestFixture]
#if __MonoCS__
[RequiresSTA]
#endif
public class ProblemReporterDialogTests
{
[TestFixtureSetUp]
public void FixtureSetup()
{
Browser.SetUpXulRunner();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
#if __MonoCS__
// Doing this in Windows works on dev machines but somehow freezes the TC test runner
Xpcom.Shutdown();
#endif
}
/// <summary>
/// This is just a smoke-test that will notify us if the SIL JIRA stops working with the API we're relying on.
/// It sends reports to https://jira.sil.org/browse/AUT
/// </summary>
[Test]
public void CanSubmitToSILJiraAutomatedTestProject()
{
using (var dlg = new ProblemReporterDialog(null, null))
{
dlg.SetupForUnitTest("AUT");
dlg.ShowDialog();
}
}
}
}``` |
377d5b97-4227-46fe-aa9c-618978d4e689 | {
"language": "C#"
} | ```c#
using System;
namespace HelloClient
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
```
Add client for simple call | ```c#
using System;
using Grpc.Core;
using Hello;
namespace HelloClient
{
class Program
{
public static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
var client = new HelloService.HelloServiceClient(channel);
String user = "Euler";
var reply = client.SayHello(new HelloReq { Name = user });
Console.WriteLine(reply.Result);
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
``` |
dddfab69-9e4d-43fc-a8a2-5b4b3e134e20 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace WebNoodle
{
public static class NodeHelper
{
public static IEnumerable<object> YieldChildren(this object node, string path, bool breakOnNull = false)
{
path = string.IsNullOrWhiteSpace(path) ? "/" : path;
yield return node;
var parts = (path).Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
node = node.GetChild(part);
if (node == null)
{
if (breakOnNull) yield break;
throw new Exception("Node '" + part + "' not found in path '" + path + "'");
}
yield return node;
}
}
}
}```
Throw 404 when you can't find the node | ```c#
using System;
using System.Collections.Generic;
using System.Web;
namespace WebNoodle
{
public static class NodeHelper
{
public static IEnumerable<object> YieldChildren(this object node, string path, bool breakOnNull = false)
{
path = string.IsNullOrWhiteSpace(path) ? "/" : path;
yield return node;
var parts = (path).Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
node = node.GetChild(part);
if (node == null)
{
if (breakOnNull) yield break;
throw new HttpException(404, "Node '" + part + "' not found in path '" + path + "'");
}
yield return node;
}
}
}
}``` |
24615e4a-ab8a-402b-8829-218e160e078e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended
{
public class FramesPerSecondCounter : IUpdate
{
public FramesPerSecondCounter(int maximumSamples = 100)
{
MaximumSamples = maximumSamples;
}
private readonly Queue<float> _sampleBuffer = new Queue<float>();
public long TotalFrames { get; private set; }
public float AverageFramesPerSecond { get; private set; }
public float CurrentFramesPerSecond { get; private set; }
public int MaximumSamples { get; }
public void Reset()
{
TotalFrames = 0;
_sampleBuffer.Clear();
}
public void Update(float deltaTime)
{
CurrentFramesPerSecond = 1.0f / deltaTime;
_sampleBuffer.Enqueue(CurrentFramesPerSecond);
if (_sampleBuffer.Count > MaximumSamples)
{
_sampleBuffer.Dequeue();
AverageFramesPerSecond = _sampleBuffer.Average(i => i);
}
else
{
AverageFramesPerSecond = CurrentFramesPerSecond;
}
TotalFrames++;
}
public void Update(GameTime gameTime)
{
Update((float)gameTime.ElapsedGameTime.TotalSeconds);
}
}
}
```
Make FPS counter to a GameComponent | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended
{
public class FramesPerSecondCounter : DrawableGameComponent
{
public FramesPerSecondCounter(Game game, int maximumSamples = 100)
:base(game)
{
MaximumSamples = maximumSamples;
}
private readonly Queue<float> _sampleBuffer = new Queue<float>();
public long TotalFrames { get; private set; }
public float AverageFramesPerSecond { get; private set; }
public float CurrentFramesPerSecond { get; private set; }
public int MaximumSamples { get; }
public void Reset()
{
TotalFrames = 0;
_sampleBuffer.Clear();
}
public void UpdateFPS(float deltaTime)
{
CurrentFramesPerSecond = 1.0f / deltaTime;
_sampleBuffer.Enqueue(CurrentFramesPerSecond);
if (_sampleBuffer.Count > MaximumSamples)
{
_sampleBuffer.Dequeue();
AverageFramesPerSecond = _sampleBuffer.Average(i => i);
}
else
{
AverageFramesPerSecond = CurrentFramesPerSecond;
}
TotalFrames++;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
UpdateFPS((float)gameTime.ElapsedGameTime.TotalSeconds);
base.Draw(gameTime);
}
}
}
``` |
84804e9d-8bd0-4b70-b3b1-d545e9b6c84c | {
"language": "C#"
} | ```c#
// 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.Globalization;
using NUnit.Framework;
using osu.Framework.Localisation;
namespace osu.Framework.Tests.Localisation
{
[TestFixture]
public class CultureInfoHelperTest
{
private const string invariant_culture = "";
[TestCase("en-US", true, "en-US")]
[TestCase("invalid name", false, invariant_culture)]
[TestCase(invariant_culture, true, invariant_culture)]
[TestCase("ko_KR", false, invariant_culture)]
public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName)
{
CultureInfo expectedCulture;
switch (expectedCultureName)
{
case invariant_culture:
expectedCulture = CultureInfo.InvariantCulture;
break;
default:
expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName);
break;
}
bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture);
Assert.That(retVal, Is.EqualTo(expectedReturnValue));
Assert.That(culture, Is.EqualTo(expectedCulture));
}
}
}
```
Fix tests failing due to not being updated with new behaviour | ```c#
// 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.Globalization;
using NUnit.Framework;
using osu.Framework.Localisation;
namespace osu.Framework.Tests.Localisation
{
[TestFixture]
public class CultureInfoHelperTest
{
private const string system_culture = "";
[TestCase("en-US", true, "en-US")]
[TestCase("invalid name", false, system_culture)]
[TestCase(system_culture, true, system_culture)]
[TestCase("ko_KR", false, system_culture)]
public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName)
{
CultureInfo expectedCulture;
switch (expectedCultureName)
{
case system_culture:
expectedCulture = CultureInfo.CurrentCulture;
break;
default:
expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName);
break;
}
bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture);
Assert.That(retVal, Is.EqualTo(expectedReturnValue));
Assert.That(culture, Is.EqualTo(expectedCulture));
}
}
}
``` |
1c91f55c-582d-47de-ad46-566ff6512361 | {
"language": "C#"
} | ```c#
// Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
namespace LfMerge.LanguageForge.Model
{
public class LfAuthorInfo : LfFieldBase
{
public string CreatedByUserRef { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedByUserRef { get; set; }
public DateTime ModifiedDate { get; set; }
}
}
```
Handle Mongo ObjectId references better | ```c#
// Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using MongoDB.Bson;
namespace LfMerge.LanguageForge.Model
{
public class LfAuthorInfo : LfFieldBase
{
public ObjectId? CreatedByUserRef { get; set; }
public DateTime CreatedDate { get; set; }
public ObjectId? ModifiedByUserRef { get; set; }
public DateTime ModifiedDate { get; set; }
}
}
``` |
07ea989b-083b-4f63-af14-7ab18fb6e8f1 | {
"language": "C#"
} | ```c#
namespace Umbraco.Core.Models
{
public enum TagCacheStorageType
{
Json,
Csv
}
}
```
Reset commit to not break backwards compatibility mode | ```c#
namespace Umbraco.Core.Models
{
public enum TagCacheStorageType
{
Csv,
Json
}
}``` |
dcf9de61-d2ec-46b4-8881-16021ee92ea0 | {
"language": "C#"
} | ```c#
using AutomaticTypeMapper;
using EOLib.Domain.NPC;
using EOLib.IO.Repositories;
using EOLib.Net;
using EOLib.Net.Communication;
namespace EOLib.Domain.Interact
{
[AutoMappedType]
public class MapNPCActions : IMapNPCActions
{
private readonly IPacketSendService _packetSendService;
private readonly IENFFileProvider _enfFileProvider;
public MapNPCActions(IPacketSendService packetSendService,
IENFFileProvider enfFileProvider)
{
_packetSendService = packetSendService;
_enfFileProvider = enfFileProvider;
}
public void RequestShop(INPC npc)
{
var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open)
.AddShort(npc.Index)
.Build();
_packetSendService.SendPacket(packet);
}
public void RequestQuest(INPC npc)
{
var data = _enfFileProvider.ENFFile[npc.ID];
var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use)
.AddShort(npc.Index)
.AddShort(data.VendorID)
.Build();
_packetSendService.SendPacket(packet);
}
}
public interface IMapNPCActions
{
void RequestShop(INPC npc);
void RequestQuest(INPC npc);
}
}
```
Fix bug where quest NPC dialog caused a crash because the requested NPC was never set | ```c#
using AutomaticTypeMapper;
using EOLib.Domain.Interact.Quest;
using EOLib.Domain.NPC;
using EOLib.IO.Repositories;
using EOLib.Net;
using EOLib.Net.Communication;
namespace EOLib.Domain.Interact
{
[AutoMappedType]
public class MapNPCActions : IMapNPCActions
{
private readonly IPacketSendService _packetSendService;
private readonly IENFFileProvider _enfFileProvider;
private readonly IQuestDataRepository _questDataRepository;
public MapNPCActions(IPacketSendService packetSendService,
IENFFileProvider enfFileProvider,
IQuestDataRepository questDataRepository)
{
_packetSendService = packetSendService;
_enfFileProvider = enfFileProvider;
_questDataRepository = questDataRepository;
}
public void RequestShop(INPC npc)
{
var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open)
.AddShort(npc.Index)
.Build();
_packetSendService.SendPacket(packet);
}
public void RequestQuest(INPC npc)
{
_questDataRepository.RequestedNPC = npc;
var data = _enfFileProvider.ENFFile[npc.ID];
var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use)
.AddShort(npc.Index)
.AddShort(data.VendorID)
.Build();
_packetSendService.SendPacket(packet);
}
}
public interface IMapNPCActions
{
void RequestShop(INPC npc);
void RequestQuest(INPC npc);
}
}
``` |
99d0a61a-14d0-44aa-9bfb-dc5fc8bdbdb8 | {
"language": "C#"
} | ```c#
namespace Glimpse.Core2.Extensibility
{
public enum ScriptOrder
{
IncludeBeforeClientInterfaceScript,
ClientInterfaceScript,
IncludeAfterClientInterfaceScript,
IncludeBeforeRequestDataScript,
RequestDataScript,
RequestMetadataScript,
IncludeAfterRequestDataScript,
}
}```
Switch the load order so that metadata comes first in the dom | ```c#
namespace Glimpse.Core2.Extensibility
{
public enum ScriptOrder
{
IncludeBeforeClientInterfaceScript,
ClientInterfaceScript,
IncludeAfterClientInterfaceScript,
IncludeBeforeRequestDataScript,
RequestMetadataScript,
RequestDataScript,
IncludeAfterRequestDataScript,
}
}``` |
92ffc775-f3d3-4f30-a19c-fb2545e473d4 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
namespace Roslyn.Utilities
{
/// <summary>
/// This is a bridge for APIs that are only available on Desktop
/// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR
/// so this shim is necessary for switching on the dependent behavior.
/// </summary>
internal static class DesktopShim
{
internal static class FileNotFoundException
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.IO.FileNotFoundException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog");
internal static string TryGetFusionLog(object obj) => s_fusionLog.GetValue(obj) as string;
}
}
}
```
Make the FNF exception light up more robust | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
namespace Roslyn.Utilities
{
/// <summary>
/// This is a bridge for APIs that are only available on Desktop
/// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR
/// so this shim is necessary for switching on the dependent behavior.
/// </summary>
internal static class DesktopShim
{
internal static class FileNotFoundException
{
internal static readonly Type Type = typeof(FileNotFoundException);
private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog");
internal static string TryGetFusionLog(object obj) => s_fusionLog?.GetValue(obj) as string;
}
}
}
``` |
25dfb194-191b-4fcf-a238-943f3ddb5d3b | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
}```
Fix bug: Clearing the cache says "All items have been cleared from the recent packages list." Work items: 986 | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearPackageCache, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
}``` |
5332227b-0465-43de-873b-7e18eea39560 | {
"language": "C#"
} | ```c#
namespace dotless.Core.Parser.Tree
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using Exceptions;
public class Url : Node
{
public Node Value { get; set; }
public Url(Node value, IEnumerable<string> paths)
{
if (value is TextNode)
{
var textValue = value as TextNode;
if (!Regex.IsMatch(textValue.Value, @"^(([A-z]+:)|(\/))") && paths.Any())
{
textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths();
}
}
Value = value;
}
public Url(Node value)
{
Value = value;
}
public string GetUrl()
{
if (Value is TextNode)
return (Value as TextNode).Value;
throw new ParserException("Imports do not allow expressions");
}
public override Node Evaluate(Env env)
{
return new Url(Value.Evaluate(env));
}
public override void AppendCSS(Env env)
{
env.Output
.Append("url(")
.Append(Value)
.Append(")");
}
}
}```
Change a-Z to a-zA-Z as reccomended | ```c#
namespace dotless.Core.Parser.Tree
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using Exceptions;
public class Url : Node
{
public Node Value { get; set; }
public Url(Node value, IEnumerable<string> paths)
{
if (value is TextNode)
{
var textValue = value as TextNode;
if (!Regex.IsMatch(textValue.Value, @"^(([a-zA-Z]+:)|(\/))") && paths.Any())
{
textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths();
}
}
Value = value;
}
public Url(Node value)
{
Value = value;
}
public string GetUrl()
{
if (Value is TextNode)
return (Value as TextNode).Value;
throw new ParserException("Imports do not allow expressions");
}
public override Node Evaluate(Env env)
{
return new Url(Value.Evaluate(env));
}
public override void AppendCSS(Env env)
{
env.Output
.Append("url(")
.Append(Value)
.Append(")");
}
}
}``` |
e09ce49c-6b86-4c8e-8ee1-1feafaf24499 | {
"language": "C#"
} | ```c#
using System;
using Glimpse.Agent.AspNet.Messages;
using Glimpse.Agent.Inspectors;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet
{
public class EnvironmentInspector : Inspector
{
private readonly IAgentBroker _broker;
private EnvironmentMessage _message;
public EnvironmentInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void Before(HttpContext context)
{
if (_message == null)
{
_message = new EnvironmentMessage
{
Server = Environment.MachineName,
OperatingSystem = Environment.OSVersion.VersionString,
ProcessorCount = Environment.ProcessorCount,
Is64Bit = Environment.Is64BitOperatingSystem,
CommandLineArgs = Environment.GetCommandLineArgs(),
EnvironmentVariables = Environment.GetEnvironmentVariables()
};
}
_broker.SendMessage(_message);
}
}
}
```
Comment out the environment message for the time being | ```c#
using System;
using Glimpse.Agent.AspNet.Messages;
using Glimpse.Agent.Inspectors;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet
{
public class EnvironmentInspector : Inspector
{
private readonly IAgentBroker _broker;
private EnvironmentMessage _message;
public EnvironmentInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void Before(HttpContext context)
{
//if (_message == null)
//{
// _message = new EnvironmentMessage
// {
// Server = Environment.MachineName,
// OperatingSystem = Environment.OSVersion.VersionString,
// ProcessorCount = Environment.ProcessorCount,
// Is64Bit = Environment.Is64BitOperatingSystem,
// CommandLineArgs = Environment.GetCommandLineArgs(),
// EnvironmentVariables = Environment.GetEnvironmentVariables()
// };
//}
//_broker.SendMessage(_message);
}
}
}
``` |
e6e61cf7-64e9-4514-b1c8-482feb4e2888 | {
"language": "C#"
} | ```c#
using Navigation.Sample.Models;
using System;
using System.Web.Mvc;
namespace Navigation.Sample.Controllers
{
public class PersonController : Controller
{
public ActionResult Index(PersonSearchModel model, string sortExpression, int startRowIndex, int maximumRows)
{
DateTime outDate;
if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate))
{
StateContext.Bag.name = model.Name;
StateContext.Bag.minDateOfBirth = model.MinDateOfBirth;
}
else
{
ModelState.AddModelError("MinDateOfBirth", "date error");
}
model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth,
sortExpression, startRowIndex, maximumRows);
return View("Listing", model);
}
public ActionResult GetDetails(int id)
{
return View("Details", new PersonSearch().GetDetails(id));
}
}
}```
Clear sort and start when search changes (same as Web Forms). Cleaner to take data from StateContext instead of parameters because most can change within the method | ```c#
using Navigation.Sample.Models;
using System;
using System.Web.Mvc;
namespace Navigation.Sample.Controllers
{
public class PersonController : Controller
{
public ActionResult Index(PersonSearchModel model)
{
DateTime outDate;
if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate))
{
if (StateContext.Bag.name != model.Name || StateContext.Bag.minDateOfBirth != model.MinDateOfBirth)
{
StateContext.Bag.startRowIndex = null;
StateContext.Bag.sortExpression = null;
}
StateContext.Bag.name = model.Name;
StateContext.Bag.minDateOfBirth = model.MinDateOfBirth;
}
else
{
ModelState.AddModelError("MinDateOfBirth", "date error");
}
model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth,
StateContext.Bag.sortExpression, StateContext.Bag.startRowIndex, StateContext.Bag.maximumRows);
return View("Listing", model);
}
public ActionResult GetDetails(int id)
{
return View("Details", new PersonSearch().GetDetails(id));
}
}
}``` |
81a2b82d-fe66-45a2-8a1a-37ba9b52ed59 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; }
public object Json { get; set; }
}
}
```
Fix unit test by making the Data property writable | ```c#
using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; set; }
public object Json { get; set; }
}
}
``` |
a6c5bd0d-20ea-46ca-afd4-f03b4491f715 | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
}```
Drop in a note for later. | ```c#
using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
// I don't think this is the right spot for this
//httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
}``` |
06539b3a-ceea-40d5-ad6a-78a5fa3d4fe6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
return Enumerable.Empty<RoomSessionSchedule>();
}
}
}```
Implement GetSchedule functionality for Rooms | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
using ISTS.Infrastructure.Model;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
private readonly IstsContext _context;
public RoomRepository(
IstsContext context)
{
_context = context;
}
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
var sessions = _context.Sessions
.Where(s => s.RoomId == id)
.ToList();
var schedule = sessions
.Select(s => RoomSessionSchedule.Create(s.Id, s.Schedule));
return schedule;
}
}
}``` |
c40f0a9e-3158-4225-85f1-f60001690196 | {
"language": "C#"
} | ```c#
<div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text">
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password">
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div>```
Add invalid message + aria tags to login | ```c#
@model bool
@{
var invalidAttributes = Model ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : "";
}
<div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
@if (Model)
{
<div class="error" style="margin-bottom: 10px;" id="invalidMessage">
<p class="error-message">Invalid Email address / Password</p>
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text"
autofocus="autofocus" aria-required="true" @invalidAttributes>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password"
aria-required="true" @invalidAttributes>
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div>``` |
3c4cd486-1426-431f-b751-b52cb5ec8b62 | {
"language": "C#"
} | ```c#
namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return Expression;
}
}
}
```
Improve debug string representation of MacroDefinition. | ```c#
namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return string.Format("{0} = {1}", Name, Expression);
}
}
}
``` |
46cd4d4e-45af-447c-acac-f9a0e17ac5ed | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
db.FileStorage.Upload("Core.dll", "Core.dll");
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
}```
Add more unit test filestorage | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Linq;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
// upload
db.FileStorage.Upload("Core.dll", "Core.dll");
// exits
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
// find
var files = db.FileStorage.Find("Core");
Assert.AreEqual(1, files.Count());
Assert.AreEqual("Core.dll", files.First().Id);
// find by id
var core = db.FileStorage.FindById("Core.dll");
Assert.IsNotNull(core);
Assert.AreEqual("Core.dll", core.Id);
// download
var mem = new MemoryStream();
db.FileStorage.Download("Core.dll", mem);
var content = Encoding.UTF8.GetString(mem.ToArray());
Assert.AreEqual("FileCoreContent", content);
// delete
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
// not found deleted
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
}``` |
5f1aa981-7968-4375-bf68-ee3a8d16ef7c | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonIgnore]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public string ZoneEmphasisString { get; set; }
}
}
```
Fix serialization of the zoneemphasis | ```c#
using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonIgnore]
public string ZoneEmphasisString { get; set; }
}
}
``` |
11697242-4a67-40dc-9d7c-524dbd00af29 | {
"language": "C#"
} | ```c#
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public abstract class GameMessageBase : MessageBase
{
public GameObject NetworkObject;
public GameObject[] NetworkObjects;
protected IEnumerator WaitFor(NetworkInstanceId id)
{
int tries = 0;
while ((NetworkObject = ClientScene.FindLocalObject(id)) == null)
{
if (tries++ > 10)
{
Debug.LogWarning("GameMessageBase could not find object with id " + id);
yield break;
}
yield return YieldHelper.EndOfFrame;
}
}
protected IEnumerator WaitFor(params NetworkInstanceId[] ids)
{
NetworkObjects = new GameObject[ids.Length];
while (!AllLoaded(ids))
{
yield return YieldHelper.EndOfFrame;
}
}
private bool AllLoaded(NetworkInstanceId[] ids)
{
for (int i = 0; i < ids.Length; i++)
{
GameObject obj = ClientScene.FindLocalObject(ids[i]);
if (obj == null)
{
return false;
}
NetworkObjects[i] = obj;
}
return true;
}
}```
Print more info if the message times out while waiting | ```c#
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public abstract class GameMessageBase : MessageBase
{
public GameObject NetworkObject;
public GameObject[] NetworkObjects;
protected IEnumerator WaitFor(NetworkInstanceId id)
{
int tries = 0;
while ((NetworkObject = ClientScene.FindLocalObject(id)) == null)
{
if (tries++ > 10)
{
Debug.LogWarning($"{this} could not find object with id {id}");
yield break;
}
yield return YieldHelper.EndOfFrame;
}
}
protected IEnumerator WaitFor(params NetworkInstanceId[] ids)
{
NetworkObjects = new GameObject[ids.Length];
while (!AllLoaded(ids))
{
yield return YieldHelper.EndOfFrame;
}
}
private bool AllLoaded(NetworkInstanceId[] ids)
{
for (int i = 0; i < ids.Length; i++)
{
GameObject obj = ClientScene.FindLocalObject(ids[i]);
if (obj == null)
{
return false;
}
NetworkObjects[i] = obj;
}
return true;
}
}
``` |
de519c64-325f-43d7-b30e-13ae247cea28 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, context.Request.Method))
{
await TraceHelper.TracedActionAsync(next());
}
});
}
}
}```
Add http path under http.uri tag | ```c#
using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.uri", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
}``` |
445af786-c2d1-4d3c-a226-99c7e03f1fb3 | {
"language": "C#"
} | ```c#
namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
Tensor<double> result = new Tensor<double>();
result.SetValue(tensor1.GetValue() / tensor2.GetValue());
return result;
}
}
}
```
Refactor Divide Doubles operation to use GetValues and CloneWithValues | ```c#
namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
double[] values1 = tensor1.GetValues();
int l = values1.Length;
double value2 = tensor2.GetValue();
double[] newvalues = new double[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] / value2;
return tensor1.CloneWithNewValues(newvalues);
}
}
}
``` |
fc62cff6-8646-4ce9-9645-cc14b8efecc9 | {
"language": "C#"
} | ```c#
namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this BoundActorTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
```
Add IRequestTarget.Cast instead of BoundActorTarget.* | ```c#
namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this IRequestTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
``` |
2b3ab885-a46d-461f-ad03-7c6de697a25d | {
"language": "C#"
} | ```c#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
}```
Add error checking to basic auth header | ```c#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName));
if (password == null) password = "";
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
}``` |
e546a99a-5b5c-42b6-9fc3-7cc558c04160 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
```
Fix for get current user on anon page | ```c#
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
if (string.IsNullOrWhiteSpace(email)) return default(Soldier);
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
``` |
cb014a47-0c2a-4cd8-8da8-1f7e2080685d | {
"language": "C#"
} | ```c#
// 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.
namespace Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14
}
}```
Update enum for VS 2017 | ```c#
// 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.
namespace Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14,
/// <summary>
/// MSBuildVersion : <c>15</c>
/// </summary>
MSBuild15 = 15
}
}``` |
e1ff7d9b-e55a-4c49-827d-56a6ead1239d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Updater
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
TryStartSc();
}
if (args.Length != 2)
return;
var setupExe= args[0];
var setupExeArgs = args[1];
if (!File.Exists(setupExe))
{
Environment.ExitCode = -1;
return;
}
//Console.WriteLine("Updating...");
var p = Process.Start(setupExe, setupExeArgs);
if (p.WaitForExit(10000))
{
TryStartSc();
}
}
public static bool TryStartSc()
{
var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe");
if (File.Exists(scExe))
{
Process.Start(scExe);
return true;
}
return false;
}
}
}
```
Fix setup not being able to start for first 10s | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Updater
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
TryStartSc();
}
if (args.Length != 2)
return;
var setupExe= args[0];
var setupExeArgs = args[1];
if (!File.Exists(setupExe))
{
Environment.ExitCode = -1;
return;
}
//Console.WriteLine("Updating...");
var p = Process.Start(setupExe, setupExeArgs);
}
public static bool TryStartSc()
{
var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe");
if (File.Exists(scExe))
{
Process.Start(scExe);
return true;
}
return false;
}
}
}
``` |
a73be33b-4f3c-4484-bcd1-8c35097ad210 | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="succesful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccesfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
```
Fix spelling of SuccessfulShards in CatSnapshots | ```c#
using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="successful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccessfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
``` |
cb291f46-ac89-4094-b0d9-4d33d50446e6 | {
"language": "C#"
} | ```c#
namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
}```
Comment code that should be commented | ```c#
namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
//string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
}``` |
7a305e8e-c7b5-497a-8137-c2f60108747b | {
"language": "C#"
} | ```c#
using System;
using System.Data;
using System.Linq;
using Cobweb.Data;
using Cobweb.Data.NHibernate;
using NHibernate;
namespace Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
```
Adjust namespaces for Data.NHibernate4 unit tests. | ```c#
using System;
using System.Data;
using System.Linq;
using NHibernate;
namespace Cobweb.Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
``` |
0ee231a4-acc1-484b-aff7-037686713b62 | {
"language": "C#"
} | ```c#
using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
}
}
```
Extend the boxing/unboxing test with a primitive value unbox | ```c#
using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
object i = 42;
Console.WriteLine((int)i);
}
}
``` |
c744abcf-2c78-4c93-8841-9bce98fe680e | {
"language": "C#"
} | ```c#
using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
public class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
```
Fix issue with test class | ```c#
using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
internal class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
``` |
c7e25cf1-fe58-4247-b70f-10d092750377 | {
"language": "C#"
} | ```c#
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, C#!");
}
}
```
Repair error in Console Writeline | ```c#
using System;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now);
}
}
``` |
f598980c-0895-47db-ac97-bf630b9d5f56 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
event EventHandler StatusChanged;
}
}
```
Add remarks about non-UI thread | ```c#
using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
/// <remarks>
/// This property might be changed by a non-UI thread.
/// </remarks>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
/// <remarks>
/// This event might fire on a non-UI thread.
/// </remarks>
event EventHandler StatusChanged;
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.