doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
e9d336a7-091e-4083-b369-006f7e31bf83 | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;
namespace Slp.Evi.Test.System.Sparql.Vendor
{
public sealed class MsSqlSparqlFixture
: SparqlFixture
{
public MsSqlSparqlFixture()
{
// Prepare all databases beforehand
var bootUp = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct()
.Select(x => base.GetStorage(x));
}
protected override ISqlDatabase GetSqlDb()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("database.json")
.AddEnvironmentVariables();
var config = builder.Build();
var connectionString = config.GetConnectionString("mssql");
return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
}
}
public class MsSqlSparqlTestSuite
: SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
{
public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
: base(fixture)
{
}
}
}
```
Improve way how fixture is bootup. | ```c#
using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;
namespace Slp.Evi.Test.System.Sparql.Vendor
{
public sealed class MsSqlSparqlFixture
: SparqlFixture
{
public MsSqlSparqlFixture()
{
// Prepare all databases beforehand
var datasetsToBootup = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct();
foreach (var dataset in datasetsToBootup)
{
GetStorage(dataset);
}
}
protected override ISqlDatabase GetSqlDb()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("database.json")
.AddEnvironmentVariables();
var config = builder.Build();
var connectionString = config.GetConnectionString("mssql");
return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
}
}
public class MsSqlSparqlTestSuite
: SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
{
public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
: base(fixture)
{
}
}
}
``` |
94c9a0bc-91bb-40db-9836-c66887bbbdd5 | {
"language": "C#"
} | ```c#
using System;
using UnityEngine;
namespace Alensia.Core.UI.Legacy
{
[Serializable]
public class CursorDefinition
{
public bool Visible;
public CursorLockMode LockMode;
public Vector2 Hotspot;
public Texture2D Image;
public void Apply()
{
Cursor.visible = Visible;
Cursor.lockState = LockMode;
Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
}
public static CursorDefinition Hidden = new CursorDefinition
{
Visible = false,
LockMode = CursorLockMode.Locked
};
public static CursorDefinition Default = new CursorDefinition
{
Visible = true,
LockMode = CursorLockMode.None
};
}
}```
Fix compile error with namespace conflict | ```c#
using System;
using UnityEngine;
namespace Alensia.Core.UI.Legacy
{
[Serializable]
public class CursorDefinition
{
public bool Visible;
public CursorLockMode LockMode;
public Vector2 Hotspot;
public Texture2D Image;
public void Apply()
{
UnityEngine.Cursor.visible = Visible;
UnityEngine.Cursor.lockState = LockMode;
UnityEngine.Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
}
public static CursorDefinition Hidden = new CursorDefinition
{
Visible = false,
LockMode = CursorLockMode.Locked
};
public static CursorDefinition Default = new CursorDefinition
{
Visible = true,
LockMode = CursorLockMode.None
};
}
}``` |
76523be0-b8a7-4023-b080-6c878105f1a8 | {
"language": "C#"
} | ```c#
using AsmResolver.PE.Debug.CodeView;
namespace AsmResolver.PE.Debug
{
/// <summary>
/// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
/// </summary>
public class DefaultDebugDataReader : IDebugDataReader
{
/// <inheritdoc />
public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
IBinaryStreamReader reader)
{
if (type == DebugDataType.CodeView)
return CodeViewDataSegment.FromReader(reader);
return new CustomDebugDataSegment(type, DataSegment.FromReader(reader));
}
}
}
```
Change if to switch expression | ```c#
using AsmResolver.PE.Debug.CodeView;
namespace AsmResolver.PE.Debug
{
/// <summary>
/// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
/// </summary>
public class DefaultDebugDataReader : IDebugDataReader
{
/// <inheritdoc />
public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
IBinaryStreamReader reader)
{
return type switch
{
DebugDataType.CodeView => CodeViewDataSegment.FromReader(reader, context),
_ => new CustomDebugDataSegment(type, DataSegment.FromReader(reader))
};
}
}
}
``` |
275f7ff5-f801-4b0b-908f-a9ae8402abed | {
"language": "C#"
} | ```c#
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SimpSim.NET
{
public class StateSaver
{
public virtual void SaveMemory(Memory memory, FileInfo file)
{
Save(memory, file);
}
public virtual Memory LoadMemory(FileInfo file)
{
return Load<Memory>(file);
}
public virtual void SaveRegisters(Registers registers, FileInfo file)
{
Save(registers, file);
}
public virtual Registers LoadRegisters(FileInfo file)
{
return Load<Registers>(file);
}
public virtual void SaveMachine(Machine machine, FileInfo file)
{
Save(machine, file);
}
public virtual Machine LoadMachine(FileInfo file)
{
return Load<Machine>(file);
}
private void Save(object @object, FileInfo file)
{
using (var fileStream = file.Create())
new BinaryFormatter().Serialize(fileStream, @object);
}
private T Load<T>(FileInfo file)
{
using (var fileStream = file.OpenRead())
return (T)new BinaryFormatter().Deserialize(fileStream);
}
}
}
```
Replace BinaryFormatter with JsonSerializer due to the former being obsoleted. Tests still fail. | ```c#
using System.IO;
using System.Text.Json;
namespace SimpSim.NET
{
public class StateSaver
{
public virtual void SaveMemory(Memory memory, FileInfo file)
{
Save(memory, file);
}
public virtual Memory LoadMemory(FileInfo file)
{
return Load<Memory>(file);
}
public virtual void SaveRegisters(Registers registers, FileInfo file)
{
Save(registers, file);
}
public virtual Registers LoadRegisters(FileInfo file)
{
return Load<Registers>(file);
}
public virtual void SaveMachine(Machine machine, FileInfo file)
{
Save(machine, file);
}
public virtual Machine LoadMachine(FileInfo file)
{
return Load<Machine>(file);
}
private void Save(object @object, FileInfo file)
{
using (var streamWriter = file.CreateText())
streamWriter.Write(JsonSerializer.Serialize(@object));
}
private T Load<T>(FileInfo file)
{
using (var streamReader = file.OpenText())
return JsonSerializer.Deserialize<T>(streamReader.ReadToEnd());
}
}
}
``` |
a0fc5ac0-10fd-4b4a-9f24-476566e974cd | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class DeskLampPuzzle : Puzzle
{
private bool isLampOn = false;
private bool hasLampBeenTurnedOn = false;
private InteractableSwitch lampSwitch;
// Use this for initialization
public override void Start ()
{
base.Start();
lampSwitch = GetComponent<InteractableSwitch>();
}
// Update is called once per frame
void Update () {
if (isLampOn != lampSwitch.turnedOn) {
isLampOn = lampSwitch.turnedOn;
hasLampBeenTurnedOn = true;
base.CompletePuzzle();
}
}
}
```
Check that the puzzle has not already been solved. | ```c#
using UnityEngine;
using System.Collections;
public class DeskLampPuzzle : Puzzle
{
private bool isLampOn = false;
private bool hasLampBeenTurnedOn = false;
private InteractableSwitch lampSwitch;
// Use this for initialization
public override void Start ()
{
base.Start();
lampSwitch = GetComponent<InteractableSwitch>();
}
// Update is called once per frame
void Update () {
if (isLampOn != lampSwitch.turnedOn) {
isLampOn = lampSwitch.turnedOn;
if (!hasLampBeenTurnedOn) {
base.CompletePuzzle();
}
hasLampBeenTurnedOn = true;
}
}
}
``` |
869bbb27-09c3-4167-aede-745446faf32b | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace EloWeb.Models
{
public class Games
{
public enum GamesSortOrder
{
MostRecentFirst = 1,
MostRecentLast = 2
}
private static List<Game> _games = new List<Game>();
public static void Initialise(IEnumerable<Game> gameEntities)
{
_games = gameEntities.ToList();
foreach(var game in _games)
Players.UpdateRatings(game);
}
public static void Add(Game game)
{
_games.Add(game);
}
public static IEnumerable<Game> All()
{
return _games.AsEnumerable();
}
public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
{
var games = _games.AsEnumerable()
.OrderBy(g => g.WhenPlayed)
.Reverse()
.Take(howMany);
if (sortOrder == GamesSortOrder.MostRecentLast)
return games.Reverse();
return games;
}
public static IEnumerable<Game> GamesByPlayer(string name)
{
return _games.Where(game => game.Winner == name || game.Loser == name);
}
}
}```
Fix order of games when calculating ratings | ```c#
using System.Collections.Generic;
using System.Linq;
namespace EloWeb.Models
{
public class Games
{
public enum GamesSortOrder
{
MostRecentFirst = 1,
MostRecentLast = 2
}
private static List<Game> _games = new List<Game>();
public static void Initialise(IEnumerable<Game> gameEntities)
{
_games = gameEntities
.OrderBy(g => g.WhenPlayed)
.ToList();
foreach(var game in _games)
Players.UpdateRatings(game);
}
public static void Add(Game game)
{
_games.Add(game);
}
public static IEnumerable<Game> All()
{
return _games.AsEnumerable();
}
public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
{
var games = _games.AsEnumerable()
.OrderBy(g => g.WhenPlayed)
.Reverse()
.Take(howMany);
if (sortOrder == GamesSortOrder.MostRecentLast)
return games.Reverse();
return games;
}
public static IEnumerable<Game> GamesByPlayer(string name)
{
return _games.Where(game => game.Winner == name || game.Loser == name);
}
}
}``` |
e773ed62-2197-4572-b5d9-7f4ac3a73df2 | {
"language": "C#"
} | ```c#
@using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
}
<div>
<form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture" asp-for="@Context.GetCurrentCulture()" asp-items="cultureItems"></select>
<button>OK</button>
</form>
</div>```
Fix issue with tagHelper that requries field or property to target for | ```c#
@using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
var currentCulture = Context.GetCurrentCulture();
}
<div>
<form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture" asp-for="@currentCulture" asp-items="cultureItems"></select>
<button>OK</button>
</form>
</div>``` |
82d17d8f-605f-4035-9bf1-91f4acc2f6ba | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Security")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ea66be4b-3391-49c4-96e8-b1b9044397b9")]
```
Correct AssemblyProduct name from Security to Credentials | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Credentials")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ea66be4b-3391-49c4-96e8-b1b9044397b9")]
``` |
3dcd2eff-eb30-4988-b92d-9dd06fab2f46 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyCopyright("Copyright © Xamarin Inc. 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9453e5ef-4541-4491-941f-d20f4e39c967")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Drop the Xamarin copyright after the CLA has been signed to contribute this back to Microsoft | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9453e5ef-4541-4491-941f-d20f4e39c967")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
``` |
c191373c-95e8-484e-bffe-3c487f575c75 | {
"language": "C#"
} | ```c#
using Arkivverket.Arkade.Core.Base.Addml.Processes;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public static class ArkadeTestNameProvider
{
public static string GetDisplayName(IArkadeTest arkadeTest)
{
TestId testId = arkadeTest.GetId();
string testName = GetTestName(testId);
string displayName = testName != null
? string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName)
: GetFallBackDisplayName(arkadeTest);
return displayName;
}
private static string GetTestName(TestId testId)
{
string resourceDisplayNameKey = testId.ToString().Replace('.', '_');
if (testId.Version.Equals("5.5"))
resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";
return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
}
private static string GetFallBackDisplayName(IArkadeTest arkadeTest)
{
try
{
return ((AddmlProcess) arkadeTest).GetName(); // Process name
}
catch
{
return arkadeTest.GetType().Name; // Class name
}
}
}
}
```
Remove no longer needed display name fallback | ```c#
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public static class ArkadeTestNameProvider
{
public static string GetDisplayName(IArkadeTest arkadeTest)
{
TestId testId = arkadeTest.GetId();
string testName = GetTestName(testId);
return string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName);
}
private static string GetTestName(TestId testId)
{
string resourceDisplayNameKey = testId.ToString().Replace('.', '_');
if (testId.Version.Equals("5.5"))
resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";
return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
}
}
}
``` |
42a0d8c9-60ab-426e-a135-91150a4c3935 | {
"language": "C#"
} | ```c#
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
```
Add Scripts section and Bootstrap styling. | ```c#
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/bootstrap.min.css")
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("Scripts", false)
</body>
</html>
``` |
5872ef42-6b22-46a2-92ca-6929f3524763 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Mango;
//
// This the default StaticContentModule that comes with all Mango apps
// if you do not wish to serve any static content with Mango you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace AppNameFoo {
public class StaticContentModule : MangoModule {
public StaticContentModule ()
{
Get ("*", Content);
}
public static void Content (IMangoContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
```
Use the correct namespace on the static content module. | ```c#
using System;
using System.IO;
using Mango;
//
// This the default StaticContentModule that comes with all Mango apps
// if you do not wish to serve any static content with Mango you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : MangoModule {
public StaticContentModule ()
{
Get ("*", Content);
}
public static void Content (IMangoContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
``` |
4ae10e0c-f314-4774-94bf-b9d18052ea50 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace GridDomain.CQRS.Messaging.MessageRouting
{
public class ProjectionGroup: IProjectionGroup
{
private readonly IServiceLocator _locator;
readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();
public ProjectionGroup(IServiceLocator locator)
{
_locator = locator;
}
public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
{
var handler = _locator.Resolve<THandler>();
List<Action<object>> builderList;
if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
{
builderList = new List<Action<object>>();
_handlers[typeof (TMessage)] = builderList;
}
builderList.Add(o => handler.Handle((TMessage) o));
_acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
}
public void Project(object message)
{
var msgType = message.GetType();
foreach(var handler in _handlers[msgType])
handler(message);
}
private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
}
}```
Fix for several handlers for one message in projection group | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace GridDomain.CQRS.Messaging.MessageRouting
{
public class ProjectionGroup: IProjectionGroup
{
private readonly IServiceLocator _locator;
readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();
public ProjectionGroup(IServiceLocator locator)
{
_locator = locator;
}
public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
{
var handler = _locator.Resolve<THandler>();
List<Action<object>> builderList;
if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
{
builderList = new List<Action<object>>();
_handlers[typeof (TMessage)] = builderList;
}
builderList.Add(o => handler.Handle((TMessage) o));
if(_acceptMessages.All(m => m.MessageType != typeof (TMessage)))
_acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
}
public void Project(object message)
{
var msgType = message.GetType();
foreach(var handler in _handlers[msgType])
handler(message);
}
private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
}
}``` |
f5a95ff0-a32d-4ed1-8089-91db23eca282 | {
"language": "C#"
} | ```c#
using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client.Test
{
[TestFixture]
internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
{
[SetUp]
protected override void Setup()
{
base.Setup();
}
[TearDown]
protected override void TearDown()
{
base.TearDown();
}
[Test]
public async Task Send_Command_And_Receive_Response_With_Success()
{
//Arrange
var commandId = Guid.NewGuid();
var commandResponse = new Command
{
Id = commandId,
Status = CommandStatus.Success,
};
ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
await MessagingHubClient.StartAsync();
//Act
var result = MessagingHubClient.SendCommandAsync(new Command { Id = commandId }).Result;
//Assert
ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
result.ShouldNotBeNull();
result.Status.ShouldBe(CommandStatus.Success);
result.Id.ShouldBe(commandId);
}
[Test]
public void Send_Command_Without_Start_Should_Throw_Exception()
{
//Act / Assert
Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
}
}
}
```
Use await um command tests | ```c#
using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client.Test
{
[TestFixture]
internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
{
[SetUp]
protected override void Setup()
{
base.Setup();
}
[TearDown]
protected override void TearDown()
{
base.TearDown();
}
[Test]
public async Task Send_Command_And_Receive_Response_With_Success()
{
//Arrange
var commandId = Guid.NewGuid();
var commandResponse = new Command
{
Id = commandId,
Status = CommandStatus.Success,
};
ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
await MessagingHubClient.StartAsync();
//Act
var result = await MessagingHubClient.SendCommandAsync(new Command { Id = commandId });
await Task.Delay(TIME_OUT);
//Assert
ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
result.ShouldNotBeNull();
result.Status.ShouldBe(CommandStatus.Success);
result.Id.ShouldBe(commandId);
}
[Test]
public void Send_Command_Without_Start_Should_Throw_Exception()
{
//Act / Assert
Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
}
}
}
``` |
95297159-6ea2-41ec-94bb-a285fb82888e | {
"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.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneTimingScreen()
{
editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new TimingScreen();
}
}
}
```
Fix beatmap potentially changing in test scene | ```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.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneTimingScreen()
{
editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Beatmap.Disabled = true;
Child = new TimingScreen();
}
protected override void Dispose(bool isDisposing)
{
Beatmap.Disabled = false;
base.Dispose(isDisposing);
}
}
}
``` |
4ffea42a-35cc-40a1-93d8-c4d308e2010b | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public IEnumerable<Embed> NavItems
{
get
{
// TODO Only for nav items
// TODO Only for the logged in unit
yield return new Embed { Name = "PO Tracker" };
yield return new Embed { Name = "SUTA" };
//return
// db
// .Embeds
// .ToList();
}
}
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
}```
Use the actual db data | ```c#
using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public IEnumerable<Embed> NavItems
{
get
{
// TODO Only for nav items
// TODO Only for the logged in uni
return
db
.Embeds
.ToList();
}
}
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
}``` |
2015707c-51e1-4b2b-b13a-38f442a5d283 | {
"language": "C#"
} | ```c#
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
{
public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope) =>
new Message<TKey, TVal>
{
Headers = new Headers(),
Value = (TVal) envelope.Message
};
public Envelope ReadEnvelope(Message<TKey, TVal> message)
{
var env = new Envelope();
foreach (var header in message.Headers)
{
env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
}
env.Message = message.Value;
return env;
}
}
}
```
Make sure Jasper MessageId goes across the wire | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
{
private const string JasperMessageIdHeader = "Jasper_MessageId";
public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope)
{
var message = new Message<TKey, TVal>
{
Headers = new Headers(),
Value = (TVal) envelope.Message
};
foreach (KeyValuePair<string, string> h in envelope.Headers)
{
Header header = new Header(h.Key, Encoding.UTF8.GetBytes(h.Value));
message.Headers.Add(header);
}
message.Headers.Add(JasperMessageIdHeader, Encoding.UTF8.GetBytes(envelope.Id.ToString()));
return message;
}
public Envelope ReadEnvelope(Message<TKey, TVal> message)
{
var env = new Envelope();
foreach (var header in message.Headers.Where(h => !h.Key.StartsWith("Jasper")))
{
env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
}
var messageIdHeader = message.Headers.Single(h => h.Key.Equals(JasperMessageIdHeader));
env.Id = Guid.Parse(Encoding.UTF8.GetString(messageIdHeader.GetValueBytes()));
env.Message = message.Value;
return env;
}
}
}
``` |
13cd8647-3d6c-4c24-a7e7-87c8a8e2c17e | {
"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.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
public DownloadButton(APIBeatmapSet beatmapSet)
{
this.beatmapSet = beatmapSet;
Icon.Icon = FontAwesome.Solid.FileDownload;
}
// TODO: implement behaviour
}
}
```
Remove unused field for now to appease inspectcode | ```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.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
public DownloadButton(APIBeatmapSet beatmapSet)
{
Icon.Icon = FontAwesome.Solid.FileDownload;
}
// TODO: implement behaviour
}
}
``` |
666a6187-6e3b-458f-9aad-ddeaf3b44d9a | {
"language": "C#"
} | ```c#
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace Orchard.Lists {
public class Migrations : DataMigrationImpl {
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("List",
cfg=>cfg
.WithPart("CommonPart")
.WithPart("RoutePart")
.WithPart("ContainerPart")
.WithPart("MenuPart")
.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
.Creatable());
return 3;
}
public int UpdateFrom1() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom2() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
}
}
```
Update Lists migrations for Autoroute | ```c#
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace Orchard.Lists {
public class Migrations : DataMigrationImpl {
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("List",
cfg=>cfg
.WithPart("CommonPart")
.WithPart("TitlePart")
.WithPart("AutoroutePart")
.WithPart("ContainerPart")
.WithPart("MenuPart")
.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
.Creatable());
return 4;
}
public int UpdateFrom1() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom2() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom3() {
// TODO: (PH:Autoroute) Copy paths, routes, etc.
ContentDefinitionManager.AlterTypeDefinition("List",
cfg => cfg
.RemovePart("RoutePart")
.WithPart("TitlePart")
.WithPart("AutoroutePart"));
return 4;
}
}
}
``` |
6503a74f-909f-492d-aecc-0001d6cb7010 | {
"language": "C#"
} | ```c#
using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
/// <summary>
/// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carrier</remarks>
[DataContract(Name = "carrier")]
public class Carrier
{
/// <summary>
/// The carrier identifier.
/// </summary>
[DataMember(Name = "id")]
public int? Id { get; set; }
/// <summary>
/// The name of the carrier.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// The windows available for ticket collection.
/// </summary>
[DataMember(Name = "pickup_windows")]
public IList<PickupWindow> PickupWindows { get; set; }
/// <summary>
/// Creates a new pickup for the ticket(s).
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
[Rel("carrier:createpickup")]
public Link CreatePickupLink { get; set; }
}
}
```
Add missing resource base class | ```c#
using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
/// <summary>
/// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carrier</remarks>
[DataContract(Name = "carrier")]
public class Carrier : Resource
{
/// <summary>
/// The carrier identifier.
/// </summary>
[DataMember(Name = "id")]
public int? Id { get; set; }
/// <summary>
/// The name of the carrier.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// The windows available for ticket collection.
/// </summary>
[DataMember(Name = "pickup_windows")]
public IList<PickupWindow> PickupWindows { get; set; }
/// <summary>
/// Creates a new pickup for the ticket(s).
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
[Rel("carrier:createpickup")]
public Link CreatePickupLink { get; set; }
}
}
``` |
b58831d3-5768-4a30-863e-78a2699b0867 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
```
Create server side API for single multiple answer question | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
``` |
04b1f7b2-1dbd-429d-aeaf-042b54759112 | {
"language": "C#"
} | ```c#
namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
```
Fix Areas property is not deserialized, In the return value of the GetRichMenuListAsync method. | ```c#
namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText,
Areas = ActionArea.CreateFrom(dynamicObject?.areas)
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
``` |
476ce850-60d2-478d-8edf-1686ac8b1324 | {
"language": "C#"
} | ```c#
using System;
namespace Staxel.Trace {
public struct TraceScope : IDisposable {
public TraceKey Key;
public TraceScope(TraceKey key) {
Key = key;
TraceRecorder.Enter(Key);
}
public void Dispose() {
TraceRecorder.Leave(Key);
}
}
}
```
Patch out the Tracescope for as far as possible when applicable. | ```c#
using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
namespace Staxel.Trace {
public struct TraceScope : IDisposable {
public TraceKey Key;
[TargetedPatchingOptOut("")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TraceScope(TraceKey key) {
Key = key;
TraceRecorder.Enter(Key);
}
[Conditional("TRACE")]
[TargetedPatchingOptOut("")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose() {
TraceRecorder.Leave(Key);
}
}
}
``` |
aba443c7-2a30-4539-be18-96f73dccb933 | {
"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.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Tests.Visual.Containers
{
public class TestSceneEnumerator : FrameworkTestScene
{
private Container parent;
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("create hierarchy", () => Child = parent = new Container
{
Child = new Container
{
}
});
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("create hierarchy", () => Child = parent = new Container
{
Child = new Container
{
}
});
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
}
}
```
Use SetUp for tests, add test for clearing children | ```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.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Tests.Visual.Containers
{
public class TestSceneEnumerator : FrameworkTestScene
{
private Container parent;
[SetUp]
public void SetUp()
{
Child = parent = new Container
{
Child = new Container
{
}
};
}
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Clear();
}
}));
}
}
}
``` |
743bf8bb-7a13-462b-8651-16972f907b13 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Veil;
using Veil.Helper;
namespace NitroNet.ViewEngine.TemplateHandler
{
internal class ComponentHelperHandler : IHelperHandler
{
private readonly INitroTemplateHandler _handler;
public ComponentHelperHandler(INitroTemplateHandler handler)
{
_handler = handler;
}
public bool IsSupported(string name)
{
return name.StartsWith("component", StringComparison.OrdinalIgnoreCase);
}
public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters)
{
RenderingParameter template;
var firstParameter = parameters.FirstOrDefault();
if (string.IsNullOrEmpty(firstParameter.Value))
{
template = new RenderingParameter("name")
{
Value = firstParameter.Key.Trim('"', '\'')
};
}
else
{
template = CreateRenderingParameter("name", parameters);
}
var skin = CreateRenderingParameter("template", parameters);
var dataVariation = CreateRenderingParameter("data", parameters);
_handler.RenderComponent(template, skin, dataVariation, model, context);
}
private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters)
{
var renderingParameter = new RenderingParameter(name);
if (parameters.ContainsKey(renderingParameter.Name))
{
var value = parameters[renderingParameter.Name];
if (!value.StartsWith("\"") && !value.StartsWith("'"))
{
renderingParameter.IsDynamic = true;
}
renderingParameter.Value = value.Trim('"', '\'');
}
return renderingParameter;
}
}
}```
Enable pattern helper as equivalent of component helper | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Veil;
using Veil.Helper;
namespace NitroNet.ViewEngine.TemplateHandler
{
internal class ComponentHelperHandler : IHelperHandler
{
private readonly INitroTemplateHandler _handler;
public ComponentHelperHandler(INitroTemplateHandler handler)
{
_handler = handler;
}
public bool IsSupported(string name)
{
return name.StartsWith("component", StringComparison.OrdinalIgnoreCase) || name.StartsWith("pattern", StringComparison.OrdinalIgnoreCase);
}
public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters)
{
RenderingParameter template;
var firstParameter = parameters.FirstOrDefault();
if (string.IsNullOrEmpty(firstParameter.Value))
{
template = new RenderingParameter("name")
{
Value = firstParameter.Key.Trim('"', '\'')
};
}
else
{
template = CreateRenderingParameter("name", parameters);
}
var skin = CreateRenderingParameter("template", parameters);
var dataVariation = CreateRenderingParameter("data", parameters);
_handler.RenderComponent(template, skin, dataVariation, model, context);
}
private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters)
{
var renderingParameter = new RenderingParameter(name);
if (parameters.ContainsKey(renderingParameter.Name))
{
var value = parameters[renderingParameter.Name];
if (!value.StartsWith("\"") && !value.StartsWith("'"))
{
renderingParameter.IsDynamic = true;
}
renderingParameter.Value = value.Trim('"', '\'');
}
return renderingParameter;
}
}
}``` |
b7601c26-298a-4afc-b66b-c6b7a5141465 | {
"language": "C#"
} | ```c#
using System;
namespace NHibernate.Sessions.Operations
{
public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation
{
protected abstract void ConfigureCache(CacheConfig cacheConfig);
protected abstract T QueryDatabase(ISessionManager sessionManager);
public virtual string CacheKeyPrefix
{
get { return GetType().FullName; }
}
protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null)
{
var cacheConfig = CacheConfig.None;
ConfigureCache(cacheConfig);
if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero)
return QueryDatabase(sessionManager);
return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls);
}
}
}```
Make the CackeKeyPrefix protected instead of Public | ```c#
using System;
namespace NHibernate.Sessions.Operations
{
public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation
{
protected abstract void ConfigureCache(CacheConfig cacheConfig);
protected abstract T QueryDatabase(ISessionManager sessionManager);
protected virtual string CacheKeyPrefix
{
get { return GetType().FullName; }
}
protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null)
{
var cacheConfig = CacheConfig.None;
ConfigureCache(cacheConfig);
if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero)
return QueryDatabase(sessionManager);
return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls);
}
}
}``` |
3da0d6bf-691e-49e9-be65-38863df4342b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Core.EventDelegate
{
public class JsonRPCEventDelegate
{
private string RPCUrl;
public JsonRPCEventDelegate(int port)
{
this.RPCUrl = "http://localhost:" + port.ToString() + @"/";
}
public void Notify(string eventName, dynamic eventData)
{
WebRequest request = WebRequest.Create (this.RPCUrl);
request.ContentType = "application/json-rpc";
request.Method = "POST";
var values = new Dictionary<string, dynamic>(){
{"method", "notify"},
{"params", JsonConvert.SerializeObject(eventData)},
{"id", "null"}
};
var data = JsonConvert.SerializeObject(values);
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
WebResponse response = request.GetResponse();
}
}
}
```
Create generic invoke method for RPC | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Core.EventDelegate
{
public class JsonRPCEventDelegate
{
private string RPCUrl;
public JsonRPCEventDelegate(int port)
{
this.RPCUrl = "http://localhost:" + port.ToString() + @"/";
}
public WebResponse InvokeMethod(string method, string methodParams, string id)
{
WebRequest request = WebRequest.Create(this.RPCUrl);
request.ContentType = "application/json-rpc";
request.Method = "POST";
var values = new Dictionary<string, dynamic>(){
{"method", method},
{"params", methodParams},
{"id", id}
};
var data = JsonConvert.SerializeObject(values);
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
return request.GetResponse();
}
public void Notify(string eventName, dynamic eventData)
{
var response = this.InvokeMethod(
"notify",
JsonConvert.SerializeObject(
new Dictionary<string, dynamic>(){
{"eventData", eventData},
{"eventName", eventName}
}),
"null"
);
}
}
}
``` |
39364cd7-a564-4664-9437-5e3601cc7647 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace Postolego {
public class PostolegoMapper : UriMapperBase {
public override Uri MapUri(Uri uri) {
var tempUri = HttpUtility.UrlDecode(uri.ToString());
if(tempUri.Contains("postolego:")) {
if(tempUri.Contains("authorize")) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
} else {
if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
}
}
}
}
```
Fix uri mapper return invalid uri | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace Postolego {
public class PostolegoMapper : UriMapperBase {
public override Uri MapUri(Uri uri) {
var tempUri = HttpUtility.UrlDecode(uri.ToString());
if(tempUri.Contains("postolego:")) {
if(tempUri.Contains("authorize")) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
}
}
if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
}
}
}
``` |
f1e30d57-e166-4a62-9dd2-de7d5233a284 | {
"language": "C#"
} | ```c#
using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay - DateTime.Now;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
span = span.Add(TimeSpan.FromDays((years + 1) * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
}```
Make sure date processing is accurate | ```c#
using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay.Date - DateTime.Now.Date;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
if (span.Days % 365 != 0) years++;
span = span.Add(TimeSpan.FromDays(years * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
}``` |
d00fadff-9b90-49a9-a3ed-a8c064b06b6b | {
"language": "C#"
} | ```c#
namespace MyCouch.IntegrationTests
{
internal static class TestClientFactory
{
internal static IClient CreateDefault()
{
return new Client("http://mycouchtester:1q2w3e4r@localhost:5984/" + TestConstants.TestDbName);
}
}
}```
Use at least a password that has char that needs to be encoded so that that is tested. | ```c#
using System;
namespace MyCouch.IntegrationTests
{
internal static class TestClientFactory
{
internal static IClient CreateDefault()
{
return new Client("http://mycouchtester:" + Uri.EscapeDataString("p@ssword") + "@localhost:5984/" + TestConstants.TestDbName);
}
}
}``` |
f0716252-239d-4ef7-b294-e545b9ede342 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.14.0")]
[assembly: AssemblyFileVersion("0.14.0")]
```
Increase project version to 0.15.0 | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.15.0")]
[assembly: AssemblyFileVersion("0.15.0")]
``` |
9fe5a901-3542-48c2-a5d3-9d4bb9230bce | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Argentum.Core;
namespace SilverScreen.Domain
{
public class Cinema : AggregateBase<CinemaState>
{
public Cinema(CinemaState state) : base(state) { }
private Cinema(string name)
{
Apply(new CinemaAdded(name));
}
public static Cinema Add(string name)
{
return new Cinema(name);
}
}
public class CinemaState : State
{
public string Name { get; set; }
public List<Screen> Screens { get; set; }
public void When(CinemaAdded evt)
{
Name = evt.Name;
}
}
public class CinemaAdded : IEvent
{
public string Name { get; private set; }
public CinemaAdded(string name)
{
Name = name;
}
}
}
```
Set id when adding new cinema | ```c#
using System;
using System.Collections.Generic;
using Argentum.Core;
namespace SilverScreen.Domain
{
public class Cinema : AggregateBase<CinemaState>
{
public Cinema(CinemaState state) : base(state) { }
private Cinema(Guid id, string name)
{
Apply(new CinemaAdded(id, name));
}
public static Cinema Add(string name)
{
return new Cinema(Guid.NewGuid(), name);
}
}
public class CinemaState : State
{
public string Name { get; set; }
public List<Screen> Screens { get; set; }
public void When(CinemaAdded evt)
{
Id = evt.Id;
Name = evt.Name;
}
}
public class CinemaAdded : IEvent
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public CinemaAdded(Guid id, string name)
{
Id = id;
Name = name;
}
}
}
``` |
4ce1533c-359d-48be-a8bb-b15614ac5d0d | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetHost : HttpTaskAsyncHandler
{
private readonly PersistentConnection _connection;
private static readonly Lazy<bool> _hasAcceptWebSocketRequest =
new Lazy<bool>(() =>
{
return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase));
});
public AspNetHost(PersistentConnection connection)
{
_connection = connection;
}
public override Task ProcessRequestAsync(HttpContextBase context)
{
var request = new AspNetRequest(context.Request);
var response = new AspNetResponse(context.Request, context.Response);
var hostContext = new HostContext(request, response, context.User);
// Determine if the client should bother to try a websocket request
hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value;
// Set the debugging flag
hostContext.Items["debugMode"] = context.IsDebuggingEnabled;
// Stick the context in here so transports or other asp.net specific logic can
// grab at it.
hostContext.Items["aspnet.context"] = context;
return _connection.ProcessRequestAsync(hostContext);
}
}
}
```
Change HttpContext variable to aspnet.HttpContext. | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetHost : HttpTaskAsyncHandler
{
private readonly PersistentConnection _connection;
private static readonly Lazy<bool> _hasAcceptWebSocketRequest =
new Lazy<bool>(() =>
{
return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase));
});
public AspNetHost(PersistentConnection connection)
{
_connection = connection;
}
public override Task ProcessRequestAsync(HttpContextBase context)
{
var request = new AspNetRequest(context.Request);
var response = new AspNetResponse(context.Request, context.Response);
var hostContext = new HostContext(request, response, context.User);
// Determine if the client should bother to try a websocket request
hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value;
// Set the debugging flag
hostContext.Items["debugMode"] = context.IsDebuggingEnabled;
// Stick the context in here so transports or other asp.net specific logic can
// grab at it.
hostContext.Items["aspnet.HttpContext"] = context;
return _connection.ProcessRequestAsync(hostContext);
}
}
}
``` |
c986c513-686f-4843-9903-1c37d265c07f | {
"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.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <returns>Whether the room could be joined.</returns>
Task<bool> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
Task LeaveRoom(long roomId);
}
}
```
Remove unnecessary room id from leave room request | ```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.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <returns>Whether the room could be joined.</returns>
Task<bool> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
}
}
``` |
c9feeb18-5af4-42a4-af1f-5e6edc526d3a | {
"language": "C#"
} | ```c#
###############################################################################
# Copyright Lewis Baker
# Licenced under MIT license. See LICENSE.txt for details.
###############################################################################
import cake.path
from cake.tools import compiler, script, env, project
includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [
'broken_promise.hpp',
'task.hpp',
'single_consumer_event.hpp',
])
sources = script.cwd([
'async_mutex.cpp',
])
extras = script.cwd([
'build.cake',
'use.cake',
])
buildDir = env.expand('${CPPCORO_BUILD}')
compiler.addIncludePath(env.expand('${CPPCORO}/include'))
objects = compiler.objects(
targetDir=env.expand('${CPPCORO_BUILD}/obj'),
sources=sources,
)
lib = compiler.library(
target=env.expand('${CPPCORO_LIB}/cppcoro'),
sources=objects,
)
vcproj = project.project(
target=env.expand('${CPPCORO_PROJECT}/cppcoro'),
items={
'Include': includes,
'Source': sources,
'': extras
},
output=lib,
)
script.setResult(
project=vcproj,
library=lib,
)
```
Add some missing headers to generated .vcproj file. | ```c#
###############################################################################
# Copyright Lewis Baker
# Licenced under MIT license. See LICENSE.txt for details.
###############################################################################
import cake.path
from cake.tools import compiler, script, env, project
includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [
'async_mutex.hpp',
'broken_promise.hpp',
'lazy_task.hpp',
'single_consumer_event.hpp',
'task.hpp',
])
sources = script.cwd([
'async_mutex.cpp',
])
extras = script.cwd([
'build.cake',
'use.cake',
])
buildDir = env.expand('${CPPCORO_BUILD}')
compiler.addIncludePath(env.expand('${CPPCORO}/include'))
objects = compiler.objects(
targetDir=env.expand('${CPPCORO_BUILD}/obj'),
sources=sources,
)
lib = compiler.library(
target=env.expand('${CPPCORO_LIB}/cppcoro'),
sources=objects,
)
vcproj = project.project(
target=env.expand('${CPPCORO_PROJECT}/cppcoro'),
items={
'Include': includes,
'Source': sources,
'': extras
},
output=lib,
)
script.setResult(
project=vcproj,
library=lib,
)
``` |
b363e611-0d85-4427-b895-811dd990e6c7 | {
"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.Game.Utils;
namespace osu.Game.Overlays.BeatmapListing
{
[HasOrderedElements]
public enum SearchLanguage
{
[Order(0)]
Any,
[Order(13)]
Other,
[Order(1)]
English,
[Order(6)]
Japanese,
[Order(2)]
Chinese,
[Order(12)]
Instrumental,
[Order(7)]
Korean,
[Order(3)]
French,
[Order(4)]
German,
[Order(9)]
Swedish,
[Order(8)]
Spanish,
[Order(5)]
Italian,
[Order(10)]
Russian,
[Order(11)]
Polish,
[Order(14)]
Unspecified
}
}
```
Update in line with other/unspecified switch | ```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.Game.Utils;
namespace osu.Game.Overlays.BeatmapListing
{
[HasOrderedElements]
public enum SearchLanguage
{
[Order(0)]
Any,
[Order(14)]
Unspecified,
[Order(1)]
English,
[Order(6)]
Japanese,
[Order(2)]
Chinese,
[Order(12)]
Instrumental,
[Order(7)]
Korean,
[Order(3)]
French,
[Order(4)]
German,
[Order(9)]
Swedish,
[Order(8)]
Spanish,
[Order(5)]
Italian,
[Order(10)]
Russian,
[Order(11)]
Polish,
[Order(13)]
Other
}
}
``` |
d86a5669-17d3-48e7-852d-ac024098ff0b | {
"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.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class DrawableOsuEditRuleset : DrawableOsuRuleset
{
public DrawableOsuEditRuleset(Ruleset ruleset, IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods)
: base(ruleset, beatmap, mods)
{
}
protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor();
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One };
private class OsuPlayfieldNoCursor : OsuPlayfield
{
protected override GameplayCursorContainer CreateCursor() => null;
}
}
}
```
Increase fade-out time of hitobjects in the editor | ```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.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class DrawableOsuEditRuleset : DrawableOsuRuleset
{
public DrawableOsuEditRuleset(Ruleset ruleset, IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods)
: base(ruleset, beatmap, mods)
{
}
public override DrawableHitObject<OsuHitObject> CreateDrawableRepresentation(OsuHitObject h)
=> base.CreateDrawableRepresentation(h)?.With(d => d.ApplyCustomUpdateState += updateState);
private void updateState(DrawableHitObject hitObject, ArmedState state)
{
switch (state)
{
case ArmedState.Miss:
// Get the existing fade out transform
var existing = hitObject.Transforms.LastOrDefault(t => t.TargetMember == nameof(Alpha));
if (existing == null)
return;
using (hitObject.BeginAbsoluteSequence(existing.StartTime))
hitObject.FadeOut(500).Expire();
break;
}
}
protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor();
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One };
private class OsuPlayfieldNoCursor : OsuPlayfield
{
protected override GameplayCursorContainer CreateCursor() => null;
}
}
}
``` |
72976332-f043-42d0-833e-772d5edbbb9a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ecologylab.semantics.metadata.scalar
{
abstract public class MetadataScalarBase<T>
{
public T value;
public static String VALUE_FIELD_NAME = "value";
public MetadataScalarBase()
{
}
public MetadataScalarBase(object value)
{
this.value = (T) value;
}
public object Value
{
get { return value; }
set { this.value = (T)value; }
}
public override String ToString()
{
return value == null ? "null" : value.ToString();
}
}
public class MetadataString : MetadataScalarBase<String>
{
public MetadataString(){}
//The termvector stuff goes here !
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public MetadataString(object value):base(value)
{}
}
public class MetadataInteger : MetadataScalarBase<int>
{
public MetadataInteger(){}
public MetadataInteger(object value):base(value)
{}
}
public class MetadataParsedURL : MetadataScalarBase<Uri>
{
public MetadataParsedURL(){}
public MetadataParsedURL(object value):base(value)
{}
}
public class MetadataDate : MetadataScalarBase<DateTime>
{
public MetadataDate(){}
public MetadataDate(object value):base(value)
{}
}
public class MetadataStringBuilder : MetadataScalarBase<StringBuilder>
{
public MetadataStringBuilder(){}
public MetadataStringBuilder(object value):base(value)
{}
}
}
```
Return type T for metadata scalars. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ecologylab.semantics.metadata.scalar
{
abstract public class MetadataScalarBase<T>
{
public T value;
public static String VALUE_FIELD_NAME = "value";
public MetadataScalarBase()
{
}
public MetadataScalarBase(object value)
{
this.value = (T) value;
}
public T Value
{
get { return value; }
set { this.value = (T)value; }
}
public override String ToString()
{
return value == null ? "null" : value.ToString();
}
}
public class MetadataString : MetadataScalarBase<String>
{
public MetadataString(){}
//The termvector stuff goes here !
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public MetadataString(object value):base(value)
{}
}
public class MetadataInteger : MetadataScalarBase<int>
{
public MetadataInteger(){}
public MetadataInteger(object value):base(value)
{}
}
public class MetadataParsedURL : MetadataScalarBase<Uri>
{
public MetadataParsedURL(){}
public MetadataParsedURL(object value):base(value)
{}
}
public class MetadataDate : MetadataScalarBase<DateTime>
{
public MetadataDate(){}
public MetadataDate(object value):base(value)
{}
}
public class MetadataStringBuilder : MetadataScalarBase<StringBuilder>
{
public MetadataStringBuilder(){}
public MetadataStringBuilder(object value):base(value)
{}
}
}
``` |
a3f59233-b838-4ead-a0f2-c23fe2b6eafd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Configuration;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}```
Change service's start mode to auto | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Configuration;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}``` |
1675bded-ade0-4025-937b-f5a8c0c28179 | {
"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.Game.Graphics;
using osu.Game.Online.Chat;
namespace osu.Game.Overlays.Chat.Tabs
{
public class ChannelSelectorTabItem : ChannelTabItem
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
protected override bool IsBoldWhenActive => false;
public ChannelSelectorTabItem()
: base(new ChannelSelectorTabChannel())
{
Depth = float.MaxValue;
Width = 45;
Icon.Alpha = 0;
Text.Font = Text.Font.With(size: 45);
Text.Truncate = false;
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundInactive = colour.Gray2;
BackgroundActive = colour.Gray3;
}
public class ChannelSelectorTabChannel : Channel
{
public ChannelSelectorTabChannel()
{
Name = "+";
}
}
}
}
```
Fix SelectorTab crashing tests after a reload | ```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.Game.Graphics;
using osu.Game.Online.Chat;
namespace osu.Game.Overlays.Chat.Tabs
{
public class ChannelSelectorTabItem : ChannelTabItem
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
protected override bool IsBoldWhenActive => false;
public ChannelSelectorTabItem()
: base(new ChannelSelectorTabChannel())
{
Depth = float.MaxValue;
Width = 45;
Icon.Alpha = 0;
Text.Font = Text.Font.With(size: 45);
Text.Truncate = false;
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundInactive = colour.Gray2;
BackgroundActive = colour.Gray3;
}
public class ChannelSelectorTabChannel : Channel
{
public ChannelSelectorTabChannel()
{
Name = "+";
Type = ChannelType.Temporary;
}
}
}
}
``` |
c2409576-0518-4709-93c4-0dfd90b24fd5 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Nohros.Configuration;
namespace Nohros.Data.Providers
{
public partial class SqlConnectionProvider : IConnectionProviderFactory
{
#region .ctor
/// <summary>
/// Constructor implied by the interface
/// <see cref="IConnectionProviderFactory"/>.
/// </summary>
SqlConnectionProvider() {
}
#endregion
#region IConnectionProviderFactory Members
/// <inheritdoc/>
IConnectionProvider IConnectionProviderFactory.CreateProvider(
IDictionary<string, string> options) {
string connection_string;
SqlConnectionStringBuilder builder;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
builder = new SqlConnectionStringBuilder(connection_string);
} else {
string[] data = ProviderOptions.ThrowIfNotExists(options, kServerOption,
kLoginOption, kPasswordOption);
const int kServer = 0;
const int kLogin = 1;
const int kPassword = 2;
builder = new SqlConnectionStringBuilder {
DataSource = data[kServer],
UserID = data[kLogin],
Password = data[kPassword]
};
}
return new SqlConnectionProvider(builder.ConnectionString);
}
#endregion
}
}
```
Fix a bug that causes the GetProviderNode to return null references. | ```c#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Nohros.Configuration;
namespace Nohros.Data.Providers
{
public partial class SqlConnectionProvider : IConnectionProviderFactory
{
#region .ctor
/// <summary>
/// Constructor implied by the interface
/// <see cref="IConnectionProviderFactory"/>.
/// </summary>
SqlConnectionProvider() { }
#endregion
#region IConnectionProviderFactory Members
/// <inheritdoc/>
IConnectionProvider IConnectionProviderFactory.CreateProvider(
IDictionary<string, string> options) {
string connection_string;
SqlConnectionStringBuilder builder;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
builder = new SqlConnectionStringBuilder(connection_string);
} else {
string[] data = ProviderOptions.ThrowIfNotExists(options, kServerOption,
kLoginOption, kPasswordOption);
const int kServer = 0;
const int kLogin = 1;
const int kPassword = 2;
builder = new SqlConnectionStringBuilder
{
DataSource = data[kServer],
UserID = data[kLogin],
Password = data[kPassword]
};
}
return new SqlConnectionProvider(builder.ConnectionString);
}
#endregion
}
}
``` |
37ba0eb8-9b63-4a52-a223-b6ad6d96b80b | {
"language": "C#"
} | ```c#
using System.Linq;
using NHibernate.Linq;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH3408
{
public class Fixture : BugTestCase
{
[Test]
public void ProjectAnonymousTypeWithArrayProperty()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query = from c in session.Query<Country>()
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
}
}
```
Add more tests for NH-3408 | ```c#
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH3408
{
public class Fixture : BugTestCase
{
[Test]
public void ProjectAnonymousTypeWithArrayProperty()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query = from c in session.Query<Country>()
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
[Test]
public void ProjectAnonymousTypeWithArrayPropertyWhenByteArrayContains()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var pictures = new List<byte[]>();
var query = from c in session.Query<Country>()
where pictures.Contains(c.Picture)
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
[Test]
public void SelectBytePropertyWithArrayPropertyWhenByteArrayContains()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var pictures = new List<byte[]>();
var query = from c in session.Query<Country>()
where pictures.Contains(c.Picture)
select c.Picture;
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
}
}
``` |
ca75c041-b02f-4c45-a3bb-a0da9bccb8dc | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Reflection;
using WampSharp.Core.Serialization;
using WampSharp.Core.Utilities;
namespace WampSharp.V2.Core
{
public class WampObjectFormatter : IWampFormatter<object>
{
public static readonly IWampFormatter<object> Value = new WampObjectFormatter();
private WampObjectFormatter()
{
}
public bool CanConvert(object argument, Type type)
{
return type.IsInstanceOfType(argument);
}
public TTarget Deserialize<TTarget>(object message)
{
return (TTarget) message;
}
public object Deserialize(Type type, object message)
{
MethodInfo genericMethod =
Method.Get((WampObjectFormatter x) => x.Deserialize<object>(default(object)))
.GetGenericMethodDefinition();
// This actually only throws an exception if types don't match.
object converted =
genericMethod.MakeGenericMethod(type)
.Invoke(this, new object[] {message});
return converted;
}
public object Serialize(object value)
{
return value;
}
}
}```
Call the reflection method only if types don't match | ```c#
using System;
using System.Linq;
using System.Reflection;
using WampSharp.Core.Serialization;
using WampSharp.Core.Utilities;
namespace WampSharp.V2.Core
{
public class WampObjectFormatter : IWampFormatter<object>
{
public static readonly IWampFormatter<object> Value = new WampObjectFormatter();
private readonly MethodInfo mSerializeMethod =
Method.Get((WampObjectFormatter x) => x.Deserialize<object>(default(object)))
.GetGenericMethodDefinition();
private WampObjectFormatter()
{
}
public bool CanConvert(object argument, Type type)
{
return type.IsInstanceOfType(argument);
}
public TTarget Deserialize<TTarget>(object message)
{
return (TTarget) message;
}
public object Deserialize(Type type, object message)
{
if (type.IsInstanceOfType(message))
{
return message;
}
else
{
// This throws an exception if types don't match.
object converted =
mSerializeMethod.MakeGenericMethod(type)
.Invoke(this, new object[] {message});
return converted;
}
}
public object Serialize(object value)
{
return value;
}
}
}``` |
f7567f1a-679d-49b2-a99f-1d4098b65f8d | {
"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.Audio;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
private readonly BindableDouble bonusSampleVolume = new BindableDouble();
private bool hasBonusPoints;
/// <summary>
/// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
/// Should be set when a spin occured after the spinner has completed.
/// </summary>
public bool HasBonusPoints
{
get => hasBonusPoints;
internal set
{
hasBonusPoints = value;
bonusSampleVolume.Value = value ? 1 : 0;
((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value;
}
}
public override bool DisplayResult => false;
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
Samples.AddAdjustment(AdjustableProperty.Volume, bonusSampleVolume);
}
public void TriggerResult(HitResult result) => ApplyResult(r => r.Type = result);
}
}
```
Set spinner tick start time to allow result reverting | ```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.Audio;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
private readonly BindableDouble bonusSampleVolume = new BindableDouble();
private bool hasBonusPoints;
/// <summary>
/// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
/// Should be set when a spin occured after the spinner has completed.
/// </summary>
public bool HasBonusPoints
{
get => hasBonusPoints;
internal set
{
hasBonusPoints = value;
bonusSampleVolume.Value = value ? 1 : 0;
((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value;
}
}
public override bool DisplayResult => false;
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
Samples.AddAdjustment(AdjustableProperty.Volume, bonusSampleVolume);
}
public void TriggerResult(HitResult result)
{
HitObject.StartTime = Time.Current;
ApplyResult(r => r.Type = result);
}
}
}
``` |
c01b8b05-721b-4a88-a1fb-ba6158ba2747 | {
"language": "C#"
} | ```c#
using Sakuno.Collections;
using System.Collections.ObjectModel;
using Xunit;
namespace Sakuno.Base.Tests
{
public static class ProjectionCollectionTests
{
[Fact]
public static void SimpleProjection()
{
var source = new ObservableCollection<int>();
var projection = new ProjectionCollection<int, int>(source, r => r * 2);
source.Add(1);
source.Add(2);
source.Add(3);
source.Add(4);
source.Add(5);
source.Remove(3);
source.Insert(1, 6);
source.Insert(2, 10);
source.Remove(5);
source.Remove(2);
Assert.Equal(projection.Count, source.Count);
using (var projectionEnumerator = projection.GetEnumerator())
using (var sourceEnumerator = source.GetEnumerator())
{
while (projectionEnumerator.MoveNext() && sourceEnumerator.MoveNext())
Assert.Equal(sourceEnumerator.Current * 2, projectionEnumerator.Current);
}
source.Clear();
Assert.Empty(projection);
projection.Dispose();
}
}
}
```
Make ProjectionCollection unit test more strict | ```c#
using Sakuno.Collections;
using System.Collections.ObjectModel;
using Xunit;
namespace Sakuno.Base.Tests
{
public static class ProjectionCollectionTests
{
[Fact]
public static void SimpleProjection()
{
var source = new ObservableCollection<int>();
var projection = new ProjectionCollection<int, int>(source, r => r * 2);
source.Add(1);
source.Add(2);
source.Add(3);
source.Add(4);
source.Add(5);
source.Remove(3);
source.Insert(1, 6);
source.Insert(2, 10);
source.Remove(5);
source.Remove(2);
Assert.Equal(projection.Count, source.Count);
using (var projectionEnumerator = projection.GetEnumerator())
using (var sourceEnumerator = source.GetEnumerator())
{
while (projectionEnumerator.MoveNext() && sourceEnumerator.MoveNext())
Assert.Equal(sourceEnumerator.Current * 2, projectionEnumerator.Current);
Assert.False(projectionEnumerator.MoveNext());
Assert.False(sourceEnumerator.MoveNext());
}
source.Clear();
Assert.Empty(projection);
projection.Dispose();
}
}
}
``` |
203414bd-37fa-4181-bdac-934b87fa2d59 | {
"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.Graphics;
using osu.Framework.Graphics.Containers;
using osuTK;
namespace osu.Game.Beatmaps.Drawables
{
/// <summary>
/// A difficulty icon which automatically calculates difficulty in the background.
/// </summary>
public class CalculatingDifficultyIcon : CompositeDrawable
{
/// <summary>
/// Size of this difficulty icon.
/// </summary>
public new Vector2 Size
{
get => difficultyIcon.Size;
set => difficultyIcon.Size = value;
}
public bool ShowTooltip
{
get => difficultyIcon.ShowTooltip;
set => difficultyIcon.ShowTooltip = value;
}
private readonly IBeatmapInfo beatmapInfo;
private readonly DifficultyIcon difficultyIcon;
/// <summary>
/// Creates a new <see cref="CalculatingDifficultyIcon"/> that follows the currently-selected ruleset and mods.
/// </summary>
/// <param name="beatmapInfo">The beatmap to show the difficulty of.</param>
public CalculatingDifficultyIcon(IBeatmapInfo beatmapInfo)
{
this.beatmapInfo = beatmapInfo ?? throw new ArgumentNullException(nameof(beatmapInfo));
AutoSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
difficultyIcon = new DifficultyIcon(beatmapInfo),
new DelayedLoadUnloadWrapper(createDifficultyRetriever, 0)
};
}
private Drawable createDifficultyRetriever() => new DifficultyRetriever(beatmapInfo) { StarDifficulty = { BindTarget = difficultyIcon.Current } };
}
}
```
Update retriever to be relatively sized | ```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.Graphics;
using osu.Framework.Graphics.Containers;
using osuTK;
namespace osu.Game.Beatmaps.Drawables
{
/// <summary>
/// A difficulty icon which automatically calculates difficulty in the background.
/// </summary>
public class CalculatingDifficultyIcon : CompositeDrawable
{
/// <summary>
/// Size of this difficulty icon.
/// </summary>
public new Vector2 Size
{
get => difficultyIcon.Size;
set => difficultyIcon.Size = value;
}
public bool ShowTooltip
{
get => difficultyIcon.ShowTooltip;
set => difficultyIcon.ShowTooltip = value;
}
private readonly DifficultyIcon difficultyIcon;
/// <summary>
/// Creates a new <see cref="CalculatingDifficultyIcon"/> that follows the currently-selected ruleset and mods.
/// </summary>
/// <param name="beatmapInfo">The beatmap to show the difficulty of.</param>
public CalculatingDifficultyIcon(IBeatmapInfo beatmapInfo)
{
AutoSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
difficultyIcon = new DifficultyIcon(beatmapInfo),
new DelayedLoadUnloadWrapper(() => new DifficultyRetriever(beatmapInfo) { StarDifficulty = { BindTarget = difficultyIcon.Current } }, 0)
{
RelativeSizeAxes = Axes.Both,
}
};
}
}
}
``` |
3d79d08d-e537-497c-b58e-7c6ad2d4fcc5 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinFormsExtendedSplashPage
{
public partial class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
Navigation.RemovePage(Navigation.NavigationStack[0]);
}
}
}
```
Fix bug when root page would be shown a second time. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinFormsExtendedSplashPage
{
public partial class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
var rootPage = Navigation.NavigationStack[0];
if (typeof (RootPage) == rootPage.GetType()) return;
Navigation.RemovePage(rootPage);
}
}
}
``` |
e5cbcd81-5b96-4d1c-ac92-8df060cf434f | {
"language": "C#"
} | ```c#
@model Unit
<div>@Html.ActionLink(Model.Name, "Index", "Soldiers", new { unit = Model.Id })</div>```
Make sure unit isn't null | ```c#
@model Unit
@if (Model != null)
{
<div>@Html.ActionLink(Model.Name, "Index", "Soldiers", new { unit = Model.Id })</div>
}``` |
3b4eae3f-2f0f-4f41-bcb8-a4b1b2f7c1c1 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
```
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
``` |
ca2d5d97-b94c-4b34-8f72-abe68a64deea | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio
{
public static class AggregatePackageSource
{
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source)
{
return source == Instance;
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate(this IPackageSourceProvider provider)
{
return new[] { Instance }.Concat(provider.GetEnabledPackageSources());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregateSmart(this IPackageSourceProvider provider)
{
var packageSources = provider.GetEnabledPackageSources().ToArray();
// If there's less than 2 package sources, don't add the Aggregate source because it will be exactly the same as the main source.
if (packageSources.Length <= 1)
{
return packageSources;
}
return new[] { Instance }.Concat(packageSources);
}
}
}```
Add back a method that was removed bug is required by functional tests. | ```c#
using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio
{
public static class AggregatePackageSource
{
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source)
{
return source == Instance;
}
// IMPORTANT: do NOT remove this method. It is used by functional tests.
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate()
{
return GetEnabledPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate(this IPackageSourceProvider provider)
{
return new[] { Instance }.Concat(provider.GetEnabledPackageSources());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregateSmart(this IPackageSourceProvider provider)
{
var packageSources = provider.GetEnabledPackageSources().ToArray();
// If there's less than 2 package sources, don't add the Aggregate source because it will be exactly the same as the main source.
if (packageSources.Length <= 1)
{
return packageSources;
}
return new[] { Instance }.Concat(packageSources);
}
}
}``` |
5e0df7d9-af7a-47ba-aed4-9d4d364662f4 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.Serialization;
using SadConsole.UI.Controls;
using SadRogue.Primitives;
namespace SadConsole.UI.Themes
{
/// <summary>
/// A basic theme for a drawing surface that simply fills the surface based on the state.
/// </summary>
[DataContract]
public class DrawingAreaTheme : ThemeBase
{
/// <summary>
/// When true, only uses <see cref="ThemeStates.Normal"/> for drawing.
/// </summary>
[DataMember]
public bool UseNormalStateOnly { get; set; } = true;
/// <summary>
/// The current appearance based on the control state.
/// </summary>
public ColoredGlyph Appearance { get; protected set; }
/// <inheritdoc />
public override void UpdateAndDraw(ControlBase control, TimeSpan time)
{
if (!(control is DrawingArea drawingSurface)) return;
RefreshTheme(control.FindThemeColors(), control);
if (!UseNormalStateOnly)
Appearance = ControlThemeState.GetStateAppearance(control.State);
else
Appearance = ControlThemeState.Normal;
drawingSurface?.OnDraw(drawingSurface, time);
control.IsDirty = false;
}
/// <inheritdoc />
public override ThemeBase Clone() => new DrawingAreaTheme()
{
ControlThemeState = ControlThemeState.Clone(),
UseNormalStateOnly = UseNormalStateOnly
};
}
}
```
Fix bug in DrawArea control | ```c#
using System;
using System.Runtime.Serialization;
using SadConsole.UI.Controls;
using SadRogue.Primitives;
namespace SadConsole.UI.Themes
{
/// <summary>
/// A basic theme for a drawing surface that simply fills the surface based on the state.
/// </summary>
[DataContract]
public class DrawingAreaTheme : ThemeBase
{
/// <summary>
/// When true, only uses <see cref="ThemeStates.Normal"/> for drawing.
/// </summary>
[DataMember]
public bool UseNormalStateOnly { get; set; } = true;
/// <summary>
/// The current appearance based on the control state.
/// </summary>
public ColoredGlyph Appearance { get; protected set; }
/// <inheritdoc />
public override void UpdateAndDraw(ControlBase control, TimeSpan time)
{
if (!(control is DrawingArea drawingSurface)) return;
RefreshTheme(control.FindThemeColors(), control);
if (!UseNormalStateOnly)
Appearance = ControlThemeState.GetStateAppearance(control.State);
else
Appearance = ControlThemeState.Normal;
drawingSurface.OnDraw?.Invoke(drawingSurface, time);
control.IsDirty = false;
}
/// <inheritdoc />
public override ThemeBase Clone() => new DrawingAreaTheme()
{
ControlThemeState = ControlThemeState.Clone(),
UseNormalStateOnly = UseNormalStateOnly
};
}
}
``` |
69a619ac-f52a-4148-a4d2-611a1f2b7b8b | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Xmp;
using TagLib.Tests.Images.Validators;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegNoMetadataTest
{
[Test]
public void Test ()
{
ImageTest.Run ("sample_no_metadata.jpg",
new JpegNoMetadataTestInvariantValidator (),
NoModificationValidator.Instance,
new NoModificationValidator (),
new CommentModificationValidator (),
new TagCommentModificationValidator (TagTypes.TiffIFD, false),
new TagCommentModificationValidator (TagTypes.XMP, false),
new TagKeywordsModificationValidator (TagTypes.XMP, false)
);
}
}
public class JpegNoMetadataTestInvariantValidator : IMetadataInvariantValidator
{
public void ValidateMetadataInvariants (Image.File file)
{
Assert.IsNotNull (file);
}
}
}
```
Remove CommentTest for jpeg test without metadata | ```c#
using System;
using NUnit.Framework;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Xmp;
using TagLib.Tests.Images.Validators;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegNoMetadataTest
{
[Test]
public void Test ()
{
ImageTest.Run ("sample_no_metadata.jpg",
new JpegNoMetadataTestInvariantValidator (),
NoModificationValidator.Instance,
new NoModificationValidator (),
new TagCommentModificationValidator (TagTypes.TiffIFD, false),
new TagCommentModificationValidator (TagTypes.XMP, false),
new TagKeywordsModificationValidator (TagTypes.XMP, false)
);
}
}
public class JpegNoMetadataTestInvariantValidator : IMetadataInvariantValidator
{
public void ValidateMetadataInvariants (Image.File file)
{
Assert.IsNotNull (file);
}
}
}
``` |
f492abf2-3b9a-48b9-a211-92e6b2488d02 | {
"language": "C#"
} | ```c#
using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class SizeOptions : PerfStressOptions
{
[Option('s', "size", Default = 10 * 1024, HelpText = "Size of message (in bytes)")]
public int Size { get; set; }
}
}
```
Convert size parameter from int to long | ```c#
using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class SizeOptions : PerfStressOptions
{
[Option('s', "size", Default = 10 * 1024, HelpText = "Size of message (in bytes)")]
public long Size { get; set; }
}
}
``` |
4bbb8c08-c5fb-479e-bc0c-b62c4852f73a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using Agiil.Web.Services.DataPackages;
using Autofac;
using Agiil.Web.Services;
namespace Agiil.Web.Bootstrap
{
public class DataPackagesModule : Autofac.Module
{
static readonly Type
NamespaceMarker = typeof(IDataPackagesNamespaceMarker),
DataPackageInterface = typeof(IDataPackage);
string DataPackagesNamespace => NamespaceMarker.Namespace;
protected override void Load(ContainerBuilder builder)
{
var packageTypes = GetDataPackageTypes();
foreach(var packageType in packageTypes)
{
builder
.RegisterType(packageType)
.WithMetadata<DataPackageMetadata>(config => {
config.For(x => x.PackageTypeName, packageType.Name);
});
}
}
IEnumerable<Type> GetDataPackageTypes()
{
return (from type in Assembly.GetExecutingAssembly().GetExportedTypes()
where
type.IsClass
&& !type.IsAbstract
&& DataPackageInterface.IsAssignableFrom(type)
&& type.Namespace == DataPackagesNamespace
select type)
.ToArray();
}
}
}
```
Fix registration of Data Packages | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using Agiil.Web.Services.DataPackages;
using Autofac;
using Agiil.Web.Services;
namespace Agiil.Web.Bootstrap
{
public class DataPackagesModule : Autofac.Module
{
static readonly Type
NamespaceMarker = typeof(IDataPackagesNamespaceMarker),
DataPackageInterface = typeof(IDataPackage);
string DataPackagesNamespace => NamespaceMarker.Namespace;
protected override void Load(ContainerBuilder builder)
{
var packageTypes = GetDataPackageTypes();
foreach(var packageType in packageTypes)
{
builder
.RegisterType(packageType)
.As<IDataPackage>()
.WithMetadata<DataPackageMetadata>(config => {
config.For(x => x.PackageTypeName, packageType.Name);
});
}
}
IEnumerable<Type> GetDataPackageTypes()
{
return (from type in Assembly.GetExecutingAssembly().GetExportedTypes()
where
type.IsClass
&& !type.IsAbstract
&& DataPackageInterface.IsAssignableFrom(type)
&& type.Namespace == DataPackagesNamespace
select type)
.ToArray();
}
}
}
``` |
9ecf5492-0b1a-4c13-8e03-3d838cedd2a0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
public static string RoleProvider { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
RoleProvider = ConfigurationManager.AppSettings["RoleProvider"];
}
}
}```
Remove unused RoleProvider setting from authentication configuration | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
}
}
}``` |
b8f78bb6-c7ca-4604-a6bf-fe4ef4e72710 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}\t{2}", p.ProcessName, p.Id, p.TotalProcessorTime));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
```
Fix access denied issue when access process information in RemoteProcessService | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
``` |
46931df7-5b01-4fa7-bd83-2f702498462a | {
"language": "C#"
} | ```c#
namespace GeneratorAPI {
/// <summary>
/// Represents a generic generator which can generate any ammount of elements.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> : IGenerator {
/// <summary>
/// Generate next element.
/// </summary>
T Generate();
}
public interface IGenerator {
object Generate();
}
}```
Add new keyword for hiding the none generic generate | ```c#
namespace GeneratorAPI {
/// <summary>
/// Represents a generic generator which can generate any ammount of elements.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> : IGenerator {
/// <summary>
/// Generate next element.
/// </summary>
new T Generate();
}
public interface IGenerator {
object Generate();
}
}``` |
dba5826c-d9d2-4925-b558-38471c0f8ad2 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using GPSTracker.Common;
using GPSTracker.GrainInterface;
namespace GPSTracker.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Test()
{
var rand = new Random();
var grain = DeviceGrainFactory.GetGrain(1);
await grain.ProcessMessage(new DeviceMessage(rand.Next(-90, 90), rand.Next(-180, 180), 1, 1, DateTime.UtcNow));
return Content("Sent");
}
}
}
```
Fix code using old style code-gen factory classes - use GrainClient.GrainFactory | ```c#
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using GPSTracker.Common;
using GPSTracker.GrainInterface;
using Orleans;
namespace GPSTracker.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Test()
{
var rand = new Random();
IDeviceGrain grain = GrainClient.GrainFactory.GetGrain<IDeviceGrain>(1);
await grain.ProcessMessage(new DeviceMessage(rand.Next(-90, 90), rand.Next(-180, 180), 1, 1, DateTime.UtcNow));
return Content("Sent");
}
}
}
``` |
60adcd12-ce72-4c96-9a84-f466cb65052c | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DomainServices")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DomainServices")]
``` |
f196ee4f-38a7-4ee4-b5cc-1e0fcab65ac3 | {
"language": "C#"
} | ```c#
using UnityEngine;
using MsgPack;
[RequireComponent(typeof (AgentController))]
[RequireComponent(typeof (AgentSensor))]
public class AgentBehaviour : MonoBehaviour {
private LISClient client = new LISClient("myagent");
private AgentController controller;
private AgentSensor sensor;
private MsgPack.CompiledPacker packer = new MsgPack.CompiledPacker();
bool created = false;
public float Reward = 0.0F;
void OnCollisionEnter(Collision col) {
if(col.gameObject.tag == "Reward") {
NotificationCenter.DefaultCenter.PostNotification(this, "OnRewardCollision");
}
}
byte[] GenerateMessage() {
Message msg = new Message();
msg.reward = PlayerPrefs.GetFloat("Reward");
msg.image = sensor.GetRgbImages();
msg.depth = sensor.GetDepthImages();
return packer.Pack(msg);
}
void Start () {
controller = GetComponent<AgentController>();
sensor = GetComponent<AgentSensor>();
}
void Update () {
if(!created) {
client.Create(GenerateMessage());
created = true;
} else {
if(!client.Calling) {
client.Step(GenerateMessage());
}
if(client.HasAction) {
string action = client.GetAction();
controller.PerformAction(action);
}
}
}
}
```
Fix behaviour from calling create multiple times | ```c#
using UnityEngine;
using MsgPack;
[RequireComponent(typeof (AgentController))]
[RequireComponent(typeof (AgentSensor))]
public class AgentBehaviour : MonoBehaviour {
private LISClient client = new LISClient("myagent");
private AgentController controller;
private AgentSensor sensor;
private MsgPack.CompiledPacker packer = new MsgPack.CompiledPacker();
bool created = false;
public float Reward = 0.0F;
void OnCollisionEnter(Collision col) {
if(col.gameObject.tag == "Reward") {
NotificationCenter.DefaultCenter.PostNotification(this, "OnRewardCollision");
}
}
byte[] GenerateMessage() {
Message msg = new Message();
msg.reward = PlayerPrefs.GetFloat("Reward");
msg.image = sensor.GetRgbImages();
msg.depth = sensor.GetDepthImages();
return packer.Pack(msg);
}
void Start () {
controller = GetComponent<AgentController>();
sensor = GetComponent<AgentSensor>();
}
void Update () {
if(!created) {
if(!client.Calling) {
client.Create(GenerateMessage());
created = true;
}
} else {
if(!client.Calling) {
client.Step(GenerateMessage());
}
if(client.HasAction) {
string action = client.GetAction();
controller.PerformAction(action);
}
}
}
}
``` |
c5325f37-67ae-4c39-a962-0c8701e5a3bb | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit, CatchJudgement>
{
public CatchScoreProcessor()
{
}
public CatchScoreProcessor(HitRenderer<CatchBaseHit, CatchJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void OnNewJudgement(CatchJudgement judgement)
{
}
}
}
```
Fix failing at beginning of map | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit, CatchJudgement>
{
public CatchScoreProcessor()
{
}
public CatchScoreProcessor(HitRenderer<CatchBaseHit, CatchJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(CatchJudgement judgement)
{
}
}
}
``` |
52ad96de-674c-4912-8a60-6d57d12fe62b | {
"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.
using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
// These are error codes we get back from the Normalization DLL
internal const int ERROR_SUCCESS = 0;
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_INVALID_PARAMETER = 87;
internal const int ERROR_INSUFFICIENT_BUFFER = 122;
internal const int ERROR_INVALID_NAME = 123;
internal const int ERROR_NO_UNICODE_TRANSLATION = 1113;
// The VM can override the last error code with this value in debug builds
// so this value for us is equivalent to ERROR_SUCCESS
internal const int LAST_ERROR_TRASH_VALUE = 42424;
internal partial class mincore
{
//
// Normalization APIs
//
[DllImport("api-ms-win-core-normalization-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool IsNormalizedString(int normForm, string source, int length);
[DllImport("api-ms-win-core-normalization-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int NormalizeString(
int normForm,
string source,
int sourceLength,
[System.Runtime.InteropServices.OutAttribute()]
char[] destenation,
int destenationLength);
}
}
```
Fix typos in NormalizeString P/Invoke signature | ```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.
using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
// These are error codes we get back from the Normalization DLL
internal const int ERROR_SUCCESS = 0;
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_INVALID_PARAMETER = 87;
internal const int ERROR_INSUFFICIENT_BUFFER = 122;
internal const int ERROR_INVALID_NAME = 123;
internal const int ERROR_NO_UNICODE_TRANSLATION = 1113;
// The VM can override the last error code with this value in debug builds
// so this value for us is equivalent to ERROR_SUCCESS
internal const int LAST_ERROR_TRASH_VALUE = 42424;
internal partial class mincore
{
//
// Normalization APIs
//
[DllImport("api-ms-win-core-normalization-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool IsNormalizedString(int normForm, string source, int length);
[DllImport("api-ms-win-core-normalization-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int NormalizeString(
int normForm,
string source,
int sourceLength,
[System.Runtime.InteropServices.OutAttribute()]
char[] destination,
int destinationLength);
}
}
``` |
9e163c38-a0f6-4e63-ac77-bc742b75e113 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace Arkivverket.Arkade.CLI.Options
{
[Verb("generate", HelpText = "Generate a specified file. Run this command followed by '--help' for more detailed info.")]
public class GenerateOptions : OutputOptions
{
[Option('m', "metadata-example", Group = "file-type",
HelpText = "Generate json file with example metadata.")]
public bool GenerateMetadataExampleFile { get; set; }
[Option('s', "noark5-test-selection", Group = "file-type",
HelpText = "Generate text file with list of noark5 tests.")]
public bool GenerateNoark5TestSelectionFile { get; set; }
[Usage(ApplicationAlias = "arkade")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Generate json file with metadata example",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true
});
yield return new Example("Generate text file with list of noark5-test",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateNoark5TestSelectionFile = true
});
yield return new Example("Generate both files",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true,
GenerateNoark5TestSelectionFile = true
});
}
}
}
}
```
Improve help texts for CLI file generation | ```c#
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace Arkivverket.Arkade.CLI.Options
{
[Verb("generate", HelpText = "Generate a specified file. Run this command followed by '--help' for more detailed info.")]
public class GenerateOptions : OutputOptions
{
[Option('m', "metadata-example", Group = "file-type",
HelpText = "Generate a metadata example file.")]
public bool GenerateMetadataExampleFile { get; set; }
[Option('s', "noark5-test-selection", Group = "file-type",
HelpText = "Generate a Noark 5 test selection file.")]
public bool GenerateNoark5TestSelectionFile { get; set; }
[Usage(ApplicationAlias = "arkade")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Generate a metadata example file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true
});
yield return new Example("Generate a Noark 5 test selection file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateNoark5TestSelectionFile = true
});
yield return new Example("Generate a metadata example file and a Noark 5 test selection file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true,
GenerateNoark5TestSelectionFile = true
});
}
}
}
}
``` |
265f2b69-e4ac-46a2-a3ce-2a9b4d297ffb | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "AvantiPoint, LLC" )]
[assembly: AssemblyCopyright( "Copyright © Dan Siegel 2016" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "1.1.0.0" )]
[assembly: AssemblyFileVersion( "1.1.0.0" )]
[assembly: AssemblyInformationalVersion( "1.1.0-pre1" )]```
Update Informational Version to 1.1.0-pre2 | ```c#
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "AvantiPoint, LLC" )]
[assembly: AssemblyCopyright( "Copyright © Dan Siegel 2016" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "1.1.0.0" )]
[assembly: AssemblyFileVersion( "1.1.0.0" )]
[assembly: AssemblyInformationalVersion( "1.1.0-pre2" )]``` |
778e6716-15b8-47b8-9a85-14b6f367c298 | {
"language": "C#"
} | ```c#
using System.Windows.Controls;
using System.Windows.Forms;
namespace food_tracker {
public class FoodBoxItem : ListBoxItem {
public int calories { get; set; }
public int fats { get; set; }
public int saturatedFat { get; set; }
public int carbohydrates { get; set; }
public int sugar { get; set; }
public int protein { get; set; }
public int salt { get; set; }
public string name { get; set; }
public FoodBoxItem() : base() { }
public FoodBoxItem(int cals, int fats, int satFat, int carbs, int sugars, int protein, int salt, string name) {
this.name = name;
this.calories = cals;
this.fats = fats;
this.salt = salt;
this.saturatedFat = satFat;
this.carbohydrates = carbs;
this.sugar = sugars;
this.protein = protein;
}
public override string ToString() {
return name;
}
}
}
```
Update food box item with fibre | ```c#
using System.Windows.Controls;
using System.Windows.Forms;
namespace food_tracker {
public class FoodBoxItem : ListBoxItem {
public int calories { get; set; }
public int fats { get; set; }
public int saturatedFat { get; set; }
public int carbohydrates { get; set; }
public int sugar { get; set; }
public int protein { get; set; }
public int salt { get; set; }
public int fibre { get; set; }
public string name { get; set; }
public FoodBoxItem() : base() { }
public FoodBoxItem(int cals, int fats, int satFat, int carbs, int sugars, int protein, int salt, int fibre, string name) {
this.name = name;
this.calories = cals;
this.fats = fats;
this.salt = salt;
this.saturatedFat = satFat;
this.carbohydrates = carbs;
this.sugar = sugars;
this.protein = protein;
this.fibre = fibre;
}
public override string ToString() {
return name;
}
}
}
``` |
4699f8b6-f9ab-4fae-a506-ddda489693c1 | {
"language": "C#"
} | ```c#
using System;
// ReSharper disable InconsistentNaming
namespace Ductus.FluentDocker.Model.Containers
{
public sealed class ContainerState
{
public string Status { get; set; }
public bool Running { get; set; }
public bool Paused { get; set; }
public bool Restarting { get; set; }
public bool OOMKilled { get; set; }
public bool Dead { get; set; }
public int Pid { get; set; }
public int ExitCode { get; set; }
public string Error { get; set; }
public DateTime StartedAt { get; set; }
public DateTime FinishedAt { get; set; }
public Health Health { get; set; }
}
}```
Update ExitCode to long. This is because Windows Containers sometimes exit with 3221225725 | ```c#
using System;
// ReSharper disable InconsistentNaming
namespace Ductus.FluentDocker.Model.Containers
{
public sealed class ContainerState
{
public string Status { get; set; }
public bool Running { get; set; }
public bool Paused { get; set; }
public bool Restarting { get; set; }
public bool OOMKilled { get; set; }
public bool Dead { get; set; }
public int Pid { get; set; }
public long ExitCode { get; set; }
public string Error { get; set; }
public DateTime StartedAt { get; set; }
public DateTime FinishedAt { get; set; }
public Health Health { get; set; }
}
}``` |
83f111c6-67a5-4e31-9467-e6412e5fbcf7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.ViewModels
{
public abstract class WasabiWalletDocumentTabViewModel : WasabiDocumentTabViewModel
{
protected WasabiWalletDocumentTabViewModel(string title, WalletViewModelBase walletViewModel)
: base(title)
{
WalletViewModel = walletViewModel;
}
public WalletViewModelBase WalletViewModel { get; }
public Wallet Wallet => WalletViewModel.Wallet;
}
}
```
Make WalletViewModel private and WalletViewModelBase protected. | ```c#
using ReactiveUI;
using Splat;
using System;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.ViewModels
{
public abstract class WasabiWalletDocumentTabViewModel : WasabiDocumentTabViewModel
{
protected WasabiWalletDocumentTabViewModel(string title, WalletViewModelBase walletViewModel)
: base(title)
{
WalletViewModel = walletViewModel;
}
public void ExpandWallet ()
{
WalletViewModel.IsExpanded = true;
}
private WalletViewModelBase WalletViewModel { get; }
protected Wallet Wallet => WalletViewModel.Wallet;
}
}
``` |
a6a6691d-b472-4e81-bf7e-15a15f209068 | {
"language": "C#"
} | ```c#
using System;
namespace Microsoft.TeamFoundation.Authentication
{
public interface ITokenStore
{
/// <summary>
/// Deletes a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token is being deleted.</param>
void DeleteToken(Uri targetUri);
/// <summary>
/// Reads a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token to read.</param>
/// <param name="token">A <see cref="Token"/> if successful; otherwise false.</param>
/// <returns>True if successful; otherwise false.</returns>
bool ReadToken(Uri targetUri, out Token token);
/// <summary>
/// Writes a <see cref="Token"/> to the underlying storage.
/// </summary>
/// <param name="targetUri">
/// Unique identifier for the token, used when reading back from storage.
/// </param>
/// <param name="token">The <see cref="Token"/> to writen.</param>
void WriteToken(Uri targetUri, Token token);
}
}
```
Fix typo and use <see langword=""/>. | ```c#
using System;
namespace Microsoft.TeamFoundation.Authentication
{
public interface ITokenStore
{
/// <summary>
/// Deletes a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token is being deleted.</param>
void DeleteToken(Uri targetUri);
/// <summary>
/// Reads a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token to read.</param>
/// <param name="token">A <see cref="Token"/> if successful; otherwise <see langword="null"/>.</param>
/// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
bool ReadToken(Uri targetUri, out Token token);
/// <summary>
/// Writes a <see cref="Token"/> to the underlying storage.
/// </summary>
/// <param name="targetUri">
/// Unique identifier for the token, used when reading back from storage.
/// </param>
/// <param name="token">The <see cref="Token"/> to be written.</param>
void WriteToken(Uri targetUri, Token token);
}
}
``` |
935385ff-16c9-4855-9ff4-8b2e697da19c | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Reporting API - Introduction";
}
<article class="article">
<h1>Introduction to the Reporting API</h1>
<p>
The Reporting API is based on standard web technologies, web services and XML.
Use the Reporting API to extract from TimeLog into intranets, extranets,
business reporting tools, applications etc.
</p>
<p>
The idea behind the Reporting API is to give access to as much of the TimeLog
Project data models as possible in a easy to use XML format. The origin of the
API goes way back in the history of TimeLog, so we will extend on it on
a per-request basis for new fields and data types. Please get in touch, if you
think we lack some information in the various methods.
</p>
<p>
Be aware that no security policies on user access will be applied to any of the
methods in the Reporting API. The Reporting API is for flat data extractions.
Take care to apply your own policies if you are exposing the data in a data
warehouse or other business intelligence tools.
</p>
</article>```
Add information about http status codes in the reporting API | ```c#
@{
ViewBag.Title = "Reporting API - Introduction";
}
<article class="article">
<h1>Introduction to the Reporting API</h1>
<p>
The Reporting API is based on standard web technologies, web services and XML.
Use the Reporting API to extract from TimeLog into intranets, extranets,
business reporting tools, applications etc.
</p>
<p>
The idea behind the Reporting API is to give access to as much of the TimeLog
Project data models as possible in a easy to use XML format. The origin of the
API goes way back in the history of TimeLog, so we will extend on it on
a per-request basis for new fields and data types. Please get in touch, if you
think we lack some information in the various methods.
</p>
<p>
Be aware that no security policies on user access will be applied to any of the
methods in the Reporting API. The Reporting API is for flat data extractions.
Take care to apply your own policies if you are exposing the data in a data
warehouse or other business intelligence tools.
</p>
<h2 id="status-codes">Status codes</h2>
<p>
The reporting will (starting from end May 2021) return specific HTTP
status codes related to the result. The result body will remain unchanged and will
in many cases provide additional information. Possible status responses:
</p>
<ul class="arrows">
<li>200 OK - request successful</li>
<li>204 No Content - the result of the request is empty</li>
<li>400 Bad Request - covers both issues with input parameters, but possibly also internal errors</li>
<li>401 Unauthorized - the Site ID, API ID and API password combination is invalid</li>
</ul>
</article>``` |
0d0d9163-79c9-4fb9-bcaf-29c3f8bd1d49 | {
"language": "C#"
} | ```c#
using System.Net;
namespace LtiLibrary.NetCore.Profiles
{
public class ToolConsumerProfileResponse
{
public HttpStatusCode StatusCode { get; set; }
public ToolConsumerProfile ToolConsumerProfile { get; set; }
}
}
```
Add ContentType of the response. | ```c#
using System.Net;
namespace LtiLibrary.NetCore.Profiles
{
public class ToolConsumerProfileResponse
{
public string ContentType { get; set; }
public HttpStatusCode StatusCode { get; set; }
public ToolConsumerProfile ToolConsumerProfile { get; set; }
}
}
``` |
885d069a-75a5-42f1-af72-688f98e588a1 | {
"language": "C#"
} | ```c#
namespace VSYard.BraceMatching
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using System.Linq;
using System.Windows.Media;
[Export(typeof(EditorFormatDefinition))]
[Name("green")]
[UserVisible(true)]
internal class HighlightFormatDefinition1 : MarkerFormatDefinition
{
public HighlightFormatDefinition1()
{
this.BackgroundColor = Colors.Aquamarine;
this.ForegroundColor = Colors.Teal;
this.DisplayName = "green element!";
this.ZOrder = 5;
}
}
[Export(typeof(IViewTaggerProvider))]
[ContentType("yardtype")]
[TagType(typeof(TextMarkerTag))]
internal class BraceMatchingTaggerProvider : IViewTaggerProvider
{
public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag
{
if (textView == null)
return null;
//provide highlighting only on the top-level buffer
if (textView.TextBuffer != buffer)
return null;
return new VSYardNS.BraceMatchingTagger(textView, buffer) as ITagger<T>;
}
}
}
```
Add example of getting root YRD file. | ```c#
namespace VSYard.BraceMatching
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using System.Linq;
using System.Windows.Media;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
[Export(typeof(EditorFormatDefinition))]
[Name("green")]
[UserVisible(true)]
internal class HighlightFormatDefinition1 : MarkerFormatDefinition
{
public HighlightFormatDefinition1()
{
this.BackgroundColor = Colors.Aquamarine;
this.ForegroundColor = Colors.Teal;
this.DisplayName = "green element!";
this.ZOrder = 5;
}
}
[Export(typeof(IViewTaggerProvider))]
[ContentType("yardtype")]
[TagType(typeof(TextMarkerTag))]
internal class BraceMatchingTaggerProvider : IViewTaggerProvider
{
public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag
{
//It is exampe of getting root *.yrd file of active project.
//Should be removed
var t = MyCompany.VSYard.Helpers.SolutionNavigatorHelper.GetRootYrd
(MyCompany.VSYard.Helpers.SolutionNavigatorHelper.GetActiveProject());
if (textView == null)
return null;
//provide highlighting only on the top-level buffer
if (textView.TextBuffer != buffer)
return null;
return new VSYardNS.BraceMatchingTagger(textView, buffer) as ITagger<T>;
}
}
}
``` |
5e7d4c5b-1c2b-4658-a1e0-a666e40b1987 | {
"language": "C#"
} | ```c#
using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
}
}
```
Add fix for missing method on interface | ```c#
using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
/// <summary>
/// execute 'yarn version' with options
/// </summary>
/// <param name="versionSettings">options when running 'yarn version'</param>
IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);
}
}
``` |
7ddec124-8d35-4301-9d39-6c9ac0a91259 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Threading.Tasks;
namespace Ylp.GitDb.Core
{
public interface ILogger
{
Task Log(string message);
}
public class Logger : ILogger
{
public readonly string FileName;
public Logger(string fileName)
{
FileName = fileName;
}
public Task Log(string message)
{
File.AppendAllText(FileName, $"{DateTime.Now.ToString("HH:mm:ss")}: {message}\n");
return Task.CompletedTask;
}
}
}```
Make sure logging doesn't cause cross-thread access to the log-file | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace Ylp.GitDb.Core
{
public interface ILogger
{
Task Log(string message);
}
public class Logger : ILogger
{
public readonly string FileName;
static readonly object LockObj = new object();
public Logger(string fileName)
{
FileName = fileName;
}
public Task Log(string message)
{
lock(LockObj)
File.AppendAllText(FileName, $"{DateTime.Now.ToString("HH:mm:ss")}: {message}\n");
return Task.CompletedTask;
}
}
}``` |
b9c79d96-0819-4627-8621-fd177ed4db23 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Tool : Bond Compiler 0.4.1.0
// File : ExceptionDetails_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External
{
using System.Collections.Concurrent;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.4.1.0")]
internal partial class ExceptionDetails
{
public int id { get; set; }
public int outerId { get; set; }
public string typeName { get; set; }
public string message { get; set; }
public bool hasFullStack { get; set; }
public string stack { get; set; }
public IList<StackFrame> parsedStack { get; set; }
public ExceptionDetails()
: this("AI.ExceptionDetails", "ExceptionDetails")
{ }
protected ExceptionDetails(string fullName, string name)
{
typeName = "";
message = "";
hasFullStack = true;
stack = "";
parsedStack = new List<StackFrame>();
}
}
} // AI
```
Revert the whitespace change of the auto generated file | ```c#
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Tool : Bond Compiler 0.4.1.0
// File : ExceptionDetails_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External
{
using System.Collections.Concurrent;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.4.1.0")]
internal partial class ExceptionDetails
{
public int id { get; set; }
public int outerId { get; set; }
public string typeName { get; set; }
public string message { get; set; }
public bool hasFullStack { get; set; }
public string stack { get; set; }
public IList<StackFrame> parsedStack { get; set; }
public ExceptionDetails()
: this("AI.ExceptionDetails", "ExceptionDetails")
{}
protected ExceptionDetails(string fullName, string name)
{
typeName = "";
message = "";
hasFullStack = true;
stack = "";
parsedStack = new List<StackFrame>();
}
}
} // AI
``` |
81b33f2c-811a-4775-babf-0a8fa8966d5b | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Qowaiv.UnitTests.TestTools
{
public static class DebuggerDisplayAssert
{
public static void HasAttribute(Type type)
{
Assert.IsNotNull(type, "The supplied type should not be null.");
var act = (DebuggerDisplayAttribute)type.GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).FirstOrDefault();
Assert.IsNotNull(act, "The type '{0}' has no DebuggerDisplay attribute.", type);
Assert.AreEqual("{DebuggerDisplay}", act.Value, "DebuggerDisplay attribute value is not '{DebuggerDisplay}'.");
}
public static void HasResult(string expected, object value)
{
Assert.IsNotNull(value, "The supplied value should not be null.");
var type = value.GetType();
var prop = type.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(prop, "The type '{0}' does not contain a non-public property DebuggerDisplay.", type);
var actual = prop.GetValue(value);
Assert.AreEqual(expected, actual);
}
}
}
```
Support all objects for debugger display. | ```c#
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Qowaiv.UnitTests.TestTools
{
public static class DebuggerDisplayAssert
{
public static void HasAttribute(Type type)
{
Assert.IsNotNull(type, "The supplied type should not be null.");
var act = (DebuggerDisplayAttribute)type.GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).FirstOrDefault();
Assert.IsNotNull(act, "The type '{0}' has no DebuggerDisplay attribute.", type);
Assert.AreEqual("{DebuggerDisplay}", act.Value, "DebuggerDisplay attribute value is not '{DebuggerDisplay}'.");
}
public static void HasResult(object expected, object value)
{
Assert.IsNotNull(value, "The supplied value should not be null.");
var type = value.GetType();
var prop = type.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(prop, "The type '{0}' does not contain a non-public property DebuggerDisplay.", type);
var actual = prop.GetValue(value);
Assert.AreEqual(expected, actual);
}
}
}
``` |
f7907317-73f1-4b90-9e8a-a231e8806833 | {
"language": "C#"
} | ```c#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.LayoutRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.LayoutRules.SA1514ElementDocumentationHeaderMustBePrecededByBlankLine,
StyleCop.Analyzers.LayoutRules.SA1514CodeFixProvider>;
public class SA1514CSharp8UnitTests : SA1514CSharp7UnitTests
{
/// <summary>
/// Verifies that method-like declarations with invalid documentation will produce the expected diagnostics.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidPropertyDeclarationAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
/// <summary>
/// Gets or sets the value.
/// </summary>
public string SomeString { get; set; } = null!;
/// <summary>
/// Gets or sets the value.
/// </summary>
public string AnotherString { get; set; } = null!;
}
}
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
```
Clean up test and reference original issue | ```c#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.LayoutRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.LayoutRules.SA1514ElementDocumentationHeaderMustBePrecededByBlankLine,
StyleCop.Analyzers.LayoutRules.SA1514CodeFixProvider>;
public class SA1514CSharp8UnitTests : SA1514CSharp7UnitTests
{
[Fact]
[WorkItem(3067, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3067")]
public async Task TestValidPropertyDeclarationAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
/// <summary>
/// Gets or sets the value.
/// </summary>
public string SomeString { get; set; } = null!;
/// <summary>
/// Gets or sets the value.
/// </summary>
public string AnotherString { get; set; } = null!;
}
}
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
``` |
a2fe2e9a-4df6-45e5-a9d5-21fb0efef8a9 | {
"language": "C#"
} | ```c#
using System;
using Marten.Testing.Harness;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_673_multiple_version_assertions: IntegrationContext
{
[Fact]
public void replaces_the_max_version_assertion()
{
var streamId = Guid.NewGuid();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
public Bug_673_multiple_version_assertions(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class WhateverEvent
{
}
}
```
Add failing test for append called several times for string identity | ```c#
using System;
using Marten.Events;
using Marten.Testing.Harness;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_673_multiple_version_assertions: IntegrationContext
{
[Fact]
public void replaces_the_max_version_assertion()
{
var streamId = Guid.NewGuid();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
[Fact]
public void replaces_the_max_version_assertion_for_string_identity()
{
UseStreamIdentity(StreamIdentity.AsString);
var streamId = Guid.NewGuid().ToString();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
public Bug_673_multiple_version_assertions(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class WhateverEvent
{
}
}
``` |
0e871456-a85c-4749-8694-66b7db0f795d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Authoring.CodeActions
{
public abstract class CodeRefactoringProvider<T> : ICodeRefactoringProvider
where T : SyntaxNode
{
public IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var syntaxToken = syntaxTree.Root.FindToken(position);
var synaxNodes = syntaxToken.Parent.AncestorsAndSelf().OfType<T>();
return synaxNodes.SelectMany(n => GetRefactorings(semanticModel, position, n));
}
protected abstract IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position, T node);
}
}```
Fix refactoring provider to correctly handle positions near EOF | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Authoring.CodeActions
{
public abstract class CodeRefactoringProvider<T> : ICodeRefactoringProvider
where T : SyntaxNode
{
public IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
return from t in syntaxTree.Root.FindStartTokens(position)
from n in t.Parent.AncestorsAndSelf().OfType<T>()
from r in GetRefactorings(semanticModel, position, n)
select r;
}
protected abstract IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position, T node);
}
}``` |
d29381e0-0c13-46c0-b0e5-98de14dd11de | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public bool RegEx { get; set; }
}
}```
Fix deserialization of RegEx enabled properties | ```c#
using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public string RegEx { get; set; }
}
}``` |
7883adc9-c035-492c-9a90-b505d7681d11 | {
"language": "C#"
} | ```c#
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using Topppro.WebSite.Areas.Humanist.Models;
namespace Topppro.WebSite.Areas.Humanist.Controllers
{
[Authorize]
public class DashboardController : Controller
{
private readonly static string _dlcFolderPath =
ConfigurationManager.AppSettings["RootDownloadsFolderPath"];
public ActionResult Index()
{
var key = "RootDownloadsFolderPath";
var cached = WebCache.Get(key);
if (cached == null)
{
string dlc_path =
Server.MapPath(_dlcFolderPath);
DirectoryInfo dlc_folder = new DirectoryInfo(dlc_path);
if (!dlc_folder.Exists)
return null;
cached = dlc_folder.GetFiles()
.Select(f => new DLCModel()
{
Url = UrlHelper.GenerateContentUrl(Path.Combine(_dlcFolderPath, f.Name), HttpContext),
Name = Path.GetFileNameWithoutExtension(f.Name),
Color = "purple-stripe",
Icon = ""
});
WebCache.Set(key, cached);
}
return View(cached);
}
}
}
```
Fix en dashboard. Uso de la clase de configuracion. | ```c#
using System.IO;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using Topppro.WebSite.Areas.Humanist.Models;
using Topppro.WebSite.Settings;
namespace Topppro.WebSite.Areas.Humanist.Controllers
{
[Authorize]
public class DashboardController : Controller
{
public ActionResult Index()
{
var key = typeof(DownloadSettings).Name;
var cached = WebCache.Get(key);
if (cached == null)
{
string dlc_path =
Server.MapPath(ToppproSettings.Download.Root);
DirectoryInfo dlc_folder = new DirectoryInfo(dlc_path);
if (!dlc_folder.Exists)
return null;
cached = dlc_folder.GetFiles()
.Select(f => new DLCModel()
{
Url = UrlHelper.GenerateContentUrl(Path.Combine(ToppproSettings.Download.Root, f.Name), HttpContext),
Name = Path.GetFileNameWithoutExtension(f.Name),
Color = "purple-stripe",
Icon = ""
});
WebCache.Set(key, cached);
}
return View(cached);
}
}
}
``` |
7ba6eb58-1b29-4213-88ba-d62e05e5c05d | {
"language": "C#"
} | ```c#
using System;
using Caliburn.Micro;
using NDC.Build.Core.Services;
using static System.String;
namespace NDC.Build.Core.ViewModels
{
public class LoginViewModel : Screen
{
private readonly ICredentialsService credentials;
private readonly IAuthenticationService authentication;
private readonly IApplicationNavigationService navigation;
public LoginViewModel(ICredentialsService credentials, IAuthenticationService authentication, IApplicationNavigationService navigation)
{
this.credentials = credentials;
this.authentication = authentication;
this.navigation = navigation;
}
protected override async void OnInitialize()
{
var stored = await credentials.GetCredentialsAsync();
if (stored == Credentials.None)
return;
Account = stored.Account;
Token = stored.Token;
}
public string Account { get; set; }
public string Token { get; set; }
public string Message { get; private set; }
public bool CanLogin => !IsNullOrEmpty(Account) && !IsNullOrEmpty(Token);
public async void Login()
{
var entered = new Credentials(Account, Token);
var authenticated = await authentication.AuthenticateCredentialsAsync(entered);
if (!authenticated)
{
Message = "Account / Token is incorrect";
}
else
{
await credentials.StoreAsync(entered);
navigation.ToProjects();
}
}
}
}
```
Fix login view model inpc | ```c#
using System;
using Caliburn.Micro;
using NDC.Build.Core.Services;
using PropertyChanged;
using static System.String;
namespace NDC.Build.Core.ViewModels
{
public class LoginViewModel : Screen
{
private readonly ICredentialsService credentials;
private readonly IAuthenticationService authentication;
private readonly IApplicationNavigationService navigation;
public LoginViewModel(ICredentialsService credentials, IAuthenticationService authentication, IApplicationNavigationService navigation)
{
this.credentials = credentials;
this.authentication = authentication;
this.navigation = navigation;
}
protected override async void OnInitialize()
{
var stored = await credentials.GetCredentialsAsync();
if (stored == Credentials.None)
return;
Account = stored.Account;
Token = stored.Token;
}
public string Account { get; set; }
public string Token { get; set; }
public string Message { get; private set; }
[DependsOn(nameof(Account), nameof(Token))]
public bool CanLogin => !IsNullOrEmpty(Account) && !IsNullOrEmpty(Token);
public async void Login()
{
var entered = new Credentials(Account, Token);
var authenticated = await authentication.AuthenticateCredentialsAsync(entered);
if (!authenticated)
{
Message = "Account / Token is incorrect";
}
else
{
await credentials.StoreAsync(entered);
navigation.ToProjects();
}
}
}
}
``` |
37f7328b-09ae-47ae-9ead-5a58805afe6e | {
"language": "C#"
} | ```c#
#load "00_constants.csx"
using DotvvmAcademy.Validation.Dothtml.Unit;
using DotvvmAcademy.Validation.Unit;
public DothtmlUnit Unit { get; set; } = new DothtmlUnit();
Unit.GetDirective("/@viewModel")
.RequireTypeArgument(ViewModelName);
var repeater = Unit.GetControl("/html/body/dot:Repeater");
{
repeater.GetProperty("@DataSource")
.RequireBinding(ItemsProperty);
repeater.GetControl("p/dot:Literal")
.GetProperty("@Text")
.RequireBinding("_this");
}```
Fix bug in the repeater step validation | ```c#
#load "00_constants.csx"
using DotvvmAcademy.Validation.Dothtml.Unit;
using DotvvmAcademy.Validation.Unit;
public DothtmlUnit Unit { get; set; } = new DothtmlUnit();
Unit.GetDirective("/@viewModel")
.RequireTypeArgument(ViewModelName);
var repeater = Unit.GetControl("/html/body/dot:Repeater");
{
repeater.GetProperty("@DataSource")
.RequireBinding(ItemsProperty)
.GetControl("p/dot:Literal")
.GetProperty("@Text")
.RequireBinding("_this");
}``` |
85d90172-097e-4fea-8683-fda56988d9ef | {
"language": "C#"
} | ```c#
using System;
namespace EasyButtons
{
/// <summary>
/// Attribute to create a button in the inspector for calling the method it is attached to.
/// The method must have no arguments.
/// </summary>
/// <example>
/// [<see cref="ButtonAttribute"/>]
/// void MyMethod()
/// {
/// Debug.Log("Clicked!");
/// }
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class ButtonAttribute : Attribute { }
}```
Update attribute summary and example | ```c#
using System;
namespace EasyButtons
{
/// <summary>
/// Attribute to create a button in the inspector for calling the method it is attached to.
/// The method must be public and have no arguments.
/// </summary>
/// <example>
/// [<see cref="ButtonAttribute"/>]
/// public void MyMethod()
/// {
/// Debug.Log("Clicked!");
/// }
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class ButtonAttribute : Attribute { }
}``` |
17832bce-7c36-4054-b434-3ee8bd54d93c | {
"language": "C#"
} | ```c#
#region using
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
#endregion
namespace GitDiffMargin
{
[Export(typeof (IWpfTextViewMarginProvider))]
[Name(EditorDiffMargin.MarginNameConst)]
[Order(Before = PredefinedMarginNames.LineNumber)]
[MarginContainer(PredefinedMarginNames.LeftSelection)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class EditorDiffMarginFactory : DiffMarginFactoryBase
{
public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin)
{
var marginCore = TryGetMarginCore(textViewHost);
if (marginCore == null)
return null;
return new EditorDiffMargin(textViewHost.TextView, marginCore);
}
}
}```
Move diff bar to the right of the line numbers (like in the GitSCC extension) | ```c#
#region using
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
#endregion
namespace GitDiffMargin
{
[Export(typeof (IWpfTextViewMarginProvider))]
[Name(EditorDiffMargin.MarginNameConst)]
[Order(After = PredefinedMarginNames.Spacer, Before = PredefinedMarginNames.Outlining)]
[MarginContainer(PredefinedMarginNames.LeftSelection)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class EditorDiffMarginFactory : DiffMarginFactoryBase
{
public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin)
{
var marginCore = TryGetMarginCore(textViewHost);
if (marginCore == null)
return null;
return new EditorDiffMargin(textViewHost.TextView, marginCore);
}
}
}``` |
b212f990-46e1-4d19-9912-0b779bf85d38 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
System.Console.WriteLine ("cleanup context");
gp_context_unref(handle);
}
}
}
```
Remove random context cleanup console output | ```c#
using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
gp_context_unref(handle);
}
}
}
``` |
9df39e58-8077-4e0b-977d-33adecbddccb | {
"language": "C#"
} | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class AccountBusinessProfileOptions : INestedOptions
{
[JsonProperty("mcc")]
public string Mcc { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("primary_color")]
public string PrimaryColor { get; set; }
[JsonProperty("product_description")]
public string ProductDescription { get; set; }
[JsonProperty("support_email")]
public string SupportEmail { get; set; }
[JsonProperty("support_phone")]
public string SupportPhone { get; set; }
[JsonProperty("support_url")]
public string SupportUrl { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
}
```
Add support for `SupportAddress` on `Account` create and update | ```c#
namespace Stripe
{
using System;
using Newtonsoft.Json;
public class AccountBusinessProfileOptions : INestedOptions
{
/// <summary>
/// The merchant category code for the account. MCCs are used to classify businesses based
/// on the goods or services they provide.
/// </summary>
[JsonProperty("mcc")]
public string Mcc { get; set; }
/// <summary>
/// The customer-facing business name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
[Obsolete("Use AccountSettingsBrandingOptions.PrimaryColor instead.")]
[JsonProperty("primary_color")]
public string PrimaryColor { get; set; }
/// <summary>
/// Internal-only description of the product sold by, or service provided by, the business.
/// Used by Stripe for risk and underwriting purposes.
/// </summary>
[JsonProperty("product_description")]
public string ProductDescription { get; set; }
/// <summary>
/// A publicly available mailing address for sending support issues to.
/// </summary>
[JsonProperty("support_address")]
public AddressOptions SupportAddress { get; set; }
/// <summary>
/// A publicly available email address for sending support issues to.
/// </summary>
[JsonProperty("support_email")]
public string SupportEmail { get; set; }
/// <summary>
/// A publicly available phone number to call with support issues.
/// </summary>
[JsonProperty("support_phone")]
public string SupportPhone { get; set; }
/// <summary>
/// A publicly available website for handling support issues.
/// </summary>
[JsonProperty("support_url")]
public string SupportUrl { get; set; }
/// <summary>
/// The business’s publicly available website.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
}
``` |
ba0375d5-675b-4dbd-ac47-8ee215e2f8f0 | {
"language": "C#"
} | ```c#
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class ReferencesRequest
{
public static readonly
RequestType<ReferencesParams, Location[], object, object> Type =
RequestType<ReferencesParams, Location[], object, object>.Create("textDocument/references");
}
public class ReferencesParams : TextDocumentPosition
{
public ReferencesContext Context { get; set; }
}
public class ReferencesContext
{
public bool IncludeDeclaration { get; set; }
}
}
```
Add registration options for reference request | ```c#
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class ReferencesRequest
{
public static readonly
RequestType<ReferencesParams, Location[], object, TextDocumentRegistrationOptions> Type =
RequestType<ReferencesParams, Location[], object, TextDocumentRegistrationOptions>.Create("textDocument/references");
}
public class ReferencesParams : TextDocumentPosition
{
public ReferencesContext Context { get; set; }
}
public class ReferencesContext
{
public bool IncludeDeclaration { get; set; }
}
}
``` |
fabbf085-3b55-417b-85b5-e1e10de5dff9 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChannelState.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
/// <summary>
/// Represents the state of a Channel
/// </summary>
public enum ChannelState
{
#pragma warning disable 1591
New,
Init,
Routing,
SoftExecute,
Execute,
ExchangeMedia,
Park,
ConsumeMedia,
Hibernate,
Reset,
Hangup,
Done,
Destroy,
Reporting
#pragma warning restore 1591
}
}```
Add channel state None (CS_NONE) | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChannelState.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
/// <summary>
/// Represents the state of a Channel
/// </summary>
public enum ChannelState
{
#pragma warning disable 1591
New,
Init,
Routing,
SoftExecute,
Execute,
ExchangeMedia,
Park,
ConsumeMedia,
Hibernate,
Reset,
Hangup,
Done,
Destroy,
Reporting,
None
#pragma warning restore 1591
}
}``` |
03a41fb8-dd5e-4207-9245-29bc7ffd7af2 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
}```
Fix for no soldier foudn on nav component | ```c#
using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => Soldier != null && !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
}``` |
3591bc22-9ec8-4076-9783-0aca90614f29 | {
"language": "C#"
} | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Login Successful";
ViewBag.HideSigninLink = "true";
}
<h1 class="heading-xlarge">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
}```
Copy change on the logged in page | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Login Successful";
ViewBag.HideSigninLink = "true";
}
<h1 class="heading-xlarge">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
}``` |
f8cd874c-c25b-49da-9fe0-a05513f3270d | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using System.Text;
using YaR.MailRuCloud.Api.Base.Requests.Repo;
namespace YaR.MailRuCloud.Api.Base.Requests.WebM1
{
class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result>
{
private readonly string _sourceFullPath;
private readonly string _destinationPath;
public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth)
{
_sourceFullPath = sourceFullPath;
_destinationPath = destinationPath;
}
protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}";
protected override byte[] CreateHttpContent()
{
var data = Encoding.UTF8.GetBytes($"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}");
return data;
}
}
}
```
Move request changed for uniformity | ```c#
using System;
using System.Net;
using System.Text;
using YaR.MailRuCloud.Api.Base.Requests.Repo;
namespace YaR.MailRuCloud.Api.Base.Requests.WebM1
{
class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result>
{
private readonly string _sourceFullPath;
private readonly string _destinationPath;
public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth)
{
_sourceFullPath = sourceFullPath;
_destinationPath = destinationPath;
}
protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}";
protected override byte[] CreateHttpContent()
{
var data = $"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}";
return Encoding.UTF8.GetBytes(data);
}
}
}
``` |
b1984a5c-7f02-4c19-97b0-f72d687a8335 | {
"language": "C#"
} | ```c#
@using Mollie.WebApplicationCoreExample.Framework.Extensions
@model CreatePaymentModel
@{
ViewData["Title"] = "Create payment";
}
<div class="container">
<h2>Create new payment</h2>
<form method="post">
<div asp-validation-summary="All"></div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label asp-for="Amount"></label>
<input class="form-control" asp-for="Amount" />
</div>
<div class="form-group">
<label asp-for="Currency"></label>
<select class="form-control" asp-for="Currency" asp-items="@Html.GetStaticStringSelectList(typeof(Currency))"></select>
</div>
<div class="form-group">
<label asp-for="Description"></label>
<textarea class="form-control" asp-for="Description" rows="4"></textarea>
</div>
<input type="submit" name="Save" value="Save" class="btn btn-primary" />
</div>
</div>
</form>
</div>```
Disable autocomplete for payment amount | ```c#
@using Mollie.WebApplicationCoreExample.Framework.Extensions
@model CreatePaymentModel
@{
ViewData["Title"] = "Create payment";
}
<div class="container">
<h2>Create new payment</h2>
<form method="post">
<div asp-validation-summary="All"></div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label asp-for="Amount"></label>
<input class="form-control" asp-for="Amount" autocomplete="off" />
</div>
<div class="form-group">
<label asp-for="Currency"></label>
<select class="form-control" asp-for="Currency" asp-items="@Html.GetStaticStringSelectList(typeof(Currency))"></select>
</div>
<div class="form-group">
<label asp-for="Description"></label>
<textarea class="form-control" asp-for="Description" rows="4"></textarea>
</div>
<input type="submit" name="Save" value="Save" class="btn btn-primary" />
</div>
</div>
</form>
</div>``` |
294b5e40-3efc-49d1-98b4-096f49bbb9b0 | {
"language": "C#"
} | ```c#
namespace Fixie.Console
{
public class Options
{
public Options(
string configuration,
bool noBuild,
string framework,
string report)
{
Configuration = configuration ?? "Debug";
NoBuild = noBuild;
Framework = framework;
Report = report;
}
public string Configuration { get; }
public bool NoBuild { get; }
public bool ShouldBuild => !NoBuild;
public string Framework { get; }
public string Report { get; }
}
}```
Declare the nullability of parsed command line arguments. | ```c#
namespace Fixie.Console
{
public class Options
{
public Options(
string? configuration,
bool noBuild,
string? framework,
string? report)
{
Configuration = configuration ?? "Debug";
NoBuild = noBuild;
Framework = framework;
Report = report;
}
public string Configuration { get; }
public bool NoBuild { get; }
public bool ShouldBuild => !NoBuild;
public string? Framework { get; }
public string? Report { get; }
}
}``` |
ebd33047-dfcf-49bd-b2cb-7f91ec24e029 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CanvasMock.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using SharpDX;
using SharpDX.Direct3D11;
namespace HelixToolkit.Wpf.SharpDX.Tests.Controls
{
class CanvasMock : IRenderHost
{
public CanvasMock()
{
Device = EffectsManager.Device;
RenderTechnique = Techniques.RenderPhong;
}
public Device Device { get; private set; }
Color4 IRenderHost.ClearColor { get; }
Device IRenderHost.Device { get; }
public Color4 ClearColor { get; private set; }
public bool IsShadowMapEnabled { get; private set; }
public bool IsMSAAEnabled { get; private set; }
public IRenderer Renderable { get; private set; }
public void SetDefaultRenderTargets()
{
throw new NotImplementedException();
}
public void SetDefaultColorTargets(DepthStencilView dsv)
{
throw new NotImplementedException();
}
public RenderTechnique RenderTechnique { get; private set; }
public double ActualHeight { get; private set; }
public double ActualWidth { get; private set; }
}
}```
Fix and re-enable the canvas mock. | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CanvasMock.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using SharpDX;
using SharpDX.Direct3D11;
namespace HelixToolkit.Wpf.SharpDX.Tests.Controls
{
class CanvasMock : IRenderHost
{
public CanvasMock()
{
Device = EffectsManager.Device;
RenderTechnique = Techniques.RenderPhong;
}
public Device Device { get; private set; }
public Color4 ClearColor { get; private set; }
public bool IsShadowMapEnabled { get; private set; }
public bool IsMSAAEnabled { get; private set; }
public IRenderer Renderable { get; private set; }
public RenderTechnique RenderTechnique { get; private set; }
public double ActualHeight { get; private set; }
public double ActualWidth { get; private set; }
public void SetDefaultRenderTargets()
{
throw new NotImplementedException();
}
public void SetDefaultColorTargets(DepthStencilView dsv)
{
throw new NotImplementedException();
}
}
}``` |
7a7816db-7a15-4166-9429-b0b3f65bd3a4 | {
"language": "C#"
} | ```c#
using CefSharp;
using CefSharp.Wpf;
using Playnite.Common;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Playnite
{
public class CefTools
{
public static bool IsInitialized { get; private set; }
public static void ConfigureCef()
{
FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath);
var settings = new CefSettings();
settings.WindowlessRenderingEnabled = true;
if (!settings.CefCommandLineArgs.ContainsKey("disable-gpu"))
{
settings.CefCommandLineArgs.Add("disable-gpu", "1");
}
if (!settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing"))
{
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
}
settings.CachePath = PlaynitePaths.BrowserCachePath;
settings.PersistSessionCookies = true;
settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log");
IsInitialized = Cef.Initialize(settings);
}
public static void Shutdown()
{
Cef.Shutdown();
IsInitialized = false;
}
}
}
```
Make sure GPU accel. in web view is disabled even if default cefsharp settings change | ```c#
using CefSharp;
using CefSharp.Wpf;
using Playnite.Common;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Playnite
{
public class CefTools
{
public static bool IsInitialized { get; private set; }
public static void ConfigureCef()
{
FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath);
var settings = new CefSettings();
settings.WindowlessRenderingEnabled = true;
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu"))
{
settings.CefCommandLineArgs.Remove("disable-gpu");
}
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing"))
{
settings.CefCommandLineArgs.Remove("disable-gpu-compositing");
}
settings.CefCommandLineArgs.Add("disable-gpu", "1");
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
settings.CachePath = PlaynitePaths.BrowserCachePath;
settings.PersistSessionCookies = true;
settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log");
IsInitialized = Cef.Initialize(settings);
}
public static void Shutdown()
{
Cef.Shutdown();
IsInitialized = false;
}
}
}
``` |
0173f32d-096c-4432-abe4-731348411c0f | {
"language": "C#"
} | ```c#
/*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.1.0")]
[assembly: AssemblyFileVersion("1.2.1.0")]
```
Update the version to 1.2.2 | ```c#
/*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.2.0")]
[assembly: AssemblyFileVersion("1.2.2.0")]``` |
8d88222e-4e92-484d-a838-c83b52d7fa71 | {
"language": "C#"
} | ```c#
using System.IO;
using SoftwareThresher.Settings.Search;
using SoftwareThresher.Utilities;
namespace SoftwareThresher.Observations {
public abstract class Observation {
readonly Search search;
protected Observation(Search search)
{
this.search = search;
}
public virtual bool Failed { get; set; }
public abstract string Name { get; }
public abstract string Location { get; }
public abstract string SystemSpecificString { get; }
// TODO - push more logic into this class?
public virtual Date LastEdit => search.GetLastEditDate(this);
public override string ToString() {
return $"{Location}{Path.PathSeparator}{Name}";
}
}
}
```
Remove comment - no action needed | ```c#
using System.IO;
using SoftwareThresher.Settings.Search;
using SoftwareThresher.Utilities;
namespace SoftwareThresher.Observations {
public abstract class Observation {
readonly Search search;
protected Observation(Search search)
{
this.search = search;
}
public virtual bool Failed { get; set; }
public abstract string Name { get; }
public abstract string Location { get; }
public abstract string SystemSpecificString { get; }
public virtual Date LastEdit => search.GetLastEditDate(this);
public override string ToString() {
return $"{Location}{Path.PathSeparator}{Name}";
}
}
}
``` |
9a374cbc-f9ee-43f0-afd7-a8b6c5cd3cb4 | {
"language": "C#"
} | ```c#
// ReSharper disable UnusedMember.Local
namespace Gu.State.Benchmarks
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
public static class Program
{
public static void Main()
{
foreach (var summary in RunSingle<EqualByComplexType>())
{
CopyResult(summary);
}
}
private static IEnumerable<Summary> RunAll() => new BenchmarkSwitcher(typeof(Program).Assembly).RunAll();
private static IEnumerable<Summary> RunSingle<T>() => new[] { BenchmarkRunner.Run<T>() };
private static void CopyResult(Summary summary)
{
var sourceFileName = Directory.EnumerateFiles(summary.ResultsDirectoryPath, $"*{summary.Title}-report-github.md")
.Single();
var destinationFileName = Path.ChangeExtension(FindCsFile(), ".md");
Console.WriteLine($"Copy: {sourceFileName} -> {destinationFileName}");
File.Copy(sourceFileName, destinationFileName, overwrite: true);
string FindCsFile()
{
return Directory.EnumerateFiles(
AppDomain.CurrentDomain.BaseDirectory.Split(new[] { "\\bin\\" }, StringSplitOptions.RemoveEmptyEntries).First(),
$"{summary.Title.Split('.').Last()}.cs",
SearchOption.AllDirectories)
.Single();
}
}
}
}
```
Fix copying of markdown result. | ```c#
// ReSharper disable UnusedMember.Local
namespace Gu.State.Benchmarks
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
public static class Program
{
public static void Main()
{
foreach (var summary in RunSingle<EqualByComplexType>())
{
CopyResult(summary);
}
}
private static IEnumerable<Summary> RunAll() => new BenchmarkSwitcher(typeof(Program).Assembly).RunAll();
private static IEnumerable<Summary> RunSingle<T>() => new[] { BenchmarkRunner.Run<T>() };
private static void CopyResult(Summary summary)
{
var trimmedTitle = summary.Title.Split('.').Last().Split('-').First();
Console.WriteLine(trimmedTitle);
var sourceFileName = FindMdFile();
var destinationFileName = Path.ChangeExtension(FindCsFile(), ".md");
Console.WriteLine($"Copy: {sourceFileName} -> {destinationFileName}");
File.Copy(sourceFileName, destinationFileName, overwrite: true);
string FindMdFile()
{
return Directory.EnumerateFiles(summary.ResultsDirectoryPath, $"*{trimmedTitle}-report-github.md")
.Single();
}
string FindCsFile()
{
return Directory.EnumerateFiles(
AppDomain.CurrentDomain.BaseDirectory.Split(new[] { "\\bin\\" }, StringSplitOptions.RemoveEmptyEntries).First(),
$"{trimmedTitle}.cs",
SearchOption.AllDirectories)
.Single();
}
}
}
}
``` |
a37e6c03-3fb9-477e-9287-92616b1b3f63 | {
"language": "C#"
} | ```c#
using System;
namespace Blog.Data
{
public class Post
{
public int Id { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ComputedDescription
{
get
{
if (!string.IsNullOrEmpty(this.Description))
{
return this.Description;
}
var description = this.Content.Split(new string[] { "<!-- more -->", "<!--more-->" }, StringSplitOptions.RemoveEmptyEntries);
if (description.Length > 0)
{
return description[0];
}
return string.Empty;
}
}
public string Content { get; set; }
public DateTime? PublicationDate { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
}
```
Add expression indicating if a post is published | ```c#
using System;
using System.Linq.Expressions;
namespace Blog.Data
{
public class Post
{
public int Id { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ComputedDescription
{
get
{
if (!string.IsNullOrEmpty(this.Description))
{
return this.Description;
}
var description = this.Content.Split(new string[] { "<!-- more -->", "<!--more-->" }, StringSplitOptions.RemoveEmptyEntries);
if (description.Length > 0)
{
return description[0];
}
return string.Empty;
}
}
public string Content { get; set; }
public DateTime? PublicationDate { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public static Expression<Func<Post, bool>> IsPublished = post => post.PublicationDate.HasValue && DateTime.Now > post.PublicationDate;
}
}
``` |
9fe4e952-407c-4893-97c8-38ee9b7babf8 | {
"language": "C#"
} | ```c#
using log4net;
using RightpointLabs.ConferenceRoom.Services.Attributes;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
namespace RightpointLabs.ConferenceRoom.Services.Controllers
{
/// <summary>
/// Operations dealing with client log messages
/// </summary>
[ErrorHandler]
public abstract class BaseController : ApiController
{
protected BaseController(ILog log)
{
this.Log = log;
}
protected internal ILog Log { get; private set; }
protected static string GetClientIp(HttpRequestMessage request = null)
{
// from https://trikks.wordpress.com/2013/06/27/getting-the-client-ip-via-asp-net-web-api/
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
}
}
```
Fix process of requesting access to a room | ```c#
using log4net;
using RightpointLabs.ConferenceRoom.Services.Attributes;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;
namespace RightpointLabs.ConferenceRoom.Services.Controllers
{
/// <summary>
/// Operations dealing with client log messages
/// </summary>
[ErrorHandler]
public abstract class BaseController : ApiController
{
protected BaseController(ILog log)
{
this.Log = log;
}
protected internal ILog Log { get; private set; }
protected string GetClientIp(HttpRequestMessage request = null)
{
request = request ?? Request;
// from https://trikks.wordpress.com/2013/06/27/getting-the-client-ip-via-asp-net-web-api/
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else if (HttpContext.Current != null)
{
return HttpContext.Current.Request.UserHostAddress;
}
else
{
return null;
}
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.