doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
ee58cff5-231d-491e-aede-3b187d955721 | {
"language": "C#"
} | ```c#
using slang.Lexing.Rules.Extensions;
using slang.Lexing.Trees.Nodes;
namespace slang.Lexing.Trees.Transformers
{
public static class OptionRuleExtensions
{
public static Node Transform (this Option rule, Node parent)
{
var option = rule.Value.Transform (parent);
return option;
}
}
}
```
Implement transform to tree for option as skeleton only | ```c#
using slang.Lexing.Rules.Extensions;
using slang.Lexing.Trees.Nodes;
namespace slang.Lexing.Trees.Transformers
{
public static class OptionRuleExtensions
{
public static Tree Transform (this Option rule, Node parent)
{
return new Tree ();
}
}
}
``` |
34bdaeb0-5652-44a5-b72b-3f47d09c7bd7 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
namespace VersionOne.SDK.APIClient.Tests.QueryTests
{
[TestFixture]
public class QueryFindTester
{
private EnvironmentContext _context;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_context = new EnvironmentContext();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
_context = null;
}
[Test]
public void FindMemberTest()
{
var assetType = _context.MetaModel.GetAssetType("Member");
var query = new Query(assetType);
var nameAttribute = assetType.GetAttributeDefinition("Username");
query.Selection.Add(nameAttribute);
query.Find = new QueryFind("admin", new AttributeSelection("Username", assetType));
QueryResult result = _context.Services.Retrieve(query);
Assert.AreEqual(1, result.TotalAvaliable);
}
}
}```
Test that finds members with "admin" in username now works when there's more than one. | ```c#
using NUnit.Framework;
namespace VersionOne.SDK.APIClient.Tests.QueryTests
{
[TestFixture]
public class QueryFindTester
{
private EnvironmentContext _context;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_context = new EnvironmentContext();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
_context = null;
}
[Test]
public void FindMemberTest()
{
var memberType = _context.MetaModel.GetAssetType("Member");
var memberQuery = new Query(memberType);
var userNameAttr = memberType.GetAttributeDefinition("Username");
memberQuery.Selection.Add(userNameAttr);
memberQuery.Find = new QueryFind("admin", new AttributeSelection("Username", memberType));
QueryResult result = _context.Services.Retrieve(memberQuery);
foreach (var member in result.Assets)
{
var name = member.GetAttribute(userNameAttr).Value as string;
Assert.IsNotNullOrEmpty(name);
if (name != null) Assert.That(name.IndexOf("admin") > -1);
}
}
}
}``` |
b29b0831-e391-413e-a6be-6bd830fe7920 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Pingy.Common;
namespace Pingy.Gui
{
public partial class App : Application
{
private readonly static string defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private readonly static string defaultFileName = "Pingy.txt";
private readonly static string defaultFilePath = Path.Combine(defaultDirectory, defaultFileName);
public App()
: this(defaultFilePath)
{ }
public App(string path)
{
if (String.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
InitializeComponent();
MainWindowViewModel viewModel = new MainWindowViewModel(path);
MainWindow = new MainWindow(viewModel);
MainWindow.Show();
}
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (e.Exception is Exception ex)
{
Log.Exception(ex, true);
}
else
{
Log.Message("an empty unhandled exception occurred");
}
}
}
}
```
Mark field as const instead of static readonly | ```c#
using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Pingy.Common;
namespace Pingy.Gui
{
public partial class App : Application
{
private static readonly string defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private const string defaultFileName = "Pingy.txt";
private readonly static string defaultFilePath = Path.Combine(defaultDirectory, defaultFileName);
public App()
: this(defaultFilePath)
{ }
public App(string path)
{
if (String.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
InitializeComponent();
MainWindowViewModel viewModel = new MainWindowViewModel(path);
MainWindow = new MainWindow(viewModel);
MainWindow.Show();
}
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (e.Exception is Exception ex)
{
Log.Exception(ex, true);
}
else
{
Log.Message("an empty unhandled exception occurred");
}
}
}
}
``` |
a27706e7-49d5-48b5-b351-30e5b540f55c | {
"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.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Taiko.UI
{
public class TaikoPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
private const float default_relative_height = TaikoPlayfield.DEFAULT_HEIGHT / 768;
private const float default_aspect = 16f / 9f;
public TaikoPlayfieldAdjustmentContainer()
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
}
protected override void Update()
{
base.Update();
float aspectAdjust = Math.Clamp(Parent.ChildSize.X / Parent.ChildSize.Y, 0.4f, 4) / default_aspect;
Size = new Vector2(1, default_relative_height * aspectAdjust);
}
}
}
```
Reposition taiko playfield to be closer to the top of the screen | ```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.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Taiko.UI
{
public class TaikoPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
private const float default_relative_height = TaikoPlayfield.DEFAULT_HEIGHT / 768;
private const float default_aspect = 16f / 9f;
protected override void Update()
{
base.Update();
float aspectAdjust = Math.Clamp(Parent.ChildSize.X / Parent.ChildSize.Y, 0.4f, 4) / default_aspect;
Size = new Vector2(1, default_relative_height * aspectAdjust);
// Position the taiko playfield exactly one playfield from the top of the screen.
RelativePositionAxes = Axes.Y;
Y = Size.Y;
}
}
}
``` |
eec3b5cf-0160-40ce-99d3-cdfcf97f1e1f | {
"language": "C#"
} | ```c#
namespace NuGetPackageVisualizer
{
public class DgmlColorConfiguration : IColorConfiguration
{
public string VersionMismatchPackageColor
{
get { return "#FF0000"; }
}
public string PackageHasDifferentVersionsColor
{
get { return "#FCE428"; }
}
public string DefaultColor
{
get { return "#15FF00"; }
}
}
}```
Make the green slightly darker, so that the text is readable. | ```c#
namespace NuGetPackageVisualizer
{
public class DgmlColorConfiguration : IColorConfiguration
{
public string VersionMismatchPackageColor
{
get { return "#FF0000"; }
}
public string PackageHasDifferentVersionsColor
{
get { return "#FCE428"; }
}
public string DefaultColor
{
get { return "#339933"; }
}
}
}``` |
ba344efb-6bc6-4eaf-bfe5-bea6719cb999 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
namespace Slp.Evi.Test.System.Sparql
{
public abstract class SparqlFixture
{
private readonly ConcurrentDictionary<string, EviQueryableStorage> _storages = new ConcurrentDictionary<string, EviQueryableStorage>();
private IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
if (Environment.GetEnvironmentVariable("APPVEYOR") != "True")
{
loggerFactory.AddConsole(LogLevel.Trace);
}
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
public EviQueryableStorage GetStorage(string storageName)
{
return _storages.GetOrAdd(storageName, CreateStorage);
}
private EviQueryableStorage CreateStorage(string storageName)
{
return SparqlTestHelpers.InitializeDataset(storageName, GetSqlDb(), GetStorageFactory());
}
protected abstract ISqlDatabase GetSqlDb();
}
}```
Disable logging so the performance profiling is more accurate. | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
namespace Slp.Evi.Test.System.Sparql
{
public abstract class SparqlFixture
{
private readonly ConcurrentDictionary<string, EviQueryableStorage> _storages = new ConcurrentDictionary<string, EviQueryableStorage>();
private IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
//if (Environment.GetEnvironmentVariable("APPVEYOR") != "True")
//{
// loggerFactory.AddConsole(LogLevel.Trace);
//}
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
public EviQueryableStorage GetStorage(string storageName)
{
return _storages.GetOrAdd(storageName, CreateStorage);
}
private EviQueryableStorage CreateStorage(string storageName)
{
return SparqlTestHelpers.InitializeDataset(storageName, GetSqlDb(), GetStorageFactory());
}
protected abstract ISqlDatabase GetSqlDb();
}
}``` |
66d56a45-0588-4e06-a31e-d48b6ece6606 | {
"language": "C#"
} | ```c#
using LazyLibrary.Storage;
using LazyLibrary.Storage.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace LazyLibrary.Tests.Storage.Memory
{
[TestClass]
public class MemoryRepositoryTests
{
[TestMethod]
public void CanAdd()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsTrue(repo.Get().Any(), "The object could not be added to the repository");
}
[TestMethod]
public void CanGetById()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsNotNull(repo.GetById(1), "The object could not be retrieved from the repository");
}
}
}```
Test can get by LINQ statement | ```c#
using LazyLibrary.Storage;
using LazyLibrary.Storage.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace LazyLibrary.Tests.Storage.Memory
{
[TestClass]
public class MemoryRepositoryTests
{
[TestMethod]
public void CanAdd()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsTrue(repo.Get().Any(), "The object could not be added to the repository");
}
[TestMethod]
public void CanGetById()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsNotNull(repo.GetById(1), "The object could not be retrieved from the repository");
}
[TestMethod]
public void CanGetByLINQ()
{
var repo = new MemoryRepository<TestObject>();
var objOne = new TestObject() { Name = "one" };
var objTwo = new TestObject() { Name = "two" };
repo.Upsert(objOne);
repo.Upsert(objTwo);
var result = repo.Get(x => x.Name == "one").SingleOrDefault();
Assert.IsNotNull(result, "The object could not be retrieved from the repository");
Assert.IsTrue(result.Equals(objOne), "The object could not be retrieved from the repository");
}
}
}``` |
da17d8a7-4a3f-401d-9cbc-8b1d9648c262 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Api
{
[TestFixture]
public class NUnitIssue52
{
class SelfContainer : IEnumerable
{
public IEnumerator GetEnumerator() { yield return this; }
}
[Test]
public void SelfContainedItemFoundInArray()
{
var item = new SelfContainer();
var items = new SelfContainer[] { new SelfContainer(), item };
// work around
//Assert.True(((ICollection<SelfContainer>)items).Contains(item));
// causes StackOverflowException
//Assert.Contains(item, items);
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
var equal = equalityComparer.AreEqual(item, items, ref tolerance);
Assert.IsFalse(equal);
//Console.WriteLine("test completed");
}
}
}
```
Add test explicitly checking recursion | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Api
{
[TestFixture]
public class NUnitIssue52
{
[TestCaseSource(nameof(GetTestCases))]
public void SelfContainedItemFoundInCollection<T>(T x, ICollection y)
{
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
var actualResult = equalityComparer.AreEqual(x, y, ref tolerance);
Assert.IsFalse(actualResult);
Assert.Contains(x, y);
}
[TestCaseSource(nameof(GetTestCases))]
public void SelfContainedItemDoesntRecurseForever<T>(T x, ICollection y)
{
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
equalityComparer.ExternalComparers.Add(new DetectRecursionComparer(30));
Assert.DoesNotThrow(() =>
{
var equality = equalityComparer.AreEqual(x, y, ref tolerance);
Assert.IsFalse(equality);
Assert.Contains(x, y);
});
}
public static IEnumerable<TestCaseData> GetTestCases()
{
var item = new SelfContainer();
var items = new SelfContainer[] { new SelfContainer(), item };
yield return new TestCaseData(item, items);
}
private class DetectRecursionComparer : EqualityAdapter
{
private readonly int maxRecursion;
[MethodImpl(MethodImplOptions.NoInlining)]
public DetectRecursionComparer(int maxRecursion)
{
var callerDepth = new StackTrace().FrameCount - 1;
this.maxRecursion = callerDepth + maxRecursion;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override bool CanCompare(object x, object y)
{
var currentDepth = new StackTrace().FrameCount - 1;
return currentDepth >= maxRecursion;
}
public override bool AreEqual(object x, object y)
{
throw new InvalidOperationException("Recurses");
}
}
private class SelfContainer : IEnumerable
{
public IEnumerator GetEnumerator() { yield return this; }
}
}
}
``` |
fb7f93dd-6991-4e0c-9c80-a2c6874ccc4f | {
"language": "C#"
} | ```c#
namespace Serilog
{
using System.IO;
/// <summary>
/// Enables hooking into log file lifecycle events
/// </summary>
public abstract class FileLifecycleHooks
{
/// <summary>
/// Wraps <paramref name="sourceStream"/> in another stream, such as a GZipStream, then returns the wrapped stream
/// </summary>
/// <param name="sourceStream">The source log file stream</param>
/// <returns>The wrapped stream</returns>
public abstract Stream Wrap(Stream sourceStream);
}
}
```
Add docs re wrapped stream ownership | ```c#
namespace Serilog
{
using System.IO;
/// <summary>
/// Enables hooking into log file lifecycle events
/// </summary>
public abstract class FileLifecycleHooks
{
/// <summary>
/// Wraps <paramref name="underlyingStream"/> in another stream, such as a GZipStream, then returns the wrapped stream
/// </summary>
/// <remarks>
/// Serilog is responsible for disposing of the wrapped stream
/// </remarks>
/// <param name="underlyingStream">The underlying log file stream</param>
/// <returns>The wrapped stream</returns>
public abstract Stream Wrap(Stream underlyingStream);
}
}
``` |
9873da97-cb22-4250-b293-6e57e61c3879 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class ArraySerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.IsArray;
}
protected override Type[] GetTypeArguments(Type type)
{
return new[] { type.GetElementType() };
}
private static JsonValue _Encode<T>(T[] array, JsonSerializer serializer)
{
var json = new JsonArray();
json.AddRange(array.Select(serializer.Serialize));
return json;
}
private static T[] _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var list = new List<T>();
list.AddRange(json.Array.Select(serializer.Deserialize<T>));
return list.ToArray();
}
}
}```
Decrease allocations during array serialization/deserialization | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class ArraySerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.IsArray;
}
protected override Type[] GetTypeArguments(Type type)
{
return new[] { type.GetElementType() };
}
private static JsonValue _Encode<T>(T[] array, JsonSerializer serializer)
{
var values = new JsonValue[array.Length];
for (int ii = 0; ii < array.Length; ++ii)
{
values[ii] = serializer.Serialize(array[ii]);
}
return new JsonArray(values);
}
private static T[] _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var array = json.Array;
var values = new T[array.Count];
for (int ii = 0; ii < array.Count; ++ii)
{
values[ii] = serializer.Deserialize<T>(array[ii]);
}
return values;
}
}
}``` |
b627a240-606b-404a-9427-ee38cacdcb62 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public object Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return "[Compilation failed]";
}
compiledAssembly = stream.ToArray();
}
object result;
using (var sandbox = new Sandbox("Sandbox", compiledAssembly))
{
result = sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
return result;
}
}
}
```
Use simpler constructor when instantiating the Sandbox | ```c#
using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public object Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return "[Compilation failed]";
}
compiledAssembly = stream.ToArray();
}
object result;
using (var sandbox = new Sandbox(compiledAssembly))
{
result = sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
return result;
}
}
}
``` |
d54b0442-048e-4a4e-9b62-19017957e1ce | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Affecto Authentication Server")]
[assembly: AssemblyProduct("Affecto Authentication Server")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0-prerelease01")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]```
Raise authentication server prerelease version number. | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Affecto Authentication Server")]
[assembly: AssemblyProduct("Affecto Authentication Server")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0-prerelease02")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]``` |
1616ac65-c369-42f5-92d2-01365f9fd786 | {
"language": "C#"
} | ```c#
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Borodar.RainbowFolders.Editor.Settings;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor
{
public static class RainbowFoldersMenu
{
[MenuItem("Rainbow Folders/Show Settings")]
public static void OpenSettings()
{
var settings = RainbowFoldersSettings.Load();
Selection.activeObject = settings;
}
}
}```
Move settings menu to the "Edit" category | ```c#
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Borodar.RainbowFolders.Editor.Settings;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor
{
public static class RainbowFoldersMenu
{
[MenuItem("Edit/Rainbow Folders Settings", false, 500)]
public static void OpenSettings()
{
var settings = RainbowFoldersSettings.Load();
Selection.activeObject = settings;
}
}
}``` |
f6bd5fb2-c100-4b1c-bcf5-205e353e64fb | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Common
{
public abstract class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetPropertyValue<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return;
storage = value;
RaisePropertyChanged(propertyName);
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression is null)
throw new ArgumentNullException(nameof(propertyExpression));
if (!(propertyExpression.Body is MemberExpression memberExpression))
throw new ArgumentException("The expression is not a member access expression.", nameof(propertyExpression));
RaisePropertyChanged(memberExpression.Member.Name);
}
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}```
Refactor notification object and add methods for static property changed event | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Common
{
public abstract class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetPropertyValue<T>(ref T storage, in T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected static bool SetPropertyValue<T>(ref T storage, in T value, EventHandler<PropertyChangedEventArgs> handler, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
RaisePropertyChanged(handler, propertyName);
return true;
}
protected static void RaisePropertyChanged(EventHandler<PropertyChangedEventArgs> handler, [CallerMemberName] string propertyName = null) =>
handler?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
}``` |
c9a9a2be-b9e6-4eb1-ba2b-46b3f2218c50 | {
"language": "C#"
} | ```c#
// -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
using System.IO;
using Weave.Compiler;
using Weave.Parser;
internal class Program
{
private static void Main(string[] args)
{
var input = File.ReadAllText(args[0]);
var parser = new WeaveParser();
var parsed = parser.Parse(input);
var output = WeaveCompiler.Compile(parsed);
File.WriteAllText(args[0] + ".cs", output.Code);
}
}
}
```
Allow multiple files on the command line. | ```c#
// -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
using System.IO;
using Weave.Compiler;
using Weave.Parser;
internal class Program
{
private static void Main(string[] args)
{
foreach (var arg in args)
{
var input = File.ReadAllText(arg);
var parser = new WeaveParser();
var parsed = parser.Parse(input, arg);
var output = WeaveCompiler.Compile(parsed);
File.WriteAllText(arg + ".cs", output.Code);
}
}
}
}
``` |
767a370f-f5b7-4f2e-bdce-ede8f175cbd3 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using ArabicSupport;
public class FixArabic3DText : MonoBehaviour {
public bool showTashkeel = true;
public bool useHinduNumbers = true;
// Use this for initialization
void Start () {
TextMesh textMesh = gameObject.GetComponent<TextMesh>();
string fixedFixed = ArabicFixer.Fix(textMesh.text, showTashkeel, useHinduNumbers);
gameObject.GetComponent<TextMesh>().text = fixedFixed;
Debug.Log(fixedFixed);
}
}
```
Make var name more descriptive | ```c#
using UnityEngine;
using System.Collections;
using ArabicSupport;
public class FixArabic3DText : MonoBehaviour {
public bool showTashkeel = true;
public bool useHinduNumbers = true;
// Use this for initialization
void Start () {
TextMesh textMesh = gameObject.GetComponent<TextMesh>();
string fixedText = ArabicFixer.Fix(textMesh.text, showTashkeel, useHinduNumbers);
gameObject.GetComponent<TextMesh>().text = fixedText;
Debug.Log(fixedFixed);
}
}
``` |
0d48b88f-ebc7-44ec-bdad-da6c01318d3c | {
"language": "C#"
} | ```c#
using PvcCore;
using System.Collections.Generic;
using System.IO;
namespace PvcPlugins
{
public class PvcLess : PvcPlugin
{
public override string[] SupportedTags
{
get
{
return new string[] { ".less" };
}
}
public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
{
var lessEngine = new dotless.Core.LessEngine();
var resultStreams = new List<PvcStream>();
foreach (var inputStream in inputStreams)
{
var lessContent = inputStream.ToString();
var cssContent = lessEngine.TransformToCss(lessContent, "");
var resultStream = PvcUtil.StringToStream(cssContent, inputStream.StreamName);
resultStreams.Add(resultStream);
}
return resultStreams;
}
}
}
```
Rename file to .css for new stream | ```c#
using PvcCore;
using System.Collections.Generic;
using System.IO;
namespace PvcPlugins
{
public class PvcLess : PvcPlugin
{
public override string[] SupportedTags
{
get
{
return new string[] { ".less" };
}
}
public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
{
var lessEngine = new dotless.Core.LessEngine();
var resultStreams = new List<PvcStream>();
foreach (var inputStream in inputStreams)
{
var lessContent = inputStream.ToString();
var cssContent = lessEngine.TransformToCss(lessContent, "");
var newStreamName = Path.Combine(Path.GetDirectoryName(inputStream.StreamName), Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".css");
var resultStream = PvcUtil.StringToStream(cssContent, newStreamName);
resultStreams.Add(resultStream);
}
return resultStreams;
}
}
}
``` |
14146b64-4611-4a0f-8afa-d80827ef58a6 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Reflection;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
if (obj.GetType().Namespace != "Castle.Proxies")
{
return obj;
}
var targetField = obj.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.FirstOrDefault(f => f.Name == "__target");
if (targetField == null)
{
return obj;
}
return targetField.GetValue(obj);
}
}
}
```
Replace reflection to call API. | ```c#
using Castle.DynamicProxy;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
return ProxyUtil.GetUnproxiedInstance(obj);
}
}
}
``` |
2240e913-0cd9-4924-bc1c-75deb4c6ddd1 | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
namespace DrawIt
{
public static class FontHelpers
{
public static Font GetHeaderFont()
{
float fontSize = Configuration.GetSettingOrDefault<float>(Constants.Application.Header.FontSize, float.TryParse, Constants.Application.Defaults.HeaderTextSize);
string fontName = Configuration.GetSetting(Constants.Application.Header.FontName) ?? "Calibri";
FontStyle fontStyle = Configuration.GetSettingOrDefault<FontStyle>(Constants.Application.Header.FontStyle, Enum.TryParse<FontStyle>, FontStyle.Regular);
return new Font(fontName, fontSize, fontStyle);
}
}
}
```
Change the default font for the header. | ```c#
using System;
using System.Drawing;
namespace DrawIt
{
public static class FontHelpers
{
public static Font GetHeaderFont()
{
float fontSize = Configuration.GetSettingOrDefault<float>(Constants.Application.Header.FontSize, float.TryParse, Constants.Application.Defaults.HeaderTextSize);
string fontName = Configuration.GetSetting(Constants.Application.Header.FontName) ?? "Segoe Script";
FontStyle fontStyle = Configuration.GetSettingOrDefault<FontStyle>(Constants.Application.Header.FontStyle, Enum.TryParse<FontStyle>, FontStyle.Regular);
return new Font(fontName, fontSize, fontStyle);
}
}
}
``` |
4c681053-d846-4e8e-9640-c4cb66647782 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using Giles.Core.Utility;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
}```
Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
if (filters.Count() == 0)
remoteTestRunner.Run(listener);
else
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
}``` |
7064bd64-6d37-4adf-81da-f5ca7c3bff21 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Arkivverket.Arkade.Core.Base
{
public class ArchiveXmlUnit
{
public ArchiveXmlFile File { get; }
public List<ArchiveXmlSchema> Schemas { get; }
public ArchiveXmlUnit(ArchiveXmlFile file, List<ArchiveXmlSchema> schemas)
{
File = file;
Schemas = schemas;
}
public ArchiveXmlUnit(ArchiveXmlFile file, ArchiveXmlSchema schema)
: this(file, new List<ArchiveXmlSchema> {schema})
{
}
public bool AllFilesExists()
{
return !GetMissingFiles().Any();
}
public IEnumerable<string> GetMissingFiles()
{
var missingFiles = new List<string>();
if (!File.Exists)
missingFiles.Add(File.FullName);
missingFiles.AddRange(
from schema in
from schema in Schemas
where schema.IsUserProvided()
select (UserProvidedXmlSchema) schema
where !schema.FileExists
select schema.FullName
);
return missingFiles;
}
}
}
```
Use name only for reporting missing file | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Arkivverket.Arkade.Core.Base
{
public class ArchiveXmlUnit
{
public ArchiveXmlFile File { get; }
public List<ArchiveXmlSchema> Schemas { get; }
public ArchiveXmlUnit(ArchiveXmlFile file, List<ArchiveXmlSchema> schemas)
{
File = file;
Schemas = schemas;
}
public ArchiveXmlUnit(ArchiveXmlFile file, ArchiveXmlSchema schema)
: this(file, new List<ArchiveXmlSchema> {schema})
{
}
public bool AllFilesExists()
{
return !GetMissingFiles().Any();
}
public IEnumerable<string> GetMissingFiles()
{
var missingFiles = new List<string>();
if (!File.Exists)
missingFiles.Add(File.Name);
missingFiles.AddRange(
from schema in
from schema in Schemas
where schema.IsUserProvided()
select (UserProvidedXmlSchema) schema
where !schema.FileExists
select schema.FullName
);
return missingFiles;
}
}
}
``` |
a8fb2d19-5766-4731-9757-3611d007698c | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utils.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of a field in an enumeration. If there is no
/// description attribute, the raw name of the field is provided.
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
}
```
Tweak for .net Standard 1.1 compatibility | ```c#
using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utils.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of a field in an enumeration. If there is no
/// description attribute, the raw name of the field is provided.
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetRuntimeField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
}
``` |
e81171a5-f375-4a89-ac1c-ddc0f375f9ac | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vikekh.Stepbot
{
class Program
{
static void Main(string[] args)
{
}
}
}
```
Test receive and send message | ```c#
using SlackAPI;
using System;
using System.Threading;
namespace Vikekh.Stepbot
{
class Program
{
static void Main(string[] args)
{
var botAuthToken = "";
var userAuthToken = "";
var name = "@stepdot";
var age = (new DateTime(2017, 1, 18) - DateTime.Now).Days / 365.0;
var ageString = age.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
var version = "0.1.0";
var mommy = "@vem";
ManualResetEventSlim clientReady = new ManualResetEventSlim(false);
SlackSocketClient client = new SlackSocketClient(botAuthToken);
client.Connect((connected) =>
{
// This is called once the client has emitted the RTM start command
clientReady.Set();
}, () =>
{
// This is called once the RTM client has connected to the end point
});
client.OnMessageReceived += (message) =>
{
// Handle each message as you receive them
Console.WriteLine(message.text);
var textData = string.Format("hello w0rld my name is {0} I am {1} years old and my version is {2} and my mommy is {3}", name, ageString, version, mommy);
client.SendMessage((x) => { }, message.channel, textData);
};
clientReady.Wait();
Console.ReadLine();
}
}
}
``` |
7f56b890-6762-4dd4-b2ca-478f2906bb07 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using TimeSeries;
using TimeSeriesService.Client.TimeSeriesReference;
namespace TimeSeriesService.Client
{
class Program
{
static void Main()
{
var proxy = new TimeSeriesServiceClient();
var oneDataPoint = new List<DataPoint>
{
new DataPoint()
}.ToArray();
var oneDataPointResult = proxy.New(oneDataPoint);
Console.WriteLine("Irregular: {0}", oneDataPointResult);
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
```
Add additional functional test cases. | ```c#
using System;
using System.Collections.Generic;
using TimeSeries;
using TimeSeriesService.Client.TimeSeriesReference;
namespace TimeSeriesService.Client
{
class Program
{
static void Main()
{
var proxy = new TimeSeriesServiceClient();
var oneDataPoint = new List<DataPoint>
{
new DataPoint()
}.ToArray();
var oneDataPointResult = proxy.New(oneDataPoint);
Console.WriteLine("One data point: {0}", oneDataPointResult);
var twoDataPoints = new List<DataPoint>
{
new DataPoint(),
new DataPoint()
}.ToArray();
var twoDataPointsResult = proxy.New(twoDataPoints);
Console.WriteLine("Two data points: {0}", twoDataPointsResult);
var threeDataPoints = new List<DataPoint>
{
new DataPoint(),
new DataPoint(),
new DataPoint()
}.ToArray();
var threeDataPointsResult = proxy.New(threeDataPoints);
Console.WriteLine("Three data points: {0}",
threeDataPointsResult);
Console.WriteLine();
Console.WriteLine("--");
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
``` |
4f7c0805-a7d3-4041-a989-b32818ec087f | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.Core.EntityFramework
{
public class ScopeStore : IScopeStore
{
private readonly string _connectionString;
public ScopeStore(string connectionString)
{
_connectionString = connectionString;
}
public Task<IEnumerable<Models.Scope>> GetScopesAsync()
{
using (var db = new CoreDbContext(_connectionString))
{
var scopes = db.Scopes
.Include("ScopeClaims")
.ToArray();
var models = scopes.ToList().Select(x => x.ToModel());
return Task.FromResult(models);
}
}
}
}
```
Remove redundant LINQ method call | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.Core.EntityFramework
{
public class ScopeStore : IScopeStore
{
private readonly string _connectionString;
public ScopeStore(string connectionString)
{
_connectionString = connectionString;
}
public Task<IEnumerable<Models.Scope>> GetScopesAsync()
{
using (var db = new CoreDbContext(_connectionString))
{
var scopes = db.Scopes
.Include("ScopeClaims");
var models = scopes.ToList().Select(x => x.ToModel());
return Task.FromResult(models);
}
}
}
}
``` |
c301fea1-46dd-448d-847a-cd557033ab52 | {
"language": "C#"
} | ```c#
namespace Mappy.Util.ImageSampling
{
using System.Drawing;
public class NearestNeighbourWrapper : IPixelImage
{
private readonly IPixelImage source;
public NearestNeighbourWrapper(IPixelImage source, int width, int height)
{
this.source = source;
this.Width = width;
this.Height = height;
}
public int Width { get; private set; }
public int Height { get; private set; }
public Color this[int x, int y]
{
get
{
int imageX = (int)((x / (float)this.Width) * this.source.Width);
int imageY = (int)((y / (float)this.Height) * this.source.Height);
return this.source[imageX, imageY];
}
}
}
}
```
Fix small offset in low quality minimap image | ```c#
namespace Mappy.Util.ImageSampling
{
using System.Drawing;
public class NearestNeighbourWrapper : IPixelImage
{
private readonly IPixelImage source;
public NearestNeighbourWrapper(IPixelImage source, int width, int height)
{
this.source = source;
this.Width = width;
this.Height = height;
}
public int Width { get; private set; }
public int Height { get; private set; }
public Color this[int x, int y]
{
get
{
// sample at the centre of each pixel
float ax = x + 0.5f;
float ay = y + 0.5f;
int imageX = (int)((ax / this.Width) * this.source.Width);
int imageY = (int)((ay / this.Height) * this.source.Height);
return this.source[imageX, imageY];
}
}
}
}
``` |
d384e497-bede-46b0-81ee-8b651fb509ae | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NiceIO;
using NUnit.Framework;
using SaferMutex.Tests.BaseSuites;
namespace SaferMutex.Tests.FileBased
{
[TestFixture]
public class ThreadedStressTestsV2 : BaseThreadedStressTests
{
protected override ISaferMutexMutex CreateMutexImplementation(bool initiallyOwned, string name, out bool owned, out bool createdNew)
{
return new SaferMutex.FileBased(initiallyOwned, name, Scope.CurrentProcess, out owned, out createdNew, _tempDirectory.ToString());
}
}
}
```
Fix stress test not creating v2 | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NiceIO;
using NUnit.Framework;
using SaferMutex.Tests.BaseSuites;
namespace SaferMutex.Tests.FileBased
{
[TestFixture]
public class ThreadedStressTestsV2 : BaseThreadedStressTests
{
protected override ISaferMutexMutex CreateMutexImplementation(bool initiallyOwned, string name, out bool owned, out bool createdNew)
{
return new SaferMutex.FileBased2(initiallyOwned, name, Scope.CurrentProcess, out owned, out createdNew, _tempDirectory.ToString());
}
}
}
``` |
2c0466ec-b8d5-442a-818e-f7b87bf7f3cd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hanc.AspNetAPI
{
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and ValuesController.cs for implimentation code
/// </summary>
public class SecretOptions
{
public SecretOptions()
{
MacSecret = "default_secret";
}
public string MacSecret { get; set; }
public string ApiKey { get; set; }
}
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and HelloController.cs for implimentation code
/// </summary>
public class HelloOptions
{
public HelloOptions()
{
HelloValue = "...";
}
public string HelloValue { get; set; }
}
}
```
Change ApiKey to AppId add RequireApiAuthToken | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hanc.AspNetAPI
{
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and ValuesController.cs for implimentation code
/// </summary>
public class SecretOptions
{
public SecretOptions()
{
MacSecret = "default_secret";
}
public string MacSecret { get; set; }
public string AppId { get; set; }
public bool RequireApiAuthToken { get; set; }
}
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and HelloController.cs for implimentation code
/// </summary>
public class HelloOptions
{
public HelloOptions()
{
HelloValue = "...";
}
public string HelloValue { get; set; }
}
}
``` |
25318acc-9ea3-4677-8755-8f191c71d534 | {
"language": "C#"
} | ```c#
using Avalonia;
namespace Sandbox
{
public class Program
{
static void Main(string[] args)
{
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.StartWithClassicDesktopLifetime(args);
}
}
}
```
Make the designer work in the sandbox project. | ```c#
using Avalonia;
namespace Sandbox
{
public class Program
{
static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
}
``` |
8cc68be6-2291-4264-94b0-015b87ef4f10 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using DataReader.BusinessLogic;
using DataReader.Models;
namespace DataReader.Controllers
{
[RoutePrefix("api")]
public class NameQueryController : ApiController
{
private readonly INameBusinessLogic _nameBusinessLogic;
public NameQueryController(INameBusinessLogic nameBusinessLogic)
{
_nameBusinessLogic = nameBusinessLogic;
}
[Route("fullName/{id}")]
[HttpGet]
public async Task<IHttpActionResult> GetData(string id)
{
var result = default(NameDTO);
try
{
result = _nameBusinessLogic.GetById(id);
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
}
}```
Add GET All Names endpoint | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using DataReader.BusinessLogic;
using DataReader.Models;
namespace DataReader.Controllers
{
[RoutePrefix("api")]
public class NameQueryController : ApiController
{
private readonly INameBusinessLogic _nameBusinessLogic;
public NameQueryController(INameBusinessLogic nameBusinessLogic)
{
_nameBusinessLogic = nameBusinessLogic;
}
[Route("fullName/{id}")]
[HttpGet]
public IHttpActionResult GetName(string id)
{
var result = default(NameDTO);
try
{
result = _nameBusinessLogic.GetById(id);
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
[Route("fullName")]
[HttpGet]
public IHttpActionResult GetAllNames()
{
var result = default(string[]);
try
{
result = _nameBusinessLogic.GetAllNameIds();
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
}
}``` |
cb15dfe4-a53b-4133-b9ea-044f4706cf58 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Microsoft.Practices.ObjectBuilder2;
namespace SignInCheckIn.Models.DTO
{
public class ParticipantDto
{
public int EventParticipantId { get; set; }
public int ParticipantId { get; set; }
public int ContactId { get; set; }
public int HouseholdId { get; set; }
public int HouseholdPositionId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public bool Selected { get; set; } = false;
public int ParticipationStatusId { get; set; }
public int? AssignedRoomId { get; set; }
public string AssignedRoomName { get; set; }
public int? AssignedSecondaryRoomId { get; set; } // adventure club field
public string AssignedSecondaryRoomName { get; set; } // adventure club field
public string CallNumber
{
get
{
var c = $"0000{EventParticipantId}";
return c.Substring(c.Length - 4);
}
}
}
}```
Add TODO on fake CallNumber | ```c#
using System;
using System.Linq;
using Microsoft.Practices.ObjectBuilder2;
namespace SignInCheckIn.Models.DTO
{
public class ParticipantDto
{
public int EventParticipantId { get; set; }
public int ParticipantId { get; set; }
public int ContactId { get; set; }
public int HouseholdId { get; set; }
public int HouseholdPositionId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public bool Selected { get; set; } = false;
public int ParticipationStatusId { get; set; }
public int? AssignedRoomId { get; set; }
public string AssignedRoomName { get; set; }
public int? AssignedSecondaryRoomId { get; set; } // adventure club field
public string AssignedSecondaryRoomName { get; set; } // adventure club field
public string CallNumber
{
// TODO Faking out a call number for now (last 4 of EventParticipantId), eventually need to store a real call number on Event Participant
get
{
var c = $"0000{EventParticipantId}";
return c.Substring(c.Length - 4);
}
}
}
}``` |
3890f860-78f1-41fc-b7ba-97ee35a30b25 | {
"language": "C#"
} | ```c#
using MultiMiner.Xgminer.Api.Parsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public class ApiContext
{
private TcpClient tcpClient;
public ApiContext(int port)
{
tcpClient = new TcpClient("127.0.0.1", port);
}
public List<DeviceInformation> GetDeviceInformation()
{
string textResponse = GetResponse(ApiVerb.Devs);
List<DeviceInformation> result = new List<DeviceInformation>();
DeviceInformationParser.ParseTextForDeviceInformation(textResponse, result);
return result;
}
public void QuitMining()
{
GetResponse(ApiVerb.Quit);
}
private string GetResponse(string apiVerb)
{
NetworkStream stream = tcpClient.GetStream();
Byte[] request = System.Text.Encoding.ASCII.GetBytes(apiVerb);
stream.Write(request, 0, request.Length);
Byte[] responseBuffer = new Byte[4096];
string response = string.Empty;
int bytesRead = stream.Read(responseBuffer, 0, responseBuffer.Length);
response = System.Text.Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
return response;
}
}
}
```
Improve TCP reading code to read more than 4096 bytes if available | ```c#
using MultiMiner.Xgminer.Api.Parsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public class ApiContext
{
private TcpClient tcpClient;
public ApiContext(int port)
{
tcpClient = new TcpClient("127.0.0.1", port);
}
public List<DeviceInformation> GetDeviceInformation()
{
string textResponse = GetResponse(ApiVerb.Devs);
List<DeviceInformation> result = new List<DeviceInformation>();
DeviceInformationParser.ParseTextForDeviceInformation(textResponse, result);
return result;
}
public void QuitMining()
{
GetResponse(ApiVerb.Quit);
}
private string GetResponse(string apiVerb)
{
NetworkStream tcpStream = tcpClient.GetStream();
Byte[] request = Encoding.ASCII.GetBytes(apiVerb);
tcpStream.Write(request, 0, request.Length);
Byte[] responseBuffer = new Byte[4096];
string response = string.Empty;
do
{
int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length);
response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
} while (tcpStream.DataAvailable);
return response;
}
}
}
``` |
dcc77d17-ee95-4543-9c54-0f7d3a799839 | {
"language": "C#"
} | ```c#
namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
}
```
Add Rotate methods contributed by CLA signers | ```c#
using Mapsui.Utilities;
namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="centerX">X coordinate of point about which to rotate</param>
/// <param name="centerY">Y coordinate of point about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, double centerX, double centerY)
{
// translate this point back to the center
var newX = X - centerX;
var newY = Y - centerY;
// rotate the values
var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees);
// translate back to original reference frame
newX = p.X + centerX;
newY = p.Y + centerY;
return new MPoint(newX, newY);
}
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="center">MPoint about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, MPoint center)
{
return Rotate(degrees, center.X, center.Y);
}
}
``` |
a5f3d21e-0c82-4f5b-85d7-5b0c0d9f6864 | {
"language": "C#"
} | ```c#
using System.Reflection;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.StaticFiles;
namespace Glimpse.Server.Resources
{
public class ClientResource : IResourceStartup
{
public void Configure(IResourceBuilder resourceBuilder)
{
// TODO: Add HTTP Caching
var options = new FileServerOptions();
options.RequestPath = "/Client";
options.EnableDefaultFiles = false;
options.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
options.FileProvider = new EmbeddedFileProvider(typeof(ClientResource).GetTypeInfo().Assembly, "Glimpse.Server.Resources.Embed.Client");
resourceBuilder.AppBuilder.UseFileServer(options);
}
public ResourceType Type => ResourceType.Client;
}
}```
Fix internal path for embedded client | ```c#
using System.Reflection;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.StaticFiles;
namespace Glimpse.Server.Resources
{
public class ClientResource : IResourceStartup
{
public void Configure(IResourceBuilder resourceBuilder)
{
// TODO: Add HTTP Caching
var options = new FileServerOptions();
options.RequestPath = "/Client";
options.EnableDefaultFiles = false;
options.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
options.FileProvider = new EmbeddedFileProvider(typeof(ClientResource).GetTypeInfo().Assembly, "Glimpse.Server.Resources.Embeded.Client");
resourceBuilder.AppBuilder.UseFileServer(options);
}
public ResourceType Type => ResourceType.Client;
}
}``` |
2936b979-c0c0-4b55-822f-98735e6f6e03 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Version.cs" company="">
// Copyright 2013 Thomas PIERRAIN
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
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.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")]```
Update the version number to 1.4.0 | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Version.cs" company="">
// Copyright 2013 Thomas PIERRAIN
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]``` |
4e77fb09-5788-4c26-8c4a-0fdb93514feb | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using Bit.Model.Dtos;
namespace Bit.OData.ODataControllers
{
public class JobsInfoController : DtoController<JobInfoDto>
{
public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; }
[Get]
public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken);
return new JobInfoDto
{
Id = jobInfo.Id,
CreatedAt = jobInfo.CreatedAt,
State = jobInfo.State
};
}
}
}
```
Check background job worker before using that in jobs info controller | ```c#
using Bit.Core.Contracts;
using Bit.Core.Models;
using Bit.Model.Dtos;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Bit.OData.ODataControllers
{
public class JobsInfoController : DtoController<JobInfoDto>
{
public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; }
[Get]
public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (BackgroundJobWorker == null)
throw new InvalidOperationException("No background job worker is configured");
JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken);
return new JobInfoDto
{
Id = jobInfo.Id,
CreatedAt = jobInfo.CreatedAt,
State = jobInfo.State
};
}
}
}
``` |
68e1a536-c21c-463d-8195-ad38c47e9be7 | {
"language": "C#"
} | ```c#
using System.Windows;
namespace Kinugasa.UI
{
/// <summary>
/// Proxy class for binding sorce.
/// </summary>
public class BindingProxy : Freezable
{
/// <summary>
/// Define dependencyProperty.
/// </summary>
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
/// <summary>
/// Create freezable object's instance.
/// </summary>
/// <returns></returns>
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
/// <summary>
/// Proxy property.
/// </summary>
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
}
}
```
Add xml comment on namespace. | ```c#
using System.Windows;
/// <summary>
/// Provide userinterface components.
/// </summary>
namespace Kinugasa.UI
{
/// <summary>
/// Proxy class for binding sorce.
/// </summary>
public class BindingProxy : Freezable
{
/// <summary>
/// Define dependencyProperty.
/// </summary>
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
/// <summary>
/// Create freezable object's instance.
/// </summary>
/// <returns></returns>
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
/// <summary>
/// Proxy property.
/// </summary>
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
}
}
``` |
1393dcd7-51b8-4395-b6de-1b4978b57a10 | {
"language": "C#"
} | ```c#
namespace Winium.Desktop.Driver.CommandExecutors
{
#region using
using System.Windows.Automation;
using Winium.Cruciatus.Extensions;
using Winium.StoreApps.Common;
#endregion
internal class IsElementSelectedExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
var controlType = element.GetAutomationPropertyValue<ControlType>(AutomationElement.ControlTypeProperty);
if (controlType.Equals(ControlType.CheckBox))
{
return this.JsonResponse(ResponseStatus.Success, element.ToCheckBox().IsToggleOn);
}
var property = SelectionItemPattern.IsSelectedProperty;
var isSelected = element.GetAutomationPropertyValue<bool>(property);
return this.JsonResponse(ResponseStatus.Success, isSelected);
}
#endregion
}
}
```
Check IsTogglePatternAvailable insted of using ControlType | ```c#
namespace Winium.Desktop.Driver.CommandExecutors
{
#region using
using System.Windows.Automation;
using Winium.Cruciatus.Exceptions;
using Winium.Cruciatus.Extensions;
using Winium.StoreApps.Common;
#endregion
internal class IsElementSelectedExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
var isSelected = false;
try
{
var isTogglePattrenAvailable =
element.GetAutomationPropertyValue<bool>(AutomationElement.IsTogglePatternAvailableProperty);
if (isTogglePattrenAvailable)
{
var toggleStateProperty = TogglePattern.ToggleStateProperty;
var toggleState = element.GetAutomationPropertyValue<ToggleState>(toggleStateProperty);
isSelected = toggleState == ToggleState.On;
}
}
catch (CruciatusException)
{
var selectionItemProperty = SelectionItemPattern.IsSelectedProperty;
isSelected = element.GetAutomationPropertyValue<bool>(selectionItemProperty);
}
return this.JsonResponse(ResponseStatus.Success, isSelected);
}
#endregion
}
}
``` |
c3f3caad-1cdd-4ca6-9a1f-243f78187af1 | {
"language": "C#"
} | ```c#
using System.Runtime.InteropServices;
using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("MeepMeep (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("MeepMeep (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .Net client.")]
[assembly: AssemblyCompany("Daniel Wertheim")]
[assembly: AssemblyCopyright("Copyright © 2013 Daniel Wertheim")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.1.0.*")]
[assembly: AssemblyFileVersion("0.1.0")]
```
Update AssemblyInfo to reference Couchbase as owner / copyright | ```c#
using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("MeepMeep (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("MeepMeep (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .NET client.")]
[assembly: AssemblyCompany("Couchbase")]
[assembly: AssemblyCopyright("Copyright © 2017 Couchbase")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.1.0.*")]
[assembly: AssemblyFileVersion("0.1.0")]
``` |
e4047d61-5ebb-4e83-8bcc-886f3eaa018a | {
"language": "C#"
} | ```c#
@model List<Catalog>
<div class="am-panel-hd">Catalog</div>
<div class="am-panel-bd">
@foreach (var catalog in Model)
{
<a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url">
@catalog.Title
<span class="am-badge am-badge-secondary am-round">@catalog.Posts.Count()</span>
</a>
}
</div>```
Update catalog list item style | ```c#
@model List<Catalog>
<div class="am-panel-hd">Catalog</div>
<div class="am-panel-bd">
@foreach (var catalog in Model)
{
<a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url">
@catalog.Title
<span class="am-badge am-badge-success am-round">@catalog.Posts.Count()</span>
</a>
}
</div>``` |
0cdb1237-a6cd-4d44-8531-58f7eab4f463 | {
"language": "C#"
} | ```c#
using Buddy.Swtor.Objects;
namespace DefaultCombat.Extensions
{
public static class TorCharacterExtensions
{
public static bool ShouldDispel(this TorCharacter target, string debuffName)
{
if (target == null)
return false;
return target.HasDebuff(debuffName);
}
}
}
```
Return whether the target has any dispellable debuff | ```c#
using System.Collections.Generic;
using System.Linq;
using Buddy.Swtor.Objects;
namespace DefaultCombat.Extensions
{
public static class TorCharacterExtensions
{
private static readonly IReadOnlyList<string> _dispellableDebuffs = new List<string>
{
"Hunting Trap",
"Burning (Physical)"
};
public static bool ShouldDispel(this TorCharacter target)
{
return target != null && _dispellableDebuffs.Any(target.HasDebuff);
}
}
}
``` |
71ade2df-3fff-4ec6-a8d5-871ca6f56121 | {
"language": "C#"
} | ```c#
@using Orchard.ContentManagement.MetaData.Models
@{
var containerId = (int) Model.ContainerId;
var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes;
}
<div class="item-properties actions">
<p>
@Html.ActionLink(T("{0} Properties", Html.Raw((string)Model.ContainerDisplayName)).Text, "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl })
</p>
</div>
<div class="manage">
@if (itemContentTypes.Any()) {
foreach (var contentType in itemContentTypes) {
@Html.ActionLink(T("New {0}", Html.Raw(contentType.DisplayName)).Text, "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" })
}
}
else {
@Html.ActionLink(T("New Content").ToString(), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" })
}
<a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a>
</div>
```
Use new ActionLink extension method. | ```c#
@using Orchard.ContentManagement.MetaData.Models
@{
var containerId = (int) Model.ContainerId;
var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes;
}
<div class="item-properties actions">
<p>
@Html.ActionLink(T("{0} Properties", (string)Model.ContainerDisplayName), "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl })
</p>
</div>
<div class="manage">
@if (itemContentTypes.Any()) {
foreach (var contentType in itemContentTypes) {
@Html.ActionLink(T("New {0}", contentType.DisplayName), "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" })
}
}
else {
@Html.ActionLink(T("New Content"), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" })
}
<a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a>
</div>
``` |
fb9090d2-b292-473b-a868-0719db8e469d | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: InternalsVisibleTo("FakeHttpContext.Tests")]
[assembly: AssemblyTitle("FakeHttpContext")]
[assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vadim Zozulya")]
[assembly: AssemblyProduct("FakeHttpContext")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
```
Update package version to 0.1.1 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: InternalsVisibleTo("FakeHttpContext.Tests")]
[assembly: AssemblyTitle("FakeHttpContext")]
[assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vadim Zozulya")]
[assembly: AssemblyProduct("FakeHttpContext")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1.1")]
[assembly: AssemblyInformationalVersion("0.1.1")]
``` |
ba3326cf-3c11-400e-91e5-88b3dc2cd3e6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace Postal.AspNetCore
{
public class EmailServiceOptions
{
public EmailServiceOptions()
{
CreateSmtpClient = () => new SmtpClient(Host, Port)
{
Credentials = new NetworkCredential(UserName, Password),
EnableSsl = EnableSSL
};
}
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSSL { get; set; }
public string FromAddress { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Func<SmtpClient> CreateSmtpClient { get; set; }
}
}
```
Fix create smtpclient with UseDefaultCredentials | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace Postal.AspNetCore
{
public class EmailServiceOptions
{
public EmailServiceOptions()
{
CreateSmtpClient = () => new SmtpClient(Host, Port)
{
UseDefaultCredentials = string.IsNullOrWhiteSpace(UserName),
Credentials = string.IsNullOrWhiteSpace(UserName) ? null : new NetworkCredential(UserName, Password),
EnableSsl = EnableSSL
};
}
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSSL { get; set; }
public string FromAddress { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Func<SmtpClient> CreateSmtpClient { get; set; }
}
}
``` |
e301a03e-dd16-445f-a808-2c4e65b0465e | {
"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;
namespace Microsoft.Cci.Extensions
{
public static class ApiKindExtensions
{
public static bool IsInfrastructure(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
}
}
```
Add helper functions for ApiKind | ```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;
namespace Microsoft.Cci.Extensions
{
public static class ApiKindExtensions
{
public static bool IsInfrastructure(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
public static bool IsNamespace(this ApiKind kind)
{
return kind == ApiKind.Namespace;
}
public static bool IsType(this ApiKind kind)
{
switch (kind)
{
case ApiKind.Interface:
case ApiKind.Delegate:
case ApiKind.Enum:
case ApiKind.Struct:
case ApiKind.Class:
return true;
default:
return false;
}
}
public static bool IsMember(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.Field:
case ApiKind.Property:
case ApiKind.Event:
case ApiKind.Constructor:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
case ApiKind.Method:
return true;
default:
return false;
}
}
public static bool IsAccessor(this ApiKind kind)
{
switch (kind)
{
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
}
}
``` |
dcb906cf-e9aa-4093-a5bf-2c53380a96da | {
"language": "C#"
} | ```c#
namespace Nancy.JohnnyFive.Sample
{
using System.Collections.Generic;
using System.IO;
using Circuits;
public class SampleModule : NancyModule
{
public SampleModule()
{
Get["/"] = _ =>
{
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<FileNotFoundException>()
.WithCircuitOpenTimeInSeconds(10));
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<KeyNotFoundException>()
.WithCircuitOpenTimeInSeconds(30));
if (this.Request.Query["fileNotFound"] != null)
throw new FileNotFoundException();
if (this.Request.Query["keyNotFound"] != null)
throw new KeyNotFoundException();
return "Hello, World!";
};
Get["/underload"] = _ =>
{
this.CanShortCircuit(new LastGoodResponseUnderLoad()
.WithRequestSampleTimeInSeconds(10)
.WithRequestThreshold(40));
};
}
}
}```
Add under load sample module | ```c#
namespace Nancy.JohnnyFive.Sample
{
using System;
using System.Collections.Generic;
using System.IO;
using Circuits;
public class SampleModule : NancyModule
{
public SampleModule()
{
Get["/"] = _ =>
{
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<FileNotFoundException>()
.WithCircuitOpenTimeInSeconds(10));
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<KeyNotFoundException>()
.WithCircuitOpenTimeInSeconds(30));
if (this.Request.Query["fileNotFound"] != null)
throw new FileNotFoundException();
if (this.Request.Query["keyNotFound"] != null)
throw new KeyNotFoundException();
return "Hello, World!";
};
Get["/underload"] = _ =>
{
this.CanShortCircuit(new NoContentUnderLoadCircuit()
.WithRequestSampleTimeInSeconds(10)
.WithRequestThreshold(5));
return "Under load " + DateTime.Now;
};
}
}
}``` |
615e0f49-a3b1-40fd-8c97-3dc09b5952d4 | {
"language": "C#"
} | ```c#
namespace NEventSocket.Tests.TestSupport
{
public class TimeOut
{
public const int TestTimeOutMs = 30 * 1000;
}
}```
Revert "Try bumping up the test timeout" | ```c#
namespace NEventSocket.Tests.TestSupport
{
public class TimeOut
{
public const int TestTimeOutMs = 10000;
}
}``` |
e55d6050-e49d-4d4e-b5cf-ee9598ea7777 | {
"language": "C#"
} | ```c#
using System;
using DokanNet;
namespace DokanNetMirror
{
internal class Program
{
private static void Main(string[] args)
{
try
{
bool unsafeReadWrite = args.Length > 0 && args[0].Equals("-unsafe", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}");
var mirror = unsafeReadWrite ? new UnsafeMirror("C:") : new Mirror("C:");
mirror.Mount("n:\\", DokanOptions.DebugMode, 5);
Console.WriteLine(@"Success");
}
catch (DokanException ex)
{
Console.WriteLine(@"Error: " + ex.Message);
}
}
}
}```
Allow mirror to accept parameters to specify what to mount and where | ```c#
using System;
using System.Linq;
using DokanNet;
namespace DokanNetMirror
{
internal class Program
{
private const string MirrorKey = "-what";
private const string MountKey = "-where";
private const string UseUnsafeKey = "-unsafe";
private static void Main(string[] args)
{
try
{
var arguments = args
.Select(x => x.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x => x[0], x => x.Length > 1 ? x[1] as object : true, StringComparer.OrdinalIgnoreCase);
var mirrorPath = arguments.ContainsKey(MirrorKey)
? arguments[MirrorKey] as string
: @"C:\";
var mountPath = arguments.ContainsKey(MountKey)
? arguments[MountKey] as string
: @"N:\";
var unsafeReadWrite = arguments.ContainsKey(UseUnsafeKey);
Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}");
var mirror = unsafeReadWrite
? new UnsafeMirror(mirrorPath)
: new Mirror(mirrorPath);
mirror.Mount(mountPath, DokanOptions.DebugMode, 5);
Console.WriteLine(@"Success");
}
catch (DokanException ex)
{
Console.WriteLine(@"Error: " + ex.Message);
}
}
}
}``` |
1beba74e-1efd-4cab-bd70-cc013b758047 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class MetallKeferController : MonoBehaviour {
public GameObject gameControllerObject;
private GameController gameController;
private GameObject[] towerBasesBuildable;
void Start () {
this.gameController = this.gameControllerObject.GetComponent<GameController>();
this.FindInititalWaypoint ();
}
void FindInititalWaypoint() {
}
}
```
Add prototype movement for MetallKefer | ```c#
using UnityEngine;
using System.Collections;
public class MetallKeferController : MonoBehaviour {
public GameObject gameControllerObject;
private GameController gameController;
private GameObject[] towerBasesBuildable;
private GameObject nextWaypiont;
private int currentWaypointIndex = 0;
private int movementSpeed = 2;
private float step = 10f;
void Start () {
this.gameController = this.gameControllerObject.GetComponent<GameController>();
this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex];
}
void Update() {
this.moveToNextWaypoint ();
}
void SetNextWaypoint() {
if (this.currentWaypointIndex < this.gameController.getWaypoints ().Length - 1) {
this.currentWaypointIndex += 1;
this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex];
this.nextWaypiont.GetComponent<Renderer> ().material.color = this.getRandomColor();
}
}
private Color getRandomColor() {
Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f );
return newColor;
}
private void moveToNextWaypoint() {
float step = movementSpeed * Time.deltaTime;
this.transform.LookAt (this.nextWaypiont.transform);
this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step);
this.SetNextWaypoint ();
}
}
``` |
48439592-6c53-4697-a9ca-6c6b1c8a198c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Plugin.MySqlLogger
{
class SessionCache
{
private Dictionary<int, string> m_cache;
public SessionCache()
{
m_cache = new Dictionary<int, string>();
}
public void Add(int sessId, string userName)
{
lock(this)
{
if (!m_cache.ContainsKey(sessId))
m_cache.Add(sessId, userName);
else
m_cache[sessId] = userName;
}
}
public string Get(int sessId)
{
if (m_cache.ContainsKey(sessId))
return m_cache[sessId];
return "";
}
public void Clear()
{
lock (this)
{
m_cache.Clear();
}
}
}
}
```
Add lock around Get in session cache, and add default "unknown" username. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Plugin.MySqlLogger
{
class SessionCache
{
private Dictionary<int, string> m_cache;
public SessionCache()
{
m_cache = new Dictionary<int, string>();
}
public void Add(int sessId, string userName)
{
lock(this)
{
if (!m_cache.ContainsKey(sessId))
m_cache.Add(sessId, userName);
else
m_cache[sessId] = userName;
}
}
public string Get(int sessId)
{
string result = "--Unknown--";
lock (this)
{
if (m_cache.ContainsKey(sessId))
result = m_cache[sessId];
}
return result;
}
public void Clear()
{
lock (this)
{
m_cache.Clear();
}
}
}
}
``` |
d52eb2b7-be1c-4109-8632-aab05b3d7c8f | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Shop.Core.BaseObjects;
using Shop.Core.Interfaces;
namespace Shop.Core.Entites
{
public class Order : LifetimeBase, IReferenceable<Order>
{
[Key]
public int OrderId { get; set; }
public string OrderReference { get; set; }
public List<OrderProduct> Products { get; set; }
public DiscountCode DiscountCode { get; set; }
public ShippingDetails ShippingMethod { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
public Order CreateReference(IReferenceGenerator referenceGenerator)
{
OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength);
return this;
}
}
}```
Add order constructor and Payment | ```c#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Shop.Core.BaseObjects;
using Shop.Core.Interfaces;
namespace Shop.Core.Entites
{
public class Order : LifetimeBase, IReferenceable<Order>
{
[Key]
public int OrderId { get; set; }
public string OrderReference { get; set; }
public List<ProductConfiguration> Products { get; set; }
public DiscountCode DiscountCode { get; set; }
public ShippingDetails ShippingMethod { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
public Payment Payment { get; set; }
public Order()
{
OrderId = 0;
OrderReference = string.Empty;
Products = new List<ProductConfiguration>();
}
public Order CreateReference(IReferenceGenerator referenceGenerator)
{
OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength);
return this;
}
}
}``` |
46578cc4-3ba5-4c81-977e-fd702db324a6 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
```
Make DllImport exclusive to iOS | ```c#
using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
#if UNITY_IOS
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
#endif
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
``` |
fbdf9fc7-2648-4a17-bda2-a2aaf8cbca45 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
[TestMethod]
public void TestProduction()
{
IFactoryMethod factory = new IncompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
try
{
factory.Build(ProductType.Baz);
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
// Try again with a complete factory
factory = new CompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(BazProduct));
}
}
}
```
Split tests and deduplicated code | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
using System.Collections.Generic;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
private Dictionary<ProductType, Type> ProductionProvider()
{
var products = new Dictionary<ProductType, Type>();
products.Add(ProductType.Foo, typeof(FooProduct));
products.Add(ProductType.Bar, typeof(BarProduct));
products.Add(ProductType.Baz, typeof(BazProduct));
return products;
}
[TestMethod]
public void TestFactoryProducesProducts()
{
var factory = new CompleteFactory();
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
}
[TestMethod]
public void TestIncompleteFactoryThrowsException()
{
IFactoryMethod factory = new IncompleteFactory();
try
{
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
// Must not get here
Assert.Fail();
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
}
}
}
``` |
108d7057-b77c-435a-8d58-8a274cc4059e | {
"language": "C#"
} | ```c#
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.MicroKernel.Lifestyle
{
using System;
/// <summary>
/// Summary description for SingletonLifestyleManager.
/// </summary>
[Serializable]
public class SingletonLifestyleManager : AbstractLifestyleManager
{
private Object instance;
public override void Dispose()
{
if (instance != null) base.Release( instance );
}
public override object Resolve(CreationContext context)
{
lock(ComponentActivator)
{
if (instance == null)
{
instance = base.Resolve(context);
}
}
return instance;
}
public override void Release( object instance )
{
// Do nothing
}
}
}
```
Use double checked lock to improve performance. | ```c#
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.MicroKernel.Lifestyle
{
using System;
/// <summary>
/// Summary description for SingletonLifestyleManager.
/// </summary>
[Serializable]
public class SingletonLifestyleManager : AbstractLifestyleManager
{
private volatile Object instance;
public override void Dispose()
{
if (instance != null) base.Release( instance );
}
public override object Resolve(CreationContext context)
{
if (instance == null)
{
lock (ComponentActivator)
{
if (instance == null)
{
instance = base.Resolve(context);
}
}
}
return instance;
}
public override void Release( object instance )
{
// Do nothing
}
}
}
``` |
1e42a45a-c474-41fc-b3d0-2f1d41d71737 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
public string Execute(List<string> parameters)
{
throw new NotImplementedException();
}
}
}```
Create JSon Reader command is ready | ```c#
using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
using MovieTheater.Framework.Core.Providers;
using MovieTheater.Framework.Core.Providers.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
private IReader reader;
private IWriter writer;
public CreateJsonReaderCommand()
{
this.reader = new ConsoleReader();
this.writer = new ConsoleWriter();
}
public string Execute(List<string> parameters)
{
var jsonReader = new JsonReader(reader, writer);
jsonReader.Read();
return "Successfully read json file!";
}
}
}``` |
d99a59d9-091f-49bb-bcda-7edc9fb1505c | {
"language": "C#"
} | ```c#
using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
public void UnapplyAll();
}
}
```
Remove extra `public`s from interface | ```c#
using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
void UnapplyAll();
}
}
``` |
a37bf3c4-d095-45ad-b363-0c119d3d7348 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: AssemblyDescription("Autofac Castle.DynamicProxy2 Integration")]
[assembly: ComVisible(false)]```
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;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: ComVisible(false)]``` |
f760628e-44ca-4694-b28a-c5660709f127 | {
"language": "C#"
} | ```c#
namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
```
Add webhooks to the client interface. | ```c#
namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets access to the webhooks resource of the SparkPost API.
/// </summary>
IWebhooks Webhooks { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
``` |
8b6484c0-69b2-4161-baec-6d691429df7f | {
"language": "C#"
} | ```c#
using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenBy(s => s.Rank)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
}```
Sort battle roster by group, then by position desc | ```c#
using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenByDescending(s => s.Position)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
}``` |
06c7b58b-5914-497e-a9ce-869381180740 | {
"language": "C#"
} | ```c#
using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
throw new NotImplementedException("ImportShaderStage $basic");
}
if (filename == "$skinned")
{
throw new NotImplementedException("ImportShaderStage $skinned");
}
return next2(filename, type, importer);
}
}
}
```
Return ShaderContent for built-in shader stages. | ```c#
using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$basic\"");
return BuiltinShaders.BasicVertexShaderContent;
}
if (filename == "$skinned")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$skinned\"");
return BuiltinShaders.SkinnedVertexShaderContent;
}
if (filename == "$fragment")
{
if (type != ShaderType.Fragment)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$fragment\"");
return BuiltinShaders.BuiltinFragmentShaderContent;
}
return next2(filename, type, importer);
}
}
}
``` |
82d486f1-acb0-4cfa-afe6-75528e6387f2 | {
"language": "C#"
} | ```c#
using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}```
Add Public to build target | ```c#
using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
"GenericGraphEditor/Public",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}``` |
60369b6d-5f49-4210-9f48-31308887f9f4 | {
"language": "C#"
} | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
}
}
```
Support listing charges by PaymentIntent id | ```c#
namespace Stripe
{
using System;
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
/// <summary>
/// Only return charges for the customer specified by this customer ID.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// Only return charges that were created by the PaymentIntent specified by this
/// PaymentIntent ID.
/// </summary>
[JsonProperty("payment_intent")]
public string PaymentIntentId { get; set; }
[Obsolete("This parameter is deprecated. Filter the returned list of charges instead.")]
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
/// <summary>
/// Only return charges for this transfer group.
/// </summary>
[JsonProperty("transfer_group")]
public string TransferGroup { get; set; }
}
}
``` |
632cea59-81be-4fe6-924d-ab4bfcfc2d38 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
```
Extend test for Jobs list | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => !string.IsNullOrEmpty(job.Department)));
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
``` |
cffd8d7d-7e97-42ea-86c6-3834a7205cad | {
"language": "C#"
} | ```c#
using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the config.json file inside a sub directory called 'configuration' with the current directory.
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
}```
Revert "Update comment to reflect possible config.json path" | ```c#
using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the configuration file at .\configuration\config.json
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
}``` |
3f8bc3b8-58b0-469b-b4bc-0b4a3256f211 | {
"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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
```
Make CatchStacker testcase more useful | ```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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 512; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f + (i / 2048f * ((i % 10) - 5)), StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
``` |
68d5d8e5-0c3b-4b1f-8ed8-4d983e94886e | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
_msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
```
Remove the nuget environment variable. | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
// Disable this for now
// _msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
``` |
596965d3-4cb9-42fb-b0bf-463ba0fc3976 | {
"language": "C#"
} | ```c#
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container);
return descriptor;
}
}
}```
Fix header behavior for the fixed length types | ```c#
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container)
{
HasHeader = false
};
return descriptor;
}
}
}``` |
e3d52962-84f9-49ed-8d6d-70d1055b6994 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature registration.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of feature registrations.</param>
/// <returns>List of feature registrations.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.Any(i => i.GetType() == typeof(T)))
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
}```
Clean up type checking code | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature list.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of features.</param>
/// <returns>List of features.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.OfType<T>().Any())
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
}``` |
cf8f4156-d7cd-4e6d-8339-91e1eb8683f1 | {
"language": "C#"
} | ```c#
// <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Class-1 Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1,
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
}
}```
Improve Beam-weapon toString to include rating value | ```c#
// <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private const string BaseSystemName = "Beam Battery System";
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
public override string ToString()
{
this.SystemName = $"Class-{this.Rating} {BaseSystemName}";
return base.ToString();
}
}
}``` |
03dea7f0-8d46-4471-a372-4a948294e6d7 | {
"language": "C#"
} | ```c#
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.8.3")]
[assembly: AssemblyFileVersion("0.8.3")]
```
Bump to v0.9 - this is going to be the beta for 1.0 | ```c#
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.9.0")]
[assembly: AssemblyFileVersion("0.9.0")]
``` |
7f9e88c7-8950-4f36-beb3-9181fcd41aa4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Attributes;
using HandlebarsDotNet;
namespace HandlebarsNet.Benchmark
{
public class LargeArray
{
private object _data;
private HandlebarsTemplate<object, object> _default;
[Params(20000, 40000, 80000)]
public int N { get; set; }
[GlobalSetup]
public void Setup()
{
const string template = @"{{#each this}}{{this}}{{/each}}";
_default = Handlebars.Compile(template);
_data = Enumerable.Range(0, N).ToList();
}
[Benchmark]
public void Default() => _default(_data);
}
}```
Use TextWriter overload for template filling. Change was requested by pull request reviewer. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Attributes;
using HandlebarsDotNet;
namespace HandlebarsNet.Benchmark
{
public class LargeArray
{
private object _data;
private HandlebarsTemplate<TextWriter, object, object> _default;
[Params(20000, 40000, 80000)]
public int N { get; set; }
[GlobalSetup]
public void Setup()
{
const string template = @"{{#each this}}{{this}}{{/each}}";
var handlebars = Handlebars.Create();
using (var reader = new StringReader(template))
{
_default = handlebars.Compile(reader);
}
_data = Enumerable.Range(0, N).ToList();
}
[Benchmark]
public void Default() => _default(TextWriter.Null, _data);
}
}``` |
01f838c6-c66d-4451-bad2-4cef6f3f0601 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace AppveyorShieldBadges
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
```
Add error to see if CI is blocking Deployment | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace AppveyorShieldBadges
{
public class Program
{
public static void Main(string[] args)
{
var host = ;new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
``` |
a8a3cd89-631f-420f-b447-1b02f7e2b40f | {
"language": "C#"
} | ```c#
using UIKit;
using Foundation;
namespace CoffeeFilter.iOS
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
const string GoogleMapsAPIKey = "AIzaSyAAOpU0qjK0LBTe2UCCxPQP1iTaSv_Xihw";
public override UIWindow Window { get; set; }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
#if DEBUG
// Xamarin.Insights.Initialize("ef02f98fd6fb47ce8624862ab7625b933b6fb21d");
#else
Xamarin.Insights.Initialize ("8da86f8b3300aa58f3dc9bbef455d0427bb29086");
#endif
// Register Google maps key to use street view
Google.Maps.MapServices.ProvideAPIKey(GoogleMapsAPIKey);
// Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
Xamarin.Calabash.Start();
#endif
return true;
}
}
}```
Use UITest compiler directive instead of ENABLE_TEST_CLOUD | ```c#
using UIKit;
using Foundation;
namespace CoffeeFilter.iOS
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
const string GoogleMapsAPIKey = "AIzaSyAAOpU0qjK0LBTe2UCCxPQP1iTaSv_Xihw";
public override UIWindow Window { get; set; }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
#if DEBUG
// Xamarin.Insights.Initialize("ef02f98fd6fb47ce8624862ab7625b933b6fb21d");
#else
Xamarin.Insights.Initialize ("8da86f8b3300aa58f3dc9bbef455d0427bb29086");
#endif
// Register Google maps key to use street view
Google.Maps.MapServices.ProvideAPIKey(GoogleMapsAPIKey);
// Code to start the Xamarin Test Cloud Agent
#if UITest
Xamarin.Calabash.Start();
#endif
return true;
}
}
}``` |
60f052d1-863b-40f3-940f-f993b8666acb | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
}
}
```
Add a default value for changeset.workitems. | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
public TfsChangesetInfo()
{
Workitems = Enumerable.Empty<ITfsWorkitem>();
}
}
}
``` |
5ede4836-0bbf-4016-9533-9e566443487c | {
"language": "C#"
} | ```c#
using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
```
Improve handling of bad format for intervals | ```c#
using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
if (!builder.IsValid())
throw builder.GetException();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
``` |
c974026f-b9b0-420d-a44d-88e56cea9432 | {
"language": "C#"
} | ```c#
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
{
var dbIsSqlCe = false;
if (databaseSettings?.ProviderName != null)
{
dbIsSqlCe = databaseSettings.ProviderName == Constants.DbProviderNames.SqlCe;
}
var sqlCeDatabaseExists = false;
if (dbIsSqlCe)
{
var parts = databaseSettings.ConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dataSourcePart = parts.FirstOrDefault(x => x.InvariantStartsWith("Data Source="));
if (dataSourcePart != null)
{
var datasource = dataSourcePart.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
var filePath = datasource.Replace("Data Source=", string.Empty);
sqlCeDatabaseExists = File.Exists(filePath);
}
}
// Either the connection details are not fully specified or it's a SQL CE database that doesn't exist yet
if (databaseSettings == null
|| string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) || string.IsNullOrWhiteSpace(databaseSettings.ProviderName)
|| (dbIsSqlCe && sqlCeDatabaseExists == false))
{
return false;
}
return true;
}
}
}
```
Remove custom SQL CE checks from IsConnectionStringConfigured | ```c#
// Copyright (c) Umbraco.
// See LICENSE for more details.
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
=> databaseSettings != null &&
!string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) &&
!string.IsNullOrWhiteSpace(databaseSettings.ProviderName);
}
}
``` |
6715e61d-b6f5-40b1-a7a8-32d766e8061f | {
"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.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable) where T : Drawable
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
```
Remove type constraint for ChildrenOfType<T> | ```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.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable)
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
``` |
c23226a7-e06b-4bef-8961-7e113c8c028c | {
"language": "C#"
} | ```c#
using System;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
```
Add <exception> tags to CreateReader. | ```c#
using System;
using System.IO;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs if <paramref name="address"/> is not a valid address.</exception>
/// <exception cref="EndOfStreamException">Occurs if <paramref name="length"/> is too long.</exception>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
``` |
3a7474ee-c49a-4a87-8a54-87b5ea354520 | {
"language": "C#"
} | ```c#
using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value)
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes);
return hexString;
}
private static string BytesToHexString(byte[] bytes)
{
var result = string.Empty;
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
result += ((char)(n2 - 10 + 'A')).ToString();
}
else
{
result += n2.ToString();
}
if (n1 > 9)
{
result += ((char)(n1 - 10 + 'A')).ToString();
}
else
{
result += n1.ToString();
}
if ((i + 1) != bytes.Length && (i + 1) % 2 == 0)
{
result += "-";
}
}
return result;
}
}
}```
Allow replace separator in crypt helper | ```c#
using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value, char? separator = '-')
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes, separator);
return hexString;
}
private static string BytesToHexString(byte[] bytes, char? separator)
{
var stringBuilder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
stringBuilder.Append((char) n2 - 10 + 'A');
}
else
{
stringBuilder.Append(n2);
}
if (n1 > 9)
{
stringBuilder.Append((char) n1 - 10 + 'A');
}
else
{
stringBuilder.Append(n1);
}
if (separator.HasValue && ((i + 1) != bytes.Length && (i + 1) % 2 == 0))
{
stringBuilder.Append(separator.Value);
}
}
return stringBuilder.ToString();
}
}
}``` |
da656e60-79c7-43d8-b164-d557e78a2e34 | {
"language": "C#"
} | ```c#
using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web.Options;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
}```
Add Options setup registration in DI container | ```c#
using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(null);
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Transient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
}``` |
89eb8e7a-fe72-49b7-b79a-09cd3cab55a0 | {
"language": "C#"
} | ```c#
using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class Repositories
{
public static void Register(IServiceCollection services) {
services.AddSingleton<IAdministratorsRepository, AdministratorsRepository>();
services.AddSingleton<IBookmarksRepository, BookmarksRepository>();
services.AddSingleton<ICommentsRepository, CommentsRepository>();
services.AddSingleton<IFollowersRepository, FollowersRepository>();
services.AddSingleton<ILikesRepository, LikesRepository>();
services.AddSingleton<ILocationsRepository, LocationsRepository>();
services.AddSingleton<IPostsRepository, IPostsRepository>();
services.AddSingleton<IReportsRepository, ReportsRepository>();
services.AddSingleton<ITagsRepository, TagsRepository>();
}
}
}
```
Fix typo in Model-Repositories Service Register | ```c#
using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class ModelRepositories
{
public static void Register(IServiceCollection services) {
services.AddScoped<IAdministratorsRepository, AdministratorsRepository>();
services.AddScoped<IBookmarksRepository, BookmarksRepository>();
services.AddScoped<ICommentsRepository, CommentsRepository>();
services.AddScoped<IFollowersRepository, FollowersRepository>();
services.AddScoped<ILikesRepository, LikesRepository>();
services.AddScoped<ILocationsRepository, LocationsRepository>();
services.AddScoped<IPostsRepository, PostsRepository>();
services.AddScoped<IReportsRepository, ReportsRepository>();
services.AddScoped<ITagsRepository, TagsRepository>();
}
}
}
``` |
23de6fd8-f514-466d-b2a3-efc0e240ecce | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facile.Core
{
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
```
Add documentation and remove unused using statements | ```c#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Facile.Core
{
/// <summary>
/// Defines the result of a command's execution
/// </summary>
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
/// <summary>
/// Defines the result of a command's execution and returns a value of T
/// </summary>
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
``` |
00471aa4-0f4b-4664-9e80-fb0b69414d09 | {
"language": "C#"
} | ```c#
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
```
Add TODO to handle serialization for null key | ```c#
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO Need to not include key in serialization when its null to allow mb to use self-signed certificate.
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
``` |
e11e952c-fd67-4ff4-b04c-ec74c8b52bb9 | {
"language": "C#"
} | ```c#
using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).ToArray().FirstOrDefault();
}
}
}
}
```
Remove a redundant ToArray call | ```c#
using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
// IQueryable.FirstOrDefault では不正な SQL 文が発行される
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).AsEnumerable().FirstOrDefault();
}
}
}
}
``` |
ce185d3d-81d7-44fc-a1ae-a98def28a650 | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using NUnit.Framework;
using RestSharp.Tests.Shared.Fixtures;
namespace RestSharp.IntegrationTests
{
[TestFixture]
public class ProxyTests
{
class RequestBodyCapturer
{
public const string RESOURCE = "Capture";
}
[Test]
public void Set_Invalid_Proxy_Fails()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var client = new RestClient(server.Url) {Proxy = new WebProxy("non_existent_proxy", false)};
var request = new RestRequest();
const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
request.AddParameter(contentType, bodyData, ParameterType.RequestBody);
var response = client.Get(request);
Assert.False(response.IsSuccessful);
Assert.IsInstanceOf<WebException>(response.ErrorException);
}
[Test]
public void Set_Invalid_Proxy_Fails_RAW()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var requestUri = new Uri(new Uri(server.Url), "");
var webRequest = (HttpWebRequest) WebRequest.Create(requestUri);
webRequest.Proxy = new WebProxy("non_existent_proxy", false);
Assert.Throws<WebException>(() => webRequest.GetResponse());
}
}
}```
Fix the proxy test, why the body was even there? | ```c#
using System;
using System.Net;
using NUnit.Framework;
using RestSharp.Tests.Shared.Fixtures;
namespace RestSharp.IntegrationTests
{
[TestFixture]
public class ProxyTests
{
[Test]
public void Set_Invalid_Proxy_Fails()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var client = new RestClient(server.Url) {Proxy = new WebProxy("non_existent_proxy", false)};
var request = new RestRequest();
var response = client.Get(request);
Assert.False(response.IsSuccessful);
Assert.IsInstanceOf<WebException>(response.ErrorException);
}
[Test]
public void Set_Invalid_Proxy_Fails_RAW()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var requestUri = new Uri(new Uri(server.Url), "");
var webRequest = (HttpWebRequest) WebRequest.Create(requestUri);
webRequest.Proxy = new WebProxy("non_existent_proxy", false);
Assert.Throws<WebException>(() => webRequest.GetResponse());
}
}
}``` |
6c266bd6-a08b-4409-a776-6c60124bfe5e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
namespace VstsMetrics.Commands.CycleTime
{
public static class WorkItemCycleTimeExtensions
{
public static IEnumerable<WorkItemCycleTimeSummary> Summarise(this IEnumerable<WorkItemCycleTime> cycleTimes)
{
var elapsedAverage = cycleTimes.Average(ct => ct.ElapsedCycleTimeInHours);
var workingAverage = cycleTimes.Average(ct => ct.ApproximateWorkingCycleTimeInHours);
var elapsedMoe = cycleTimes.MarginOfError(ct => ct.ElapsedCycleTimeInHours);
var workingMoe = cycleTimes.MarginOfError(ct => ct.ApproximateWorkingCycleTimeInHours);
return new[] {
new WorkItemCycleTimeSummary("Elapsed", elapsedAverage, elapsedMoe),
new WorkItemCycleTimeSummary("Approximate Working Time", workingAverage, workingMoe)
};
}
private static double MarginOfError(this IEnumerable<WorkItemCycleTime> cycleTimes, Func<WorkItemCycleTime, double> getter)
{
// http://www.dummies.com/education/math/statistics/how-to-calculate-the-margin-of-error-for-a-sample-mean/
return cycleTimes.Select(getter).PopulationStandardDeviation()
/ Math.Sqrt(cycleTimes.Count())
* 1.96;
}
}
}```
Add a comment about when the MoE calculation will be wrong. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
namespace VstsMetrics.Commands.CycleTime
{
public static class WorkItemCycleTimeExtensions
{
public static IEnumerable<WorkItemCycleTimeSummary> Summarise(this IEnumerable<WorkItemCycleTime> cycleTimes)
{
var elapsedAverage = cycleTimes.Average(ct => ct.ElapsedCycleTimeInHours);
var workingAverage = cycleTimes.Average(ct => ct.ApproximateWorkingCycleTimeInHours);
var elapsedMoe = cycleTimes.MarginOfError(ct => ct.ElapsedCycleTimeInHours);
var workingMoe = cycleTimes.MarginOfError(ct => ct.ApproximateWorkingCycleTimeInHours);
return new[] {
new WorkItemCycleTimeSummary("Elapsed", elapsedAverage, elapsedMoe),
new WorkItemCycleTimeSummary("Approximate Working Time", workingAverage, workingMoe)
};
}
private static double MarginOfError(this IEnumerable<WorkItemCycleTime> cycleTimes, Func<WorkItemCycleTime, double> getter)
{
// http://www.dummies.com/education/math/statistics/how-to-calculate-the-margin-of-error-for-a-sample-mean/
// If the central limit theorem does not apply, then this will be incorrect. This should be exposed somehow at some point.
return cycleTimes.Select(getter).PopulationStandardDeviation()
/ Math.Sqrt(cycleTimes.Count())
* 1.96;
}
}
}``` |
c1ff7bb6-12b5-480f-af1a-8966bcf26f31 | {
"language": "C#"
} | ```c#
#if HAS_SPAN
#nullable enable
using NBitcoin.Secp256k1.Musig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace NBitcoin.Secp256k1
{
#if SECP256K1_LIB
public
#endif
class MusigPartialSignature
{
#if SECP256K1_LIB
public
#else
internal
#endif
readonly Scalar E;
public MusigPartialSignature(Scalar e)
{
this.E = e;
}
public MusigPartialSignature(ReadOnlySpan<byte> in32)
{
this.E = new Scalar(in32, out var overflow);
if (overflow != 0)
throw new ArgumentOutOfRangeException(nameof(in32), "in32 is overflowing");
}
public void WriteToSpan(Span<byte> in32)
{
E.WriteToSpan(in32);
}
public byte[] ToBytes()
{
byte[] b = new byte[32];
WriteToSpan(b);
return b;
}
}
}
#endif
```
Move musig class in the musig namespace | ```c#
#if HAS_SPAN
#nullable enable
using NBitcoin.Secp256k1.Musig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace NBitcoin.Secp256k1.Musig
{
#if SECP256K1_LIB
public
#endif
class MusigPartialSignature
{
#if SECP256K1_LIB
public
#else
internal
#endif
readonly Scalar E;
public MusigPartialSignature(Scalar e)
{
this.E = e;
}
public MusigPartialSignature(ReadOnlySpan<byte> in32)
{
this.E = new Scalar(in32, out var overflow);
if (overflow != 0)
throw new ArgumentOutOfRangeException(nameof(in32), "in32 is overflowing");
}
public void WriteToSpan(Span<byte> in32)
{
E.WriteToSpan(in32);
}
public byte[] ToBytes()
{
byte[] b = new byte[32];
WriteToSpan(b);
return b;
}
}
}
#endif
``` |
f8e2f772-4b0c-4d09-b96e-5137a857ecb8 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.Adjust");
}
ajcAdjustImei.CallStatic("readImei");
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.Adjust");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
```
Fix native AdjustImei class path | ```c#
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("readImei");
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
``` |
59e8b85c-135e-46ab-a359-a12e0dcb1103 | {
"language": "C#"
} | ```c#
namespace StyleCop.Analyzers.Status.Generator
{
using System;
using System.IO;
using LibGit2Sharp;
using Newtonsoft.Json;
/// <summary>
/// The starting point of this application.
/// </summary>
internal class Program
{
/// <summary>
/// The starting point of this application.
/// </summary>
/// <param name="args">The command line parameters.</param>
internal static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to sln file required.");
return;
}
SolutionReader reader = SolutionReader.CreateAsync(args[0]).Result;
var diagnostics = reader.GetDiagnosticsAsync().Result;
string commitId;
using (Repository repository = new Repository(Path.GetDirectoryName(args[0])))
{
commitId = repository.Head.Tip.Sha;
}
var output = new
{
diagnostics,
commitId
};
Console.WriteLine(JsonConvert.SerializeObject(output));
}
}
}
```
Include git information in json file | ```c#
namespace StyleCop.Analyzers.Status.Generator
{
using System;
using System.IO;
using System.Linq;
using LibGit2Sharp;
using Newtonsoft.Json;
/// <summary>
/// The starting point of this application.
/// </summary>
internal class Program
{
/// <summary>
/// The starting point of this application.
/// </summary>
/// <param name="args">The command line parameters.</param>
internal static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to sln file required.");
return;
}
SolutionReader reader = SolutionReader.CreateAsync(args[0]).Result;
var diagnostics = reader.GetDiagnosticsAsync().Result;
Commit commit;
string commitId;
using (Repository repository = new Repository(Path.GetDirectoryName(args[0])))
{
commitId = repository.Head.Tip.Sha;
commit = repository.Head.Tip;
var output = new
{
diagnostics,
git = new
{
commit.Sha,
commit.Message,
commit.Author,
commit.Committer,
Parents = commit.Parents.Select(x => x.Sha)
}
};
Console.WriteLine(JsonConvert.SerializeObject(output));
}
}
}
}
``` |
113e1a0d-58e2-4ce9-a7de-97bcd9c87cfe | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: AssemblyDescription("Autofac WCF Integration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Wcf, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
```
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;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Wcf, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
``` |
76781453-1119-429d-8295-67d6c190c9ea | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Gigobyte.Daterpillar.Compare
{
public class ComparisonReport
{
public Counter Counters;
public Outcome Summary { get; set; }
public IList<Discrepancy> Discrepancies { get; set; }
public struct Counter
{
public int SourceTables;
public int DestTables;
}
}
}```
Add data contract attributes to ComparisionReport.cs | ```c#
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Gigobyte.Daterpillar.Compare
{
[DataContract]
public class ComparisonReport : IEnumerable<Discrepancy>
{
public Counter Counters;
[DataMember]
public Outcome Summary { get; set; }
[DataMember]
public IList<Discrepancy> Discrepancies { get; set; }
public IEnumerator<Discrepancy> GetEnumerator()
{
foreach (var item in Discrepancies) { yield return item; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Counter
{
public int SourceTables;
public int DestTables;
}
}
}``` |
a2cacfd9-27fb-46ac-bd8b-47f491eaf48b | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
using Toggl.Phoebe.Bugsnag.Json;
using System.Collections.Generic;
namespace Toggl.Phoebe.Bugsnag.Data
{
[JsonObject (MemberSerialization.OptIn)]
public class Event
{
[JsonProperty ("user", DefaultValueHandling = DefaultValueHandling.Ignore)]
public UserInfo User { get; set; }
[JsonProperty ("app")]
public ApplicationInfo App { get; set; }
[JsonProperty ("appState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ApplicationState AppState { get; set; }
[JsonProperty ("device", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemInfo System { get; set; }
[JsonProperty ("deviceState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemState SystemState { get; set; }
[JsonProperty ("context")]
public string Context { get; set; }
[JsonProperty ("severity"), JsonConverter (typeof(ErrorSeverityConverter))]
public ErrorSeverity Severity { get; set; }
[JsonProperty ("exceptions")]
public List<ExceptionInfo> Exceptions { get; set; }
[JsonProperty ("metadata")]
public Metadata Metadata { get; set; }
}
}
```
Fix metaData JSON property name case. | ```c#
using System;
using Newtonsoft.Json;
using Toggl.Phoebe.Bugsnag.Json;
using System.Collections.Generic;
namespace Toggl.Phoebe.Bugsnag.Data
{
[JsonObject (MemberSerialization.OptIn)]
public class Event
{
[JsonProperty ("user", DefaultValueHandling = DefaultValueHandling.Ignore)]
public UserInfo User { get; set; }
[JsonProperty ("app")]
public ApplicationInfo App { get; set; }
[JsonProperty ("appState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ApplicationState AppState { get; set; }
[JsonProperty ("device", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemInfo System { get; set; }
[JsonProperty ("deviceState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemState SystemState { get; set; }
[JsonProperty ("context")]
public string Context { get; set; }
[JsonProperty ("severity"), JsonConverter (typeof(ErrorSeverityConverter))]
public ErrorSeverity Severity { get; set; }
[JsonProperty ("exceptions")]
public List<ExceptionInfo> Exceptions { get; set; }
[JsonProperty ("metaData")]
public Metadata Metadata { get; set; }
}
}
``` |
c7e4df80-dd88-46d4-8079-53a0f56cf0cf | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
namespace Plexo
{
[DataContract]
public class Currency
{
[DataMember]
public int CurrencyId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Plural { get; set; }
[DataMember]
public string Symbol { get; set; }
//Mercury Id is for internal use, no serialization required
public int MercuryId { get; set; }
}
}```
Make sure MercuryId do not get serialized. | ```c#
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Plexo
{
[DataContract]
public class Currency
{
[DataMember]
public int CurrencyId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Plural { get; set; }
[DataMember]
public string Symbol { get; set; }
//Mercury Id is for internal use, no serialization required
[JsonIgnore]
public int MercuryId { get; set; }
}
}``` |
9bc5dadf-3691-494f-949e-593e8780b4da | {
"language": "C#"
} | ```c#
namespace GraphQL.Types
{
public interface INamedType
{
string Name { get; set; }
}
public interface IGraphType : IProvideMetadata, INamedType
{
string Description { get; set; }
string DeprecationReason { get; set; }
string CollectTypes(TypeCollectionContext context);
}
public interface IOutputGraphType : IGraphType
{
}
public interface IInputGraphType : IGraphType
{
}
}
```
Remove input/output interfaces for now | ```c#
namespace GraphQL.Types
{
public interface INamedType
{
string Name { get; set; }
}
public interface IGraphType : IProvideMetadata, INamedType
{
string Description { get; set; }
string DeprecationReason { get; set; }
string CollectTypes(TypeCollectionContext context);
}
}
``` |
0ea1cb5f-4c01-4378-ad81-d40b57b8f276 | {
"language": "C#"
} | ```c#
using JetBrains.TextControl.DocumentMarkup;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon.Attributes
{
[RegisterHighlighter(GUID_REFERENCE_TOOLTIP, EffectType = EffectType.TEXT)]
public static class AsmDefHighlightingAttributeIds
{
public const string GUID_REFERENCE_TOOLTIP = "ReSharper AsmDef GUID Reference Tooltip";
}
}```
Fix registration of tooltip only highlighter | ```c#
using JetBrains.TextControl.DocumentMarkup;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon.Attributes
{
// Rider doesn't support an empty set of attributes (all the implementations of IRiderHighlighterModelCreator
// return null), so we must define something. If we define an EffectType, ReSharper throws if we don't define it
// properly. But this is just a tooltip, and should have EffectType.NONE. So define one dummy attribute, this keeps
// both Rider and ReSharper happy
[RegisterHighlighter(GUID_REFERENCE_TOOLTIP, FontFamily = "Unused")]
public static class AsmDefHighlightingAttributeIds
{
public const string GUID_REFERENCE_TOOLTIP = "ReSharper AsmDef GUID Reference Tooltip";
}
}``` |
f4eb061a-6591-4b26-9876-684e59081768 | {
"language": "C#"
} | ```c#
// The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow
{
public sealed class MetadataKeys
{
public const string EventName = "event_name";
public const string EventVersion = "event_version";
public const string Timestamp = "timestamp";
public const string AggregateSequenceNumber = "global_sequence_number";
}
}
```
Fix metadata key, its the aggregate sequence number not the global one | ```c#
// The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow
{
public sealed class MetadataKeys
{
public const string EventName = "event_name";
public const string EventVersion = "event_version";
public const string Timestamp = "timestamp";
public const string AggregateSequenceNumber = "aggregate_sequence_number";
}
}
``` |
f724a718-7ad2-4444-8ae7-031621783ac9 | {
"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.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public abstract class CatchSelectionBlueprint<THitObject> : HitObjectSelectionBlueprint<THitObject>
where THitObject : CatchHitObject
{
public override Vector2 ScreenSpaceSelectionPoint
{
get
{
float x = HitObject.OriginalX;
float y = HitObjectContainer.PositionAtTime(HitObject.StartTime);
return HitObjectContainer.ToScreenSpace(new Vector2(x, y + HitObjectContainer.DrawHeight));
}
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => SelectionQuad.Contains(screenSpacePos);
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
protected CatchSelectionBlueprint(THitObject hitObject)
: base(hitObject)
{
}
}
}
```
Fix catch selection blueprint not displayed after copy-pasted | ```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.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public abstract class CatchSelectionBlueprint<THitObject> : HitObjectSelectionBlueprint<THitObject>
where THitObject : CatchHitObject
{
protected override bool AlwaysShowWhenSelected => true;
public override Vector2 ScreenSpaceSelectionPoint
{
get
{
float x = HitObject.OriginalX;
float y = HitObjectContainer.PositionAtTime(HitObject.StartTime);
return HitObjectContainer.ToScreenSpace(new Vector2(x, y + HitObjectContainer.DrawHeight));
}
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => SelectionQuad.Contains(screenSpacePos);
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
protected CatchSelectionBlueprint(THitObject hitObject)
: base(hitObject)
{
}
}
}
``` |
e6b3bec1-917c-4dfe-b4b9-6490da7420db | {
"language": "C#"
} | ```c#
using System;
namespace Cake.Xamarin.Build
{
[Flags]
public enum BuildPlatforms
{
Mac = 0,
Windows = 1,
Linux = 2
}
}
```
Fix flags (Mac shouldn't be 0 based) | ```c#
using System;
namespace Cake.Xamarin.Build
{
[Flags]
public enum BuildPlatforms
{
Mac = 1,
Windows = 2,
Linux = 4
}
}
``` |
45b183b4-dced-4d28-9bb7-59359edc6bc5 | {
"language": "C#"
} | ```c#
using System.IO;
using System.IO.Compression;
using System.Web;
namespace Kudu.Services
{
public static class HttpRequestExtensions
{
public static Stream GetInputStream(this HttpRequestBase request)
{
var contentEncoding = request.Headers["Content-Encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip"))
{
return new GZipStream(request.InputStream, CompressionMode.Decompress);
}
return request.InputStream;
}
}
}
```
Use bufferless stream to improve perf and resource usage | ```c#
using System.IO;
using System.IO.Compression;
using System.Web;
namespace Kudu.Services
{
public static class HttpRequestExtensions
{
public static Stream GetInputStream(this HttpRequestBase request)
{
var contentEncoding = request.Headers["Content-Encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip"))
{
return new GZipStream(request.GetBufferlessInputStream(), CompressionMode.Decompress);
}
return request.GetBufferlessInputStream();
}
}
}
``` |
8c05fe73-a778-42d9-b177-af43827a6f72 | {
"language": "C#"
} | ```c#
using System.Diagnostics.Tracing;
using Glimpse.Agent.AspNet.Mvc;
using Glimpse.Agent.Web;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.FunctionalTest.Website
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGlimpse()
.RunningAgentWeb()
.RunningServerWeb()
.WithLocalAgent();
services.AddMvc();
services.AddTransient<MvcTelemetryListener>();
}
public void Configure(IApplicationBuilder app)
{
var telemetryListener = app.ApplicationServices.GetRequiredService<TelemetryListener>();
telemetryListener.SubscribeWithAdapter(app.ApplicationServices.GetRequiredService<MvcTelemetryListener>());
app.UseGlimpseServer();
app.UseGlimpseAgent();
app.UseMvcWithDefaultRoute();
}
}
}
```
Remove need for function test to register telemetry source | ```c#
using System.Diagnostics.Tracing;
using Glimpse.Agent.AspNet.Mvc;
using Glimpse.Agent.Web;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.FunctionalTest.Website
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGlimpse()
.RunningAgentWeb()
.RunningServerWeb()
.WithLocalAgent();
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseGlimpseServer();
app.UseGlimpseAgent();
app.UseMvcWithDefaultRoute();
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.